repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
AlignShift | AlignShift-master/mmdet/models/backbones/resnext.py | import math
import torch.nn as nn
from mmdet.ops import DeformConv, ModulatedDeformConv
from ..registry import BACKBONES
from ..utils import build_conv_layer, build_norm_layer
from .resnet import Bottleneck as _Bottleneck
from .resnet import ResNet
class Bottleneck(_Bottleneck):
def __init__(self, inplanes, planes, groups=1, base_width=4, **kwargs):
"""Bottleneck block for ResNeXt.
If style is "pytorch", the stride-two layer is the 3x3 conv layer,
if it is "caffe", the stride-two layer is the first 1x1 conv layer.
"""
super(Bottleneck, self).__init__(inplanes, planes, **kwargs)
if groups == 1:
width = self.planes
else:
width = math.floor(self.planes * (base_width / 64)) * groups
self.norm1_name, norm1 = build_norm_layer(
self.norm_cfg, width, postfix=1)
self.norm2_name, norm2 = build_norm_layer(
self.norm_cfg, width, postfix=2)
self.norm3_name, norm3 = build_norm_layer(
self.norm_cfg, self.planes * self.expansion, postfix=3)
self.conv1 = build_conv_layer(
self.conv_cfg,
self.inplanes,
width,
kernel_size=1,
stride=self.conv1_stride,
bias=False)
self.add_module(self.norm1_name, norm1)
fallback_on_stride = False
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = self.dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = self.dcn.get('modulated', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = build_conv_layer(
self.conv_cfg,
width,
width,
kernel_size=3,
stride=self.conv2_stride,
padding=self.dilation,
dilation=self.dilation,
groups=groups,
bias=False)
else:
assert self.conv_cfg is None, 'conv_cfg must be None for DCN'
groups = self.dcn.get('groups', 1)
deformable_groups = self.dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
conv_op = DeformConv
offset_channels = 18
else:
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
width,
deformable_groups * offset_channels,
kernel_size=3,
stride=self.conv2_stride,
padding=self.dilation,
dilation=self.dilation)
self.conv2 = conv_op(
width,
width,
kernel_size=3,
stride=self.conv2_stride,
padding=self.dilation,
dilation=self.dilation,
groups=groups,
deformable_groups=deformable_groups,
bias=False)
self.add_module(self.norm2_name, norm2)
self.conv3 = build_conv_layer(
self.conv_cfg,
width,
self.planes * self.expansion,
kernel_size=1,
bias=False)
self.add_module(self.norm3_name, norm3)
def make_res_layer(block,
inplanes,
planes,
blocks,
stride=1,
dilation=1,
groups=1,
base_width=4,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
dcn=None,
gcb=None):
downsample = None
if stride != 1 or inplanes != planes * block.expansion:
downsample = nn.Sequential(
build_conv_layer(
conv_cfg,
inplanes,
planes * block.expansion,
kernel_size=1,
stride=stride,
bias=False),
build_norm_layer(norm_cfg, planes * block.expansion)[1],
)
layers = []
layers.append(
block(
inplanes=inplanes,
planes=planes,
stride=stride,
dilation=dilation,
downsample=downsample,
groups=groups,
base_width=base_width,
style=style,
with_cp=with_cp,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
dcn=dcn,
gcb=gcb))
inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(
block(
inplanes=inplanes,
planes=planes,
stride=1,
dilation=dilation,
groups=groups,
base_width=base_width,
style=style,
with_cp=with_cp,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
dcn=dcn,
gcb=gcb))
return nn.Sequential(*layers)
@BACKBONES.register_module
class ResNeXt(ResNet):
"""ResNeXt backbone.
Args:
depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.
in_channels (int): Number of input image channels. Normally 3.
num_stages (int): Resnet stages, normally 4.
groups (int): Group of resnext.
base_width (int): Base width of resnext.
strides (Sequence[int]): Strides of the first block of each stage.
dilations (Sequence[int]): Dilation of each stage.
out_indices (Sequence[int]): Output from which stages.
style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
layer is the 3x3 conv layer, otherwise the stride-two layer is
the first 1x1 conv layer.
frozen_stages (int): Stages to be frozen (all param fixed). -1 means
not freezing any parameters.
norm_cfg (dict): dictionary to construct and config norm layer.
norm_eval (bool): Whether to set norm layers to eval mode, namely,
freeze running stats (mean and var). Note: Effect on Batch Norm
and its variants only.
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
memory while slowing down the training speed.
zero_init_residual (bool): whether to use zero init for last norm layer
in resblocks to let them behave as identity.
Example:
>>> from mmdet.models import ResNeXt
>>> import torch
>>> self = ResNeXt(depth=50)
>>> self.eval()
>>> inputs = torch.rand(1, 3, 32, 32)
>>> level_outputs = self.forward(inputs)
>>> for level_out in level_outputs:
... print(tuple(level_out.shape))
(1, 256, 8, 8)
(1, 512, 4, 4)
(1, 1024, 2, 2)
(1, 2048, 1, 1)
"""
arch_settings = {
50: (Bottleneck, (3, 4, 6, 3)),
101: (Bottleneck, (3, 4, 23, 3)),
152: (Bottleneck, (3, 8, 36, 3))
}
def __init__(self, groups=1, base_width=4, **kwargs):
super(ResNeXt, self).__init__(**kwargs)
self.groups = groups
self.base_width = base_width
self.inplanes = 64
self.res_layers = []
for i, num_blocks in enumerate(self.stage_blocks):
stride = self.strides[i]
dilation = self.dilations[i]
dcn = self.dcn if self.stage_with_dcn[i] else None
gcb = self.gcb if self.stage_with_gcb[i] else None
planes = 64 * 2**i
res_layer = make_res_layer(
self.block,
self.inplanes,
planes,
num_blocks,
stride=stride,
dilation=dilation,
groups=self.groups,
base_width=self.base_width,
style=self.style,
with_cp=self.with_cp,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
dcn=dcn,
gcb=gcb)
self.inplanes = planes * self.block.expansion
layer_name = 'layer{}'.format(i + 1)
self.add_module(layer_name, res_layer)
self.res_layers.append(layer_name)
self._freeze_stages()
| 8,336 | 33.882845 | 79 | py |
AlignShift | AlignShift-master/mmdet/models/mask_heads/grid_head.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import kaiming_init, normal_init
from ..builder import build_loss
from ..registry import HEADS
from ..utils import ConvModule
@HEADS.register_module
class GridHead(nn.Module):
def __init__(self,
grid_points=9,
num_convs=8,
roi_feat_size=14,
in_channels=256,
conv_kernel_size=3,
point_feat_channels=64,
deconv_kernel_size=4,
class_agnostic=False,
loss_grid=dict(
type='CrossEntropyLoss', use_sigmoid=True,
loss_weight=15),
conv_cfg=None,
norm_cfg=dict(type='GN', num_groups=36)):
super(GridHead, self).__init__()
self.grid_points = grid_points
self.num_convs = num_convs
self.roi_feat_size = roi_feat_size
self.in_channels = in_channels
self.conv_kernel_size = conv_kernel_size
self.point_feat_channels = point_feat_channels
self.conv_out_channels = self.point_feat_channels * self.grid_points
self.class_agnostic = class_agnostic
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
if isinstance(norm_cfg, dict) and norm_cfg['type'] == 'GN':
assert self.conv_out_channels % norm_cfg['num_groups'] == 0
assert self.grid_points >= 4
self.grid_size = int(np.sqrt(self.grid_points))
if self.grid_size * self.grid_size != self.grid_points:
raise ValueError('grid_points must be a square number')
# the predicted heatmap is half of whole_map_size
if not isinstance(self.roi_feat_size, int):
raise ValueError('Only square RoIs are supporeted in Grid R-CNN')
self.whole_map_size = self.roi_feat_size * 4
# compute point-wise sub-regions
self.sub_regions = self.calc_sub_regions()
self.convs = []
for i in range(self.num_convs):
in_channels = (
self.in_channels if i == 0 else self.conv_out_channels)
stride = 2 if i == 0 else 1
padding = (self.conv_kernel_size - 1) // 2
self.convs.append(
ConvModule(
in_channels,
self.conv_out_channels,
self.conv_kernel_size,
stride=stride,
padding=padding,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
bias=True))
self.convs = nn.Sequential(*self.convs)
self.deconv1 = nn.ConvTranspose2d(
self.conv_out_channels,
self.conv_out_channels,
kernel_size=deconv_kernel_size,
stride=2,
padding=(deconv_kernel_size - 2) // 2,
groups=grid_points)
self.norm1 = nn.GroupNorm(grid_points, self.conv_out_channels)
self.deconv2 = nn.ConvTranspose2d(
self.conv_out_channels,
grid_points,
kernel_size=deconv_kernel_size,
stride=2,
padding=(deconv_kernel_size - 2) // 2,
groups=grid_points)
# find the 4-neighbor of each grid point
self.neighbor_points = []
grid_size = self.grid_size
for i in range(grid_size): # i-th column
for j in range(grid_size): # j-th row
neighbors = []
if i > 0: # left: (i - 1, j)
neighbors.append((i - 1) * grid_size + j)
if j > 0: # up: (i, j - 1)
neighbors.append(i * grid_size + j - 1)
if j < grid_size - 1: # down: (i, j + 1)
neighbors.append(i * grid_size + j + 1)
if i < grid_size - 1: # right: (i + 1, j)
neighbors.append((i + 1) * grid_size + j)
self.neighbor_points.append(tuple(neighbors))
# total edges in the grid
self.num_edges = sum([len(p) for p in self.neighbor_points])
self.forder_trans = nn.ModuleList() # first-order feature transition
self.sorder_trans = nn.ModuleList() # second-order feature transition
for neighbors in self.neighbor_points:
fo_trans = nn.ModuleList()
so_trans = nn.ModuleList()
for _ in range(len(neighbors)):
# each transition module consists of a 5x5 depth-wise conv and
# 1x1 conv.
fo_trans.append(
nn.Sequential(
nn.Conv2d(
self.point_feat_channels,
self.point_feat_channels,
5,
stride=1,
padding=2,
groups=self.point_feat_channels),
nn.Conv2d(self.point_feat_channels,
self.point_feat_channels, 1)))
so_trans.append(
nn.Sequential(
nn.Conv2d(
self.point_feat_channels,
self.point_feat_channels,
5,
1,
2,
groups=self.point_feat_channels),
nn.Conv2d(self.point_feat_channels,
self.point_feat_channels, 1)))
self.forder_trans.append(fo_trans)
self.sorder_trans.append(so_trans)
self.loss_grid = build_loss(loss_grid)
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
# TODO: compare mode = "fan_in" or "fan_out"
kaiming_init(m)
for m in self.modules():
if isinstance(m, nn.ConvTranspose2d):
normal_init(m, std=0.001)
nn.init.constant_(self.deconv2.bias, -np.log(0.99 / 0.01))
def forward(self, x):
assert x.shape[-1] == x.shape[-2] == self.roi_feat_size
# RoI feature transformation, downsample 2x
x = self.convs(x)
c = self.point_feat_channels
# first-order fusion
x_fo = [None for _ in range(self.grid_points)]
for i, points in enumerate(self.neighbor_points):
x_fo[i] = x[:, i * c:(i + 1) * c]
for j, point_idx in enumerate(points):
x_fo[i] = x_fo[i] + self.forder_trans[i][j](
x[:, point_idx * c:(point_idx + 1) * c])
# second-order fusion
x_so = [None for _ in range(self.grid_points)]
for i, points in enumerate(self.neighbor_points):
x_so[i] = x[:, i * c:(i + 1) * c]
for j, point_idx in enumerate(points):
x_so[i] = x_so[i] + self.sorder_trans[i][j](x_fo[point_idx])
# predicted heatmap with fused features
x2 = torch.cat(x_so, dim=1)
x2 = self.deconv1(x2)
x2 = F.relu(self.norm1(x2), inplace=True)
heatmap = self.deconv2(x2)
# predicted heatmap with original features (applicable during training)
if self.training:
x1 = x
x1 = self.deconv1(x1)
x1 = F.relu(self.norm1(x1), inplace=True)
heatmap_unfused = self.deconv2(x1)
else:
heatmap_unfused = heatmap
return dict(fused=heatmap, unfused=heatmap_unfused)
def calc_sub_regions(self):
"""Compute point specific representation regions.
See Grid R-CNN Plus (https://arxiv.org/abs/1906.05688) for details.
"""
# to make it consistent with the original implementation, half_size
# is computed as 2 * quarter_size, which is smaller
half_size = self.whole_map_size // 4 * 2
sub_regions = []
for i in range(self.grid_points):
x_idx = i // self.grid_size
y_idx = i % self.grid_size
if x_idx == 0:
sub_x1 = 0
elif x_idx == self.grid_size - 1:
sub_x1 = half_size
else:
ratio = x_idx / (self.grid_size - 1) - 0.25
sub_x1 = max(int(ratio * self.whole_map_size), 0)
if y_idx == 0:
sub_y1 = 0
elif y_idx == self.grid_size - 1:
sub_y1 = half_size
else:
ratio = y_idx / (self.grid_size - 1) - 0.25
sub_y1 = max(int(ratio * self.whole_map_size), 0)
sub_regions.append(
(sub_x1, sub_y1, sub_x1 + half_size, sub_y1 + half_size))
return sub_regions
def get_target(self, sampling_results, rcnn_train_cfg):
# mix all samples (across images) together.
pos_bboxes = torch.cat([res.pos_bboxes for res in sampling_results],
dim=0).cpu()
pos_gt_bboxes = torch.cat(
[res.pos_gt_bboxes for res in sampling_results], dim=0).cpu()
assert pos_bboxes.shape == pos_gt_bboxes.shape
# expand pos_bboxes to 2x of original size
x1 = pos_bboxes[:, 0] - (pos_bboxes[:, 2] - pos_bboxes[:, 0]) / 2
y1 = pos_bboxes[:, 1] - (pos_bboxes[:, 3] - pos_bboxes[:, 1]) / 2
x2 = pos_bboxes[:, 2] + (pos_bboxes[:, 2] - pos_bboxes[:, 0]) / 2
y2 = pos_bboxes[:, 3] + (pos_bboxes[:, 3] - pos_bboxes[:, 1]) / 2
pos_bboxes = torch.stack([x1, y1, x2, y2], dim=-1)
pos_bbox_ws = (pos_bboxes[:, 2] - pos_bboxes[:, 0]).unsqueeze(-1)
pos_bbox_hs = (pos_bboxes[:, 3] - pos_bboxes[:, 1]).unsqueeze(-1)
num_rois = pos_bboxes.shape[0]
map_size = self.whole_map_size
# this is not the final target shape
targets = torch.zeros((num_rois, self.grid_points, map_size, map_size),
dtype=torch.float)
# pre-compute interpolation factors for all grid points.
# the first item is the factor of x-dim, and the second is y-dim.
# for a 9-point grid, factors are like (1, 0), (0.5, 0.5), (0, 1)
factors = []
for j in range(self.grid_points):
x_idx = j // self.grid_size
y_idx = j % self.grid_size
factors.append((1 - x_idx / (self.grid_size - 1),
1 - y_idx / (self.grid_size - 1)))
radius = rcnn_train_cfg.pos_radius
radius2 = radius**2
for i in range(num_rois):
# ignore small bboxes
if (pos_bbox_ws[i] <= self.grid_size
or pos_bbox_hs[i] <= self.grid_size):
continue
# for each grid point, mark a small circle as positive
for j in range(self.grid_points):
factor_x, factor_y = factors[j]
gridpoint_x = factor_x * pos_gt_bboxes[i, 0] + (
1 - factor_x) * pos_gt_bboxes[i, 2]
gridpoint_y = factor_y * pos_gt_bboxes[i, 1] + (
1 - factor_y) * pos_gt_bboxes[i, 3]
cx = int((gridpoint_x - pos_bboxes[i, 0]) / pos_bbox_ws[i] *
map_size)
cy = int((gridpoint_y - pos_bboxes[i, 1]) / pos_bbox_hs[i] *
map_size)
for x in range(cx - radius, cx + radius + 1):
for y in range(cy - radius, cy + radius + 1):
if x >= 0 and x < map_size and y >= 0 and y < map_size:
if (x - cx)**2 + (y - cy)**2 <= radius2:
targets[i, j, y, x] = 1
# reduce the target heatmap size by a half
# proposed in Grid R-CNN Plus (https://arxiv.org/abs/1906.05688).
sub_targets = []
for i in range(self.grid_points):
sub_x1, sub_y1, sub_x2, sub_y2 = self.sub_regions[i]
sub_targets.append(targets[:, [i], sub_y1:sub_y2, sub_x1:sub_x2])
sub_targets = torch.cat(sub_targets, dim=1)
sub_targets = sub_targets.cuda()
return sub_targets
def loss(self, grid_pred, grid_targets):
loss_fused = self.loss_grid(grid_pred['fused'], grid_targets)
loss_unfused = self.loss_grid(grid_pred['unfused'], grid_targets)
loss_grid = loss_fused + loss_unfused
return dict(loss_grid=loss_grid)
def get_bboxes(self, det_bboxes, grid_pred, img_meta):
# TODO: refactoring
assert det_bboxes.shape[0] == grid_pred.shape[0]
det_bboxes = det_bboxes.cpu()
cls_scores = det_bboxes[:, [4]]
det_bboxes = det_bboxes[:, :4]
grid_pred = grid_pred.sigmoid().cpu()
R, c, h, w = grid_pred.shape
half_size = self.whole_map_size // 4 * 2
assert h == w == half_size
assert c == self.grid_points
# find the point with max scores in the half-sized heatmap
grid_pred = grid_pred.view(R * c, h * w)
pred_scores, pred_position = grid_pred.max(dim=1)
xs = pred_position % w
ys = pred_position // w
# get the position in the whole heatmap instead of half-sized heatmap
for i in range(self.grid_points):
xs[i::self.grid_points] += self.sub_regions[i][0]
ys[i::self.grid_points] += self.sub_regions[i][1]
# reshape to (num_rois, grid_points)
pred_scores, xs, ys = tuple(
map(lambda x: x.view(R, c), [pred_scores, xs, ys]))
# get expanded pos_bboxes
widths = (det_bboxes[:, 2] - det_bboxes[:, 0]).unsqueeze(-1)
heights = (det_bboxes[:, 3] - det_bboxes[:, 1]).unsqueeze(-1)
x1 = (det_bboxes[:, 0, None] - widths / 2)
y1 = (det_bboxes[:, 1, None] - heights / 2)
# map the grid point to the absolute coordinates
abs_xs = (xs.float() + 0.5) / w * widths + x1
abs_ys = (ys.float() + 0.5) / h * heights + y1
# get the grid points indices that fall on the bbox boundaries
x1_inds = [i for i in range(self.grid_size)]
y1_inds = [i * self.grid_size for i in range(self.grid_size)]
x2_inds = [
self.grid_points - self.grid_size + i
for i in range(self.grid_size)
]
y2_inds = [(i + 1) * self.grid_size - 1 for i in range(self.grid_size)]
# voting of all grid points on some boundary
bboxes_x1 = (abs_xs[:, x1_inds] * pred_scores[:, x1_inds]).sum(
dim=1, keepdim=True) / (
pred_scores[:, x1_inds].sum(dim=1, keepdim=True))
bboxes_y1 = (abs_ys[:, y1_inds] * pred_scores[:, y1_inds]).sum(
dim=1, keepdim=True) / (
pred_scores[:, y1_inds].sum(dim=1, keepdim=True))
bboxes_x2 = (abs_xs[:, x2_inds] * pred_scores[:, x2_inds]).sum(
dim=1, keepdim=True) / (
pred_scores[:, x2_inds].sum(dim=1, keepdim=True))
bboxes_y2 = (abs_ys[:, y2_inds] * pred_scores[:, y2_inds]).sum(
dim=1, keepdim=True) / (
pred_scores[:, y2_inds].sum(dim=1, keepdim=True))
bbox_res = torch.cat(
[bboxes_x1, bboxes_y1, bboxes_x2, bboxes_y2, cls_scores], dim=1)
bbox_res[:, [0, 2]].clamp_(min=0, max=img_meta[0]['img_shape'][1] - 1)
bbox_res[:, [1, 3]].clamp_(min=0, max=img_meta[0]['img_shape'][0] - 1)
return bbox_res
| 15,429 | 41.624309 | 79 | py |
AlignShift | AlignShift-master/mmdet/models/mask_heads/maskiou_head.py | import numpy as np
import torch
import torch.nn as nn
from mmcv.cnn import kaiming_init, normal_init
from torch.nn.modules.utils import _pair
from mmdet.core import force_fp32
from ..builder import build_loss
from ..registry import HEADS
@HEADS.register_module
class MaskIoUHead(nn.Module):
"""Mask IoU Head.
This head predicts the IoU of predicted masks and corresponding gt masks.
"""
def __init__(self,
num_convs=4,
num_fcs=2,
roi_feat_size=14,
in_channels=256,
conv_out_channels=256,
fc_out_channels=1024,
num_classes=81,
loss_iou=dict(type='MSELoss', loss_weight=0.5)):
super(MaskIoUHead, self).__init__()
self.in_channels = in_channels
self.conv_out_channels = conv_out_channels
self.fc_out_channels = fc_out_channels
self.num_classes = num_classes
self.fp16_enabled = False
self.convs = nn.ModuleList()
for i in range(num_convs):
if i == 0:
# concatenation of mask feature and mask prediction
in_channels = self.in_channels + 1
else:
in_channels = self.conv_out_channels
stride = 2 if i == num_convs - 1 else 1
self.convs.append(
nn.Conv2d(
in_channels,
self.conv_out_channels,
3,
stride=stride,
padding=1))
roi_feat_size = _pair(roi_feat_size)
pooled_area = (roi_feat_size[0] // 2) * (roi_feat_size[1] // 2)
self.fcs = nn.ModuleList()
for i in range(num_fcs):
in_channels = (
self.conv_out_channels *
pooled_area if i == 0 else self.fc_out_channels)
self.fcs.append(nn.Linear(in_channels, self.fc_out_channels))
self.fc_mask_iou = nn.Linear(self.fc_out_channels, self.num_classes)
self.relu = nn.ReLU()
self.max_pool = nn.MaxPool2d(2, 2)
self.loss_iou = build_loss(loss_iou)
def init_weights(self):
for conv in self.convs:
kaiming_init(conv)
for fc in self.fcs:
kaiming_init(
fc,
a=1,
mode='fan_in',
nonlinearity='leaky_relu',
distribution='uniform')
normal_init(self.fc_mask_iou, std=0.01)
def forward(self, mask_feat, mask_pred):
mask_pred = mask_pred.sigmoid()
mask_pred_pooled = self.max_pool(mask_pred.unsqueeze(1))
x = torch.cat((mask_feat, mask_pred_pooled), 1)
for conv in self.convs:
x = self.relu(conv(x))
x = x.view(x.size(0), -1)
for fc in self.fcs:
x = self.relu(fc(x))
mask_iou = self.fc_mask_iou(x)
return mask_iou
@force_fp32(apply_to=('mask_iou_pred', ))
def loss(self, mask_iou_pred, mask_iou_targets):
pos_inds = mask_iou_targets > 0
if pos_inds.sum() > 0:
loss_mask_iou = self.loss_iou(mask_iou_pred[pos_inds],
mask_iou_targets[pos_inds])
else:
loss_mask_iou = mask_iou_pred * 0
return dict(loss_mask_iou=loss_mask_iou)
@force_fp32(apply_to=('mask_pred', ))
def get_target(self, sampling_results, gt_masks, mask_pred, mask_targets,
rcnn_train_cfg):
"""Compute target of mask IoU.
Mask IoU target is the IoU of the predicted mask (inside a bbox) and
the gt mask of corresponding gt mask (the whole instance).
The intersection area is computed inside the bbox, and the gt mask area
is computed with two steps, firstly we compute the gt area inside the
bbox, then divide it by the area ratio of gt area inside the bbox and
the gt area of the whole instance.
Args:
sampling_results (list[:obj:`SamplingResult`]): sampling results.
gt_masks (list[ndarray]): Gt masks (the whole instance) of each
image, binary maps with the same shape of the input image.
mask_pred (Tensor): Predicted masks of each positive proposal,
shape (num_pos, h, w).
mask_targets (Tensor): Gt mask of each positive proposal,
binary map of the shape (num_pos, h, w).
rcnn_train_cfg (dict): Training config for R-CNN part.
Returns:
Tensor: mask iou target (length == num positive).
"""
pos_proposals = [res.pos_bboxes for res in sampling_results]
pos_assigned_gt_inds = [
res.pos_assigned_gt_inds for res in sampling_results
]
# compute the area ratio of gt areas inside the proposals and
# the whole instance
area_ratios = map(self._get_area_ratio, pos_proposals,
pos_assigned_gt_inds, gt_masks)
area_ratios = torch.cat(list(area_ratios))
assert mask_targets.size(0) == area_ratios.size(0)
mask_pred = (mask_pred > rcnn_train_cfg.mask_thr_binary).float()
mask_pred_areas = mask_pred.sum((-1, -2))
# mask_pred and mask_targets are binary maps
overlap_areas = (mask_pred * mask_targets).sum((-1, -2))
# compute the mask area of the whole instance
gt_full_areas = mask_targets.sum((-1, -2)) / (area_ratios + 1e-7)
mask_iou_targets = overlap_areas / (
mask_pred_areas + gt_full_areas - overlap_areas)
return mask_iou_targets
def _get_area_ratio(self, pos_proposals, pos_assigned_gt_inds, gt_masks):
"""Compute area ratio of the gt mask inside the proposal and the gt
mask of the corresponding instance"""
num_pos = pos_proposals.size(0)
if num_pos > 0:
area_ratios = []
proposals_np = pos_proposals.cpu().numpy()
pos_assigned_gt_inds = pos_assigned_gt_inds.cpu().numpy()
# compute mask areas of gt instances (batch processing for speedup)
gt_instance_mask_area = gt_masks.sum((-1, -2))
for i in range(num_pos):
gt_mask = gt_masks[pos_assigned_gt_inds[i]]
# crop the gt mask inside the proposal
x1, y1, x2, y2 = proposals_np[i, :].astype(np.int32)
gt_mask_in_proposal = gt_mask[y1:y2 + 1, x1:x2 + 1]
ratio = gt_mask_in_proposal.sum() / (
gt_instance_mask_area[pos_assigned_gt_inds[i]] + 1e-7)
area_ratios.append(ratio)
area_ratios = torch.from_numpy(np.stack(area_ratios)).float().to(
pos_proposals.device)
else:
area_ratios = pos_proposals.new_zeros((0, ))
return area_ratios
@force_fp32(apply_to=('mask_iou_pred', ))
def get_mask_scores(self, mask_iou_pred, det_bboxes, det_labels):
"""Get the mask scores.
mask_score = bbox_score * mask_iou
"""
inds = range(det_labels.size(0))
mask_scores = mask_iou_pred[inds, det_labels + 1] * det_bboxes[inds,
-1]
mask_scores = mask_scores.cpu().numpy()
det_labels = det_labels.cpu().numpy()
return [
mask_scores[det_labels == i] for i in range(self.num_classes - 1)
]
| 7,453 | 38.026178 | 79 | py |
AlignShift | AlignShift-master/mmdet/models/mask_heads/fcn_mask_head.py | import mmcv
import numpy as np
import pycocotools.mask as mask_util
import torch
import torch.nn as nn
from torch.nn.modules.utils import _pair
from mmdet.core import auto_fp16, force_fp32, mask_target
from ..builder import build_loss
from ..registry import HEADS
from ..utils import ConvModule
@HEADS.register_module
class FCNMaskHead(nn.Module):
def __init__(self,
num_convs=4,
roi_feat_size=14,
in_channels=256,
conv_kernel_size=3,
conv_out_channels=256,
upsample_method='deconv',
upsample_ratio=2,
num_classes=81,
class_agnostic=False,
conv_cfg=None,
norm_cfg=None,
loss_mask=dict(
type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)):
super(FCNMaskHead, self).__init__()
if upsample_method not in [None, 'deconv', 'nearest', 'bilinear']:
raise ValueError(
'Invalid upsample method {}, accepted methods '
'are "deconv", "nearest", "bilinear"'.format(upsample_method))
self.num_convs = num_convs
# WARN: roi_feat_size is reserved and not used
self.roi_feat_size = _pair(roi_feat_size)
self.in_channels = in_channels
self.conv_kernel_size = conv_kernel_size
self.conv_out_channels = conv_out_channels
self.upsample_method = upsample_method
self.upsample_ratio = upsample_ratio
self.num_classes = num_classes
self.class_agnostic = class_agnostic
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.fp16_enabled = False
self.loss_mask = build_loss(loss_mask)
self.convs = nn.ModuleList()
for i in range(self.num_convs):
in_channels = (
self.in_channels if i == 0 else self.conv_out_channels)
padding = (self.conv_kernel_size - 1) // 2
self.convs.append(
ConvModule(
in_channels,
self.conv_out_channels,
self.conv_kernel_size,
padding=padding,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg))
upsample_in_channels = (
self.conv_out_channels if self.num_convs > 0 else in_channels)
if self.upsample_method is None:
self.upsample = None
elif self.upsample_method == 'deconv':
self.upsample = nn.ConvTranspose2d(
upsample_in_channels,
self.conv_out_channels,
self.upsample_ratio,
stride=self.upsample_ratio)
else:
self.upsample = nn.Upsample(
scale_factor=self.upsample_ratio, mode=self.upsample_method)
out_channels = 1 if self.class_agnostic else self.num_classes
logits_in_channel = (
self.conv_out_channels
if self.upsample_method == 'deconv' else upsample_in_channels)
self.conv_logits = nn.Conv2d(logits_in_channel, out_channels, 1)
self.relu = nn.ReLU(inplace=True)
self.debug_imgs = None
def init_weights(self):
for m in [self.upsample, self.conv_logits]:
if m is None:
continue
nn.init.kaiming_normal_(
m.weight, mode='fan_out', nonlinearity='relu')
nn.init.constant_(m.bias, 0)
@auto_fp16()
def forward(self, x):
for conv in self.convs:
x = conv(x)
if self.upsample is not None:
x = self.upsample(x)
if self.upsample_method == 'deconv':
x = self.relu(x)
mask_pred = self.conv_logits(x)
return mask_pred
def get_target(self, sampling_results, gt_masks, rcnn_train_cfg):
pos_proposals = [res.pos_bboxes for res in sampling_results]
pos_assigned_gt_inds = [
res.pos_assigned_gt_inds for res in sampling_results
]
mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds,
gt_masks, rcnn_train_cfg)
return mask_targets
@force_fp32(apply_to=('mask_pred', ))
def loss(self, mask_pred, mask_targets, labels):
loss = dict()
if self.class_agnostic:
loss_mask = self.loss_mask(mask_pred, mask_targets,
torch.zeros_like(labels))
else:
loss_mask = self.loss_mask(mask_pred, mask_targets, labels)
loss['loss_mask'] = loss_mask
return loss
def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg,
ori_shape, scale_factor, rescale):
"""Get segmentation masks from mask_pred and bboxes.
Args:
mask_pred (Tensor or ndarray): shape (n, #class+1, h, w).
For single-scale testing, mask_pred is the direct output of
model, whose type is Tensor, while for multi-scale testing,
it will be converted to numpy array outside of this method.
det_bboxes (Tensor): shape (n, 4/5)
det_labels (Tensor): shape (n, )
img_shape (Tensor): shape (3, )
rcnn_test_cfg (dict): rcnn testing config
ori_shape: original image size
Returns:
list[list]: encoded masks
"""
if isinstance(mask_pred, torch.Tensor):
mask_pred = mask_pred.sigmoid().cpu().numpy()
assert isinstance(mask_pred, np.ndarray)
# when enabling mixed precision training, mask_pred may be float16
# numpy array
mask_pred = mask_pred.astype(np.float32)
cls_segms = [[] for _ in range(self.num_classes - 1)]
bboxes = det_bboxes.cpu().numpy()[:, :4]
labels = det_labels.cpu().numpy() + 1
if rescale:
img_h, img_w = ori_shape[:2]
else:
img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32)
img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32)
scale_factor = 1.0
for i in range(bboxes.shape[0]):
if not isinstance(scale_factor, (float, np.ndarray)):
scale_factor = scale_factor.cpu().numpy()
bbox = (bboxes[i, :] / scale_factor).astype(np.int32)
label = labels[i]
w = max(bbox[2] - bbox[0] + 1, 1)
h = max(bbox[3] - bbox[1] + 1, 1)
if not self.class_agnostic:
mask_pred_ = mask_pred[i, label, :, :]
else:
mask_pred_ = mask_pred[i, 0, :, :]
im_mask = np.zeros((img_h, img_w), dtype=np.uint8)
bbox_mask = mmcv.imresize(mask_pred_, (w, h))
bbox_mask = (bbox_mask > rcnn_test_cfg.mask_thr_binary).astype(
np.uint8)
try:
im_mask[bbox[1]:bbox[1] + h, bbox[0]:bbox[0] + w] = bbox_mask
except:
print(f'mask erro:{(w,h)}--{bbox_mask.shape}')
rle = mask_util.encode(
np.array(im_mask[:, :, np.newaxis], order='F'))[0]
cls_segms[label - 1].append(rle)
return cls_segms
| 7,271 | 37.887701 | 79 | py |
AlignShift | AlignShift-master/mmdet/models/mask_heads/fused_semantic_head.py | import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import kaiming_init
from mmdet.core import auto_fp16, force_fp32
from ..registry import HEADS
from ..utils import ConvModule
@HEADS.register_module
class FusedSemanticHead(nn.Module):
r"""Multi-level fused semantic segmentation head.
in_1 -> 1x1 conv ---
|
in_2 -> 1x1 conv -- |
||
in_3 -> 1x1 conv - ||
||| /-> 1x1 conv (mask prediction)
in_4 -> 1x1 conv -----> 3x3 convs (*4)
| \-> 1x1 conv (feature)
in_5 -> 1x1 conv ---
""" # noqa: W605
def __init__(self,
num_ins,
fusion_level,
num_convs=4,
in_channels=256,
conv_out_channels=256,
num_classes=183,
ignore_label=255,
loss_weight=0.2,
conv_cfg=None,
norm_cfg=None):
super(FusedSemanticHead, self).__init__()
self.num_ins = num_ins
self.fusion_level = fusion_level
self.num_convs = num_convs
self.in_channels = in_channels
self.conv_out_channels = conv_out_channels
self.num_classes = num_classes
self.ignore_label = ignore_label
self.loss_weight = loss_weight
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.fp16_enabled = False
self.lateral_convs = nn.ModuleList()
for i in range(self.num_ins):
self.lateral_convs.append(
ConvModule(
self.in_channels,
self.in_channels,
1,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
inplace=False))
self.convs = nn.ModuleList()
for i in range(self.num_convs):
in_channels = self.in_channels if i == 0 else conv_out_channels
self.convs.append(
ConvModule(
in_channels,
conv_out_channels,
3,
padding=1,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg))
self.conv_embedding = ConvModule(
conv_out_channels,
conv_out_channels,
1,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg)
self.conv_logits = nn.Conv2d(conv_out_channels, self.num_classes, 1)
self.criterion = nn.CrossEntropyLoss(ignore_index=ignore_label)
def init_weights(self):
kaiming_init(self.conv_logits)
@auto_fp16()
def forward(self, feats):
x = self.lateral_convs[self.fusion_level](feats[self.fusion_level])
fused_size = tuple(x.shape[-2:])
for i, feat in enumerate(feats):
if i != self.fusion_level:
feat = F.interpolate(
feat, size=fused_size, mode='bilinear', align_corners=True)
x += self.lateral_convs[i](feat)
for i in range(self.num_convs):
x = self.convs[i](x)
mask_pred = self.conv_logits(x)
x = self.conv_embedding(x)
return mask_pred, x
@force_fp32(apply_to=('mask_pred', ))
def loss(self, mask_pred, labels):
labels = labels.squeeze(1).long()
loss_semantic_seg = self.criterion(mask_pred, labels)
loss_semantic_seg *= self.loss_weight
return loss_semantic_seg
| 3,554 | 32.224299 | 79 | py |
AlignShift | AlignShift-master/mmdet/datasets/custom.py | import os.path as osp
import mmcv
import numpy as np
from torch.utils.data import Dataset
from .pipelines import Compose
from .registry import DATASETS
@DATASETS.register_module
class CustomDataset(Dataset):
"""Custom dataset for detection.
Annotation format:
[
{
'filename': 'a.jpg',
'width': 1280,
'height': 720,
'ann': {
'bboxes': <np.ndarray> (n, 4),
'labels': <np.ndarray> (n, ),
'bboxes_ignore': <np.ndarray> (k, 4), (optional field)
'labels_ignore': <np.ndarray> (k, 4) (optional field)
}
},
...
]
The `ann` field is optional for testing.
"""
CLASSES = None
def __init__(self,
ann_file,
pipeline,
data_root=None,
img_prefix='',
seg_prefix=None,
proposal_file=None,
test_mode=False):
self.ann_file = ann_file
self.data_root = data_root
self.img_prefix = img_prefix
self.seg_prefix = seg_prefix
self.proposal_file = proposal_file
self.test_mode = test_mode
# join paths if data_root is specified
if self.data_root is not None:
if not osp.isabs(self.ann_file):
self.ann_file = osp.join(self.data_root, self.ann_file)
if not (self.img_prefix is None or osp.isabs(self.img_prefix)):
self.img_prefix = osp.join(self.data_root, self.img_prefix)
if not (self.seg_prefix is None or osp.isabs(self.seg_prefix)):
self.seg_prefix = osp.join(self.data_root, self.seg_prefix)
if not (self.proposal_file is None
or osp.isabs(self.proposal_file)):
self.proposal_file = osp.join(self.data_root,
self.proposal_file)
# load annotations (and proposals)
self.img_infos = self.load_annotations(self.ann_file)
if self.proposal_file is not None:
self.proposals = self.load_proposals(self.proposal_file)
else:
self.proposals = None
# filter images with no annotation during training
if not test_mode:
valid_inds = self._filter_imgs()
self.img_infos = [self.img_infos[i] for i in valid_inds]
if self.proposals is not None:
self.proposals = [self.proposals[i] for i in valid_inds]
# set group flag for the sampler
if not self.test_mode:
self._set_group_flag()
# processing pipeline
self.pipeline = Compose(pipeline)
def __len__(self):
return len(self.img_infos)
def load_annotations(self, ann_file):
return mmcv.load(ann_file)
def load_proposals(self, proposal_file):
return mmcv.load(proposal_file)
def get_ann_info(self, idx):
return self.img_infos[idx]['ann']
def pre_pipeline(self, results):
results['img_prefix'] = self.img_prefix
results['seg_prefix'] = self.seg_prefix
results['proposal_file'] = self.proposal_file
results['bbox_fields'] = []
results['mask_fields'] = []
def _filter_imgs(self, min_size=32):
"""Filter images too small."""
valid_inds = []
for i, img_info in enumerate(self.img_infos):
if min(img_info['width'], img_info['height']) >= min_size:
valid_inds.append(i)
return valid_inds
def _set_group_flag(self):
"""Set flag according to image aspect ratio.
Images with aspect ratio greater than 1 will be set as group 1,
otherwise group 0.
"""
self.flag = np.zeros(len(self), dtype=np.uint8)
for i in range(len(self)):
img_info = self.img_infos[i]
if img_info['width'] / img_info['height'] > 1:
self.flag[i] = 1
def _rand_another(self, idx):
pool = np.where(self.flag == self.flag[idx])[0]
return np.random.choice(pool)
def __getitem__(self, idx):
if self.test_mode:
return self.prepare_test_img(idx)
while True:
data = self.prepare_train_img(idx)
if data is None:
idx = self._rand_another(idx)
continue
return data
def prepare_train_img(self, idx):
img_info = self.img_infos[idx]
ann_info = self.get_ann_info(idx)
results = dict(img_info=img_info, ann_info=ann_info)
if self.proposals is not None:
results['proposals'] = self.proposals[idx]
self.pre_pipeline(results)
return self.pipeline(results)
def prepare_test_img(self, idx):
img_info = self.img_infos[idx]
results = dict(img_info=img_info)
if self.proposals is not None:
results['proposals'] = self.proposals[idx]
self.pre_pipeline(results)
return self.pipeline(results)
| 5,047 | 32.653333 | 75 | py |
AlignShift | AlignShift-master/mmdet/datasets/dataset_wrappers.py | import numpy as np
from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
from .registry import DATASETS
@DATASETS.register_module
class ConcatDataset(_ConcatDataset):
"""A wrapper of concatenated dataset.
Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but
concat the group flag for image aspect ratio.
Args:
datasets (list[:obj:`Dataset`]): A list of datasets.
"""
def __init__(self, datasets):
super(ConcatDataset, self).__init__(datasets)
self.CLASSES = datasets[0].CLASSES
if hasattr(datasets[0], 'flag'):
flags = []
for i in range(0, len(datasets)):
flags.append(datasets[i].flag)
self.flag = np.concatenate(flags)
@DATASETS.register_module
class RepeatDataset(object):
"""A wrapper of repeated dataset.
The length of repeated dataset will be `times` larger than the original
dataset. This is useful when the data loading time is long but the dataset
is small. Using RepeatDataset can reduce the data loading time between
epochs.
Args:
dataset (:obj:`Dataset`): The dataset to be repeated.
times (int): Repeat times.
"""
def __init__(self, dataset, times):
self.dataset = dataset
self.times = times
self.CLASSES = dataset.CLASSES
if hasattr(self.dataset, 'flag'):
self.flag = np.tile(self.dataset.flag, times)
self._ori_len = len(self.dataset)
def __getitem__(self, idx):
return self.dataset[idx % self._ori_len]
def __len__(self):
return self.times * self._ori_len
| 1,639 | 28.285714 | 78 | py |
AlignShift | AlignShift-master/mmdet/datasets/loader/sampler.py | from __future__ import division
import math
import numpy as np
import torch
from mmcv.runner import get_dist_info
from torch.utils.data import DistributedSampler as _DistributedSampler
from torch.utils.data import Sampler
class DistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True):
super().__init__(dataset, num_replicas=num_replicas, rank=rank)
self.shuffle = shuffle
def __iter__(self):
# deterministically shuffle based on epoch
if self.shuffle:
g = torch.Generator()
g.manual_seed(self.epoch)
indices = torch.randperm(len(self.dataset), generator=g).tolist()
else:
indices = torch.arange(len(self.dataset)).tolist()
# add extra samples to make it evenly divisible
indices += indices[:(self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank:self.total_size:self.num_replicas]
assert len(indices) == self.num_samples
return iter(indices)
class GroupSampler(Sampler):
def __init__(self, dataset, samples_per_gpu=1):
assert hasattr(dataset, 'flag')
self.dataset = dataset
self.samples_per_gpu = samples_per_gpu
self.flag = dataset.flag.astype(np.int64)
self.group_sizes = np.bincount(self.flag)
self.num_samples = 0
for i, size in enumerate(self.group_sizes):
self.num_samples += int(np.ceil(
size / self.samples_per_gpu)) * self.samples_per_gpu
def __iter__(self):
indices = []
for i, size in enumerate(self.group_sizes):
if size == 0:
continue
indice = np.where(self.flag == i)[0]
assert len(indice) == size
np.random.shuffle(indice)
num_extra = int(np.ceil(size / self.samples_per_gpu)
) * self.samples_per_gpu - len(indice)
indice = np.concatenate(
[indice, np.random.choice(indice, num_extra)])
indices.append(indice)
indices = np.concatenate(indices)
indices = [
indices[i * self.samples_per_gpu:(i + 1) * self.samples_per_gpu]
for i in np.random.permutation(
range(len(indices) // self.samples_per_gpu))
]
indices = np.concatenate(indices)
indices = indices.astype(np.int64).tolist()
assert len(indices) == self.num_samples
return iter(indices)
def __len__(self):
return self.num_samples
class DistributedGroupSampler(Sampler):
"""Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
process can pass a DistributedSampler instance as a DataLoader sampler,
and load a subset of the original dataset that is exclusive to it.
.. note::
Dataset is assumed to be of constant size.
Arguments:
dataset: Dataset used for sampling.
num_replicas (optional): Number of processes participating in
distributed training.
rank (optional): Rank of the current process within num_replicas.
"""
def __init__(self,
dataset,
samples_per_gpu=1,
num_replicas=None,
rank=None):
_rank, _num_replicas = get_dist_info()
if num_replicas is None:
num_replicas = _num_replicas
if rank is None:
rank = _rank
self.dataset = dataset
self.samples_per_gpu = samples_per_gpu
self.num_replicas = num_replicas
self.rank = rank
self.epoch = 0
assert hasattr(self.dataset, 'flag')
self.flag = self.dataset.flag
self.group_sizes = np.bincount(self.flag)
self.num_samples = 0
for i, j in enumerate(self.group_sizes):
self.num_samples += int(
math.ceil(self.group_sizes[i] * 1.0 / self.samples_per_gpu /
self.num_replicas)) * self.samples_per_gpu
self.total_size = self.num_samples * self.num_replicas
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = []
for i, size in enumerate(self.group_sizes):
if size > 0:
indice = np.where(self.flag == i)[0]
assert len(indice) == size
indice = indice[list(torch.randperm(int(size),
generator=g))].tolist()
extra = int(
math.ceil(
size * 1.0 / self.samples_per_gpu / self.num_replicas)
) * self.samples_per_gpu * self.num_replicas - len(indice)
# pad indice
tmp = indice.copy()
for _ in range(extra // size):
indice.extend(tmp)
indice.extend(tmp[:extra % size])
indices.extend(indice)
assert len(indices) == self.total_size
indices = [
indices[j] for i in list(
torch.randperm(
len(indices) // self.samples_per_gpu, generator=g))
for j in range(i * self.samples_per_gpu, (i + 1) *
self.samples_per_gpu)
]
# subsample
offset = self.num_samples * self.rank
indices = indices[offset:offset + self.num_samples]
assert len(indices) == self.num_samples
return iter(indices)
def __len__(self):
return self.num_samples
def set_epoch(self, epoch):
self.epoch = epoch
| 5,860 | 34.521212 | 78 | py |
AlignShift | AlignShift-master/mmdet/datasets/loader/build_loader.py | import platform
from functools import partial
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from torch.utils.data import DataLoader
from .sampler import DistributedGroupSampler, DistributedSampler, GroupSampler
if platform.system() != 'Windows':
# https://github.com/pytorch/pytorch/issues/973
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))
def build_dataloader(dataset,
imgs_per_gpu,
workers_per_gpu,
num_gpus=1,
dist=True,
shuffle=True,
**kwargs):
if dist:
rank, world_size = get_dist_info()
if shuffle:
sampler = DistributedGroupSampler(dataset, imgs_per_gpu,
world_size, rank)
else:
sampler = DistributedSampler(
dataset, world_size, rank, shuffle=False)
batch_size = imgs_per_gpu
num_workers = workers_per_gpu
else:
sampler = GroupSampler(dataset, imgs_per_gpu) if shuffle else None
batch_size = num_gpus * imgs_per_gpu
num_workers = num_gpus * workers_per_gpu
data_loader = DataLoader(
dataset,
batch_size=batch_size,
sampler=sampler,
num_workers=num_workers,
collate_fn=partial(collate, samples_per_gpu=imgs_per_gpu),
pin_memory=False,
**kwargs)
return data_loader
| 1,552 | 30.693878 | 78 | py |
AlignShift | AlignShift-master/mmdet/datasets/pipelines/formating.py | from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..registry import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
:class:`Sequence`, :class:`int` and :class:`float`.
"""
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.ndarray):
return torch.from_numpy(data)
elif isinstance(data, Sequence) and not mmcv.is_str(data):
return torch.tensor(data)
elif isinstance(data, int):
return torch.LongTensor([data])
elif isinstance(data, float):
return torch.FloatTensor([data])
else:
raise TypeError('type {} cannot be converted to tensor.'.format(
type(data)))
@PIPELINES.register_module
class ToTensor(object):
def __init__(self, keys):
self.keys = keys
def __call__(self, results):
for key in self.keys:
results[key] = to_tensor(results[key])
return results
def __repr__(self):
return self.__class__.__name__ + '(keys={})'.format(self.keys)
@PIPELINES.register_module
class ImageToTensor(object):
def __init__(self, keys):
self.keys = keys
def __call__(self, results):
for key in self.keys:
results[key] = to_tensor(results[key].transpose(2, 0, 1))
return results
def __repr__(self):
return self.__class__.__name__ + '(keys={})'.format(self.keys)
@PIPELINES.register_module
class Transpose(object):
def __init__(self, keys, order):
self.keys = keys
self.order = order
def __call__(self, results):
for key in self.keys:
results[key] = results[key].transpose(self.order)
return results
def __repr__(self):
return self.__class__.__name__ + '(keys={}, order={})'.format(
self.keys, self.order)
@PIPELINES.register_module
class ToDataContainer(object):
def __init__(self,
fields=(dict(key='img', stack=True), dict(key='gt_bboxes'),
dict(key='gt_labels'))):
self.fields = fields
def __call__(self, results):
for field in self.fields:
field = field.copy()
key = field.pop('key')
results[key] = DC(results[key], **field)
return results
def __repr__(self):
return self.__class__.__name__ + '(fields={})'.format(self.fields)
@PIPELINES.register_module
class DefaultFormatBundle(object):
"""Default formatting bundle.
It simplifies the pipeline of formatting common fields, including "img",
"proposals", "gt_bboxes", "gt_labels", "gt_masks" and "gt_semantic_seg".
These fields are formatted as follows.
- img: (1)transpose, (2)to tensor, (3)to DataContainer (stack=True)
- proposals: (1)to tensor, (2)to DataContainer
- gt_bboxes: (1)to tensor, (2)to DataContainer
- gt_bboxes_ignore: (1)to tensor, (2)to DataContainer
- gt_labels: (1)to tensor, (2)to DataContainer
- gt_masks: (1)to tensor, (2)to DataContainer (cpu_only=True)
- gt_semantic_seg: (1)unsqueeze dim-0 (2)to tensor,
(3)to DataContainer (stack=True)
"""
def __call__(self, results):
if 'img' in results:
img = np.ascontiguousarray(results['img'].transpose(2, 0, 1))
results['img'] = DC(to_tensor(img), stack=True)
for key in ['proposals', 'gt_bboxes', 'gt_bboxes_ignore', 'gt_labels']:
if key not in results:
continue
results[key] = DC(to_tensor(results[key]))
if 'gt_masks' in results:
results['gt_masks'] = DC(results['gt_masks'], cpu_only=True)
if 'gt_semantic_seg' in results:
results['gt_semantic_seg'] = DC(
to_tensor(results['gt_semantic_seg'][None, ...]), stack=True)
return results
def __repr__(self):
return self.__class__.__name__
@PIPELINES.register_module
class Collect(object):
"""
Collect data from the loader relevant to the specific task.
This is usually the last stage of the data loader pipeline. Typically keys
is set to some subset of "img", "proposals", "gt_bboxes",
"gt_bboxes_ignore", "gt_labels", and/or "gt_masks".
The "img_meta" item is always populated. The contents of the "img_meta"
dictionary depends on "meta_keys". By default this includes:
- "img_shape": shape of the image input to the network as a tuple
(h, w, c). Note that images may be zero padded on the bottom/right
if the batch tensor is larger than this shape.
- "scale_factor": a float indicating the preprocessing scale
- "flip": a boolean indicating if image flip transform was used
- "filename": path to the image file
- "ori_shape": original shape of the image as a tuple (h, w, c)
- "pad_shape": image shape after padding
- "img_norm_cfg": a dict of normalization information:
- mean - per channel mean subtraction
- std - per channel std divisor
- to_rgb - bool indicating if bgr was converted to rgb
"""
def __init__(self,
keys,
meta_keys=('filename', 'ori_shape', 'img_shape', 'pad_shape',
'scale_factor', 'flip', 'img_norm_cfg')):
self.keys = keys
self.meta_keys = meta_keys
def __call__(self, results):
data = {}
img_meta = {}
for key in self.meta_keys:
img_meta[key] = results[key]
data['img_meta'] = DC(img_meta, cpu_only=True)
for key in self.keys:
data[key] = results[key]
return data
def __repr__(self):
return self.__class__.__name__ + '(keys={}, meta_keys={})'.format(
self.keys, self.meta_keys)
| 5,994 | 31.058824 | 79 | py |
AlignShift | AlignShift-master/mmdet/utils/flops_counter.py | # Modified from flops-counter.pytorch by Vladislav Sovrasov
# original repo: https://github.com/sovrasov/flops-counter.pytorch
# MIT License
# Copyright (c) 2018 Vladislav Sovrasov
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import numpy as np
import torch
import torch.nn as nn
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn.modules.conv import _ConvNd, _ConvTransposeMixin
from torch.nn.modules.pooling import (_AdaptiveAvgPoolNd, _AdaptiveMaxPoolNd,
_AvgPoolNd, _MaxPoolNd)
CONV_TYPES = (_ConvNd, )
DECONV_TYPES = (_ConvTransposeMixin, )
LINEAR_TYPES = (nn.Linear, )
POOLING_TYPES = (_AvgPoolNd, _MaxPoolNd, _AdaptiveAvgPoolNd,
_AdaptiveMaxPoolNd)
RELU_TYPES = (nn.ReLU, nn.PReLU, nn.ELU, nn.LeakyReLU, nn.ReLU6)
BN_TYPES = (_BatchNorm, )
UPSAMPLE_TYPES = (nn.Upsample, )
SUPPORTED_TYPES = (
CONV_TYPES + DECONV_TYPES + LINEAR_TYPES + POOLING_TYPES + RELU_TYPES +
BN_TYPES + UPSAMPLE_TYPES)
def get_model_complexity_info(model,
input_res,
print_per_layer_stat=True,
as_strings=True,
input_constructor=None,
ost=sys.stdout):
assert type(input_res) is tuple
assert len(input_res) >= 2
flops_model = add_flops_counting_methods(model)
flops_model.eval().start_flops_count()
if input_constructor:
input = input_constructor(input_res)
_ = flops_model(**input)
else:
batch = torch.ones(()).new_empty(
(1, *input_res),
dtype=next(flops_model.parameters()).dtype,
device=next(flops_model.parameters()).device)
flops_model(batch)
if print_per_layer_stat:
print_model_with_flops(flops_model, ost=ost)
flops_count = flops_model.compute_average_flops_cost()
params_count = get_model_parameters_number(flops_model)
flops_model.stop_flops_count()
if as_strings:
return flops_to_string(flops_count), params_to_string(params_count)
return flops_count, params_count
def flops_to_string(flops, units='GMac', precision=2):
if units is None:
if flops // 10**9 > 0:
return str(round(flops / 10.**9, precision)) + ' GMac'
elif flops // 10**6 > 0:
return str(round(flops / 10.**6, precision)) + ' MMac'
elif flops // 10**3 > 0:
return str(round(flops / 10.**3, precision)) + ' KMac'
else:
return str(flops) + ' Mac'
else:
if units == 'GMac':
return str(round(flops / 10.**9, precision)) + ' ' + units
elif units == 'MMac':
return str(round(flops / 10.**6, precision)) + ' ' + units
elif units == 'KMac':
return str(round(flops / 10.**3, precision)) + ' ' + units
else:
return str(flops) + ' Mac'
def params_to_string(params_num):
"""converting number to string
:param float params_num: number
:returns str: number
>>> params_to_string(1e9)
'1000.0 M'
>>> params_to_string(2e5)
'200.0 k'
>>> params_to_string(3e-9)
'3e-09'
"""
if params_num // 10**6 > 0:
return str(round(params_num / 10**6, 2)) + ' M'
elif params_num // 10**3:
return str(round(params_num / 10**3, 2)) + ' k'
else:
return str(params_num)
def print_model_with_flops(model, units='GMac', precision=3, ost=sys.stdout):
total_flops = model.compute_average_flops_cost()
def accumulate_flops(self):
if is_supported_instance(self):
return self.__flops__ / model.__batch_counter__
else:
sum = 0
for m in self.children():
sum += m.accumulate_flops()
return sum
def flops_repr(self):
accumulated_flops_cost = self.accumulate_flops()
return ', '.join([
flops_to_string(
accumulated_flops_cost, units=units, precision=precision),
'{:.3%} MACs'.format(accumulated_flops_cost / total_flops),
self.original_extra_repr()
])
def add_extra_repr(m):
m.accumulate_flops = accumulate_flops.__get__(m)
flops_extra_repr = flops_repr.__get__(m)
if m.extra_repr != flops_extra_repr:
m.original_extra_repr = m.extra_repr
m.extra_repr = flops_extra_repr
assert m.extra_repr != m.original_extra_repr
def del_extra_repr(m):
if hasattr(m, 'original_extra_repr'):
m.extra_repr = m.original_extra_repr
del m.original_extra_repr
if hasattr(m, 'accumulate_flops'):
del m.accumulate_flops
model.apply(add_extra_repr)
print(model, file=ost)
model.apply(del_extra_repr)
def get_model_parameters_number(model):
params_num = sum(p.numel() for p in model.parameters() if p.requires_grad)
return params_num
def add_flops_counting_methods(net_main_module):
# adding additional methods to the existing module object,
# this is done this way so that each function has access to self object
net_main_module.start_flops_count = start_flops_count.__get__(
net_main_module)
net_main_module.stop_flops_count = stop_flops_count.__get__(
net_main_module)
net_main_module.reset_flops_count = reset_flops_count.__get__(
net_main_module)
net_main_module.compute_average_flops_cost = \
compute_average_flops_cost.__get__(net_main_module)
net_main_module.reset_flops_count()
# Adding variables necessary for masked flops computation
net_main_module.apply(add_flops_mask_variable_or_reset)
return net_main_module
def compute_average_flops_cost(self):
"""
A method that will be available after add_flops_counting_methods() is
called on a desired net object.
Returns current mean flops consumption per image.
"""
batches_count = self.__batch_counter__
flops_sum = 0
for module in self.modules():
if is_supported_instance(module):
flops_sum += module.__flops__
return flops_sum / batches_count
def start_flops_count(self):
"""
A method that will be available after add_flops_counting_methods() is
called on a desired net object.
Activates the computation of mean flops consumption per image.
Call it before you run the network.
"""
add_batch_counter_hook_function(self)
self.apply(add_flops_counter_hook_function)
def stop_flops_count(self):
"""
A method that will be available after add_flops_counting_methods() is
called on a desired net object.
Stops computing the mean flops consumption per image.
Call whenever you want to pause the computation.
"""
remove_batch_counter_hook_function(self)
self.apply(remove_flops_counter_hook_function)
def reset_flops_count(self):
"""
A method that will be available after add_flops_counting_methods() is
called on a desired net object.
Resets statistics computed so far.
"""
add_batch_counter_variables_or_reset(self)
self.apply(add_flops_counter_variable_or_reset)
def add_flops_mask(module, mask):
def add_flops_mask_func(module):
if isinstance(module, torch.nn.Conv2d):
module.__mask__ = mask
module.apply(add_flops_mask_func)
def remove_flops_mask(module):
module.apply(add_flops_mask_variable_or_reset)
def is_supported_instance(module):
if isinstance(module, SUPPORTED_TYPES):
return True
else:
return False
def empty_flops_counter_hook(module, input, output):
module.__flops__ += 0
def upsample_flops_counter_hook(module, input, output):
output_size = output[0]
batch_size = output_size.shape[0]
output_elements_count = batch_size
for val in output_size.shape[1:]:
output_elements_count *= val
module.__flops__ += int(output_elements_count)
def relu_flops_counter_hook(module, input, output):
active_elements_count = output.numel()
module.__flops__ += int(active_elements_count)
def linear_flops_counter_hook(module, input, output):
input = input[0]
batch_size = input.shape[0]
module.__flops__ += int(batch_size * input.shape[1] * output.shape[1])
def pool_flops_counter_hook(module, input, output):
input = input[0]
module.__flops__ += int(np.prod(input.shape))
def bn_flops_counter_hook(module, input, output):
module.affine
input = input[0]
batch_flops = np.prod(input.shape)
if module.affine:
batch_flops *= 2
module.__flops__ += int(batch_flops)
def deconv_flops_counter_hook(conv_module, input, output):
# Can have multiple inputs, getting the first one
input = input[0]
batch_size = input.shape[0]
input_height, input_width = input.shape[2:]
kernel_height, kernel_width = conv_module.kernel_size
in_channels = conv_module.in_channels
out_channels = conv_module.out_channels
groups = conv_module.groups
filters_per_channel = out_channels // groups
conv_per_position_flops = (
kernel_height * kernel_width * in_channels * filters_per_channel)
active_elements_count = batch_size * input_height * input_width
overall_conv_flops = conv_per_position_flops * active_elements_count
bias_flops = 0
if conv_module.bias is not None:
output_height, output_width = output.shape[2:]
bias_flops = out_channels * batch_size * output_height * output_height
overall_flops = overall_conv_flops + bias_flops
conv_module.__flops__ += int(overall_flops)
def conv_flops_counter_hook(conv_module, input, output):
# Can have multiple inputs, getting the first one
input = input[0]
batch_size = input.shape[0]
output_dims = list(output.shape[2:])
kernel_dims = list(conv_module.kernel_size)
in_channels = conv_module.in_channels
out_channels = conv_module.out_channels
groups = conv_module.groups
filters_per_channel = out_channels // groups
conv_per_position_flops = np.prod(
kernel_dims) * in_channels * filters_per_channel
active_elements_count = batch_size * np.prod(output_dims)
if conv_module.__mask__ is not None:
# (b, 1, h, w)
output_height, output_width = output.shape[2:]
flops_mask = conv_module.__mask__.expand(batch_size, 1, output_height,
output_width)
active_elements_count = flops_mask.sum()
overall_conv_flops = conv_per_position_flops * active_elements_count
bias_flops = 0
if conv_module.bias is not None:
bias_flops = out_channels * active_elements_count
overall_flops = overall_conv_flops + bias_flops
conv_module.__flops__ += int(overall_flops)
def batch_counter_hook(module, input, output):
batch_size = 1
if len(input) > 0:
# Can have multiple inputs, getting the first one
input = input[0]
batch_size = len(input)
else:
print('Warning! No positional inputs found for a module, '
'assuming batch size is 1.')
module.__batch_counter__ += batch_size
def add_batch_counter_variables_or_reset(module):
module.__batch_counter__ = 0
def add_batch_counter_hook_function(module):
if hasattr(module, '__batch_counter_handle__'):
return
handle = module.register_forward_hook(batch_counter_hook)
module.__batch_counter_handle__ = handle
def remove_batch_counter_hook_function(module):
if hasattr(module, '__batch_counter_handle__'):
module.__batch_counter_handle__.remove()
del module.__batch_counter_handle__
def add_flops_counter_variable_or_reset(module):
if is_supported_instance(module):
module.__flops__ = 0
def add_flops_counter_hook_function(module):
if is_supported_instance(module):
if hasattr(module, '__flops_handle__'):
return
if isinstance(module, CONV_TYPES):
handle = module.register_forward_hook(conv_flops_counter_hook)
elif isinstance(module, RELU_TYPES):
handle = module.register_forward_hook(relu_flops_counter_hook)
elif isinstance(module, LINEAR_TYPES):
handle = module.register_forward_hook(linear_flops_counter_hook)
elif isinstance(module, POOLING_TYPES):
handle = module.register_forward_hook(pool_flops_counter_hook)
elif isinstance(module, BN_TYPES):
handle = module.register_forward_hook(bn_flops_counter_hook)
elif isinstance(module, UPSAMPLE_TYPES):
handle = module.register_forward_hook(upsample_flops_counter_hook)
elif isinstance(module, DECONV_TYPES):
handle = module.register_forward_hook(deconv_flops_counter_hook)
else:
handle = module.register_forward_hook(empty_flops_counter_hook)
module.__flops_handle__ = handle
def remove_flops_counter_hook_function(module):
if is_supported_instance(module):
if hasattr(module, '__flops_handle__'):
module.__flops_handle__.remove()
del module.__flops_handle__
# --- Masked flops counting
# Also being run in the initialization
def add_flops_mask_variable_or_reset(module):
if is_supported_instance(module):
module.__mask__ = None
| 14,351 | 32.069124 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/context_block.py | import torch
from mmcv.cnn import constant_init, kaiming_init
from torch import nn
def last_zero_init(m):
if isinstance(m, nn.Sequential):
constant_init(m[-1], val=0)
else:
constant_init(m, val=0)
class ContextBlock(nn.Module):
def __init__(self,
inplanes,
ratio,
pooling_type='att',
fusion_types=('channel_add', )):
super(ContextBlock, self).__init__()
assert pooling_type in ['avg', 'att']
assert isinstance(fusion_types, (list, tuple))
valid_fusion_types = ['channel_add', 'channel_mul']
assert all([f in valid_fusion_types for f in fusion_types])
assert len(fusion_types) > 0, 'at least one fusion should be used'
self.inplanes = inplanes
self.ratio = ratio
self.planes = int(inplanes * ratio)
self.pooling_type = pooling_type
self.fusion_types = fusion_types
if pooling_type == 'att':
self.conv_mask = nn.Conv2d(inplanes, 1, kernel_size=1)
self.softmax = nn.Softmax(dim=2)
else:
self.avg_pool = nn.AdaptiveAvgPool2d(1)
if 'channel_add' in fusion_types:
self.channel_add_conv = nn.Sequential(
nn.Conv2d(self.inplanes, self.planes, kernel_size=1),
nn.LayerNorm([self.planes, 1, 1]),
nn.ReLU(inplace=True), # yapf: disable
nn.Conv2d(self.planes, self.inplanes, kernel_size=1))
else:
self.channel_add_conv = None
if 'channel_mul' in fusion_types:
self.channel_mul_conv = nn.Sequential(
nn.Conv2d(self.inplanes, self.planes, kernel_size=1),
nn.LayerNorm([self.planes, 1, 1]),
nn.ReLU(inplace=True), # yapf: disable
nn.Conv2d(self.planes, self.inplanes, kernel_size=1))
else:
self.channel_mul_conv = None
self.reset_parameters()
def reset_parameters(self):
if self.pooling_type == 'att':
kaiming_init(self.conv_mask, mode='fan_in')
self.conv_mask.inited = True
if self.channel_add_conv is not None:
last_zero_init(self.channel_add_conv)
if self.channel_mul_conv is not None:
last_zero_init(self.channel_mul_conv)
def spatial_pool(self, x):
batch, channel, height, width = x.size()
if self.pooling_type == 'att':
input_x = x
# [N, C, H * W]
input_x = input_x.view(batch, channel, height * width)
# [N, 1, C, H * W]
input_x = input_x.unsqueeze(1)
# [N, 1, H, W]
context_mask = self.conv_mask(x)
# [N, 1, H * W]
context_mask = context_mask.view(batch, 1, height * width)
# [N, 1, H * W]
context_mask = self.softmax(context_mask)
# [N, 1, H * W, 1]
context_mask = context_mask.unsqueeze(-1)
# [N, 1, C, 1]
context = torch.matmul(input_x, context_mask)
# [N, C, 1, 1]
context = context.view(batch, channel, 1, 1)
else:
# [N, C, 1, 1]
context = self.avg_pool(x)
return context
def forward(self, x):
# [N, C, 1, 1]
context = self.spatial_pool(x)
out = x
if self.channel_mul_conv is not None:
# [N, C, 1, 1]
channel_mul_term = torch.sigmoid(self.channel_mul_conv(context))
out = out * channel_mul_term
if self.channel_add_conv is not None:
# [N, C, 1, 1]
channel_add_term = self.channel_add_conv(context)
out = out + channel_add_term
return out
| 3,766 | 34.87619 | 76 | py |
AlignShift | AlignShift-master/mmdet/ops/dcn/deform_pool.py | import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import deform_pool_cuda
class DeformRoIPoolingFunction(Function):
@staticmethod
def forward(ctx,
data,
rois,
offset,
spatial_scale,
out_size,
out_channels,
no_trans,
group_size=1,
part_size=None,
sample_per_part=4,
trans_std=.0):
# TODO: support unsquare RoIs
out_h, out_w = _pair(out_size)
assert isinstance(out_h, int) and isinstance(out_w, int)
assert out_h == out_w
out_size = out_h # out_h and out_w must be equal
ctx.spatial_scale = spatial_scale
ctx.out_size = out_size
ctx.out_channels = out_channels
ctx.no_trans = no_trans
ctx.group_size = group_size
ctx.part_size = out_size if part_size is None else part_size
ctx.sample_per_part = sample_per_part
ctx.trans_std = trans_std
assert 0.0 <= ctx.trans_std <= 1.0
if not data.is_cuda:
raise NotImplementedError
n = rois.shape[0]
output = data.new_empty(n, out_channels, out_size, out_size)
output_count = data.new_empty(n, out_channels, out_size, out_size)
deform_pool_cuda.deform_psroi_pooling_cuda_forward(
data, rois, offset, output, output_count, ctx.no_trans,
ctx.spatial_scale, ctx.out_channels, ctx.group_size, ctx.out_size,
ctx.part_size, ctx.sample_per_part, ctx.trans_std)
if data.requires_grad or rois.requires_grad or offset.requires_grad:
ctx.save_for_backward(data, rois, offset)
ctx.output_count = output_count
return output
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
if not grad_output.is_cuda:
raise NotImplementedError
data, rois, offset = ctx.saved_tensors
output_count = ctx.output_count
grad_input = torch.zeros_like(data)
grad_rois = None
grad_offset = torch.zeros_like(offset)
deform_pool_cuda.deform_psroi_pooling_cuda_backward(
grad_output, data, rois, offset, output_count, grad_input,
grad_offset, ctx.no_trans, ctx.spatial_scale, ctx.out_channels,
ctx.group_size, ctx.out_size, ctx.part_size, ctx.sample_per_part,
ctx.trans_std)
return (grad_input, grad_rois, grad_offset, None, None, None, None,
None, None, None, None)
deform_roi_pooling = DeformRoIPoolingFunction.apply
class DeformRoIPooling(nn.Module):
def __init__(self,
spatial_scale,
out_size,
out_channels,
no_trans,
group_size=1,
part_size=None,
sample_per_part=4,
trans_std=.0):
super(DeformRoIPooling, self).__init__()
self.spatial_scale = spatial_scale
self.out_size = _pair(out_size)
self.out_channels = out_channels
self.no_trans = no_trans
self.group_size = group_size
self.part_size = out_size if part_size is None else part_size
self.sample_per_part = sample_per_part
self.trans_std = trans_std
def forward(self, data, rois, offset):
if self.no_trans:
offset = data.new_empty(0)
return deform_roi_pooling(data, rois, offset, self.spatial_scale,
self.out_size, self.out_channels,
self.no_trans, self.group_size,
self.part_size, self.sample_per_part,
self.trans_std)
class DeformRoIPoolingPack(DeformRoIPooling):
def __init__(self,
spatial_scale,
out_size,
out_channels,
no_trans,
group_size=1,
part_size=None,
sample_per_part=4,
trans_std=.0,
num_offset_fcs=3,
deform_fc_channels=1024):
super(DeformRoIPoolingPack,
self).__init__(spatial_scale, out_size, out_channels, no_trans,
group_size, part_size, sample_per_part, trans_std)
self.num_offset_fcs = num_offset_fcs
self.deform_fc_channels = deform_fc_channels
if not no_trans:
seq = []
ic = self.out_size[0] * self.out_size[1] * self.out_channels
for i in range(self.num_offset_fcs):
if i < self.num_offset_fcs - 1:
oc = self.deform_fc_channels
else:
oc = self.out_size[0] * self.out_size[1] * 2
seq.append(nn.Linear(ic, oc))
ic = oc
if i < self.num_offset_fcs - 1:
seq.append(nn.ReLU(inplace=True))
self.offset_fc = nn.Sequential(*seq)
self.offset_fc[-1].weight.data.zero_()
self.offset_fc[-1].bias.data.zero_()
def forward(self, data, rois):
assert data.size(1) == self.out_channels
if self.no_trans:
offset = data.new_empty(0)
return deform_roi_pooling(data, rois, offset, self.spatial_scale,
self.out_size, self.out_channels,
self.no_trans, self.group_size,
self.part_size, self.sample_per_part,
self.trans_std)
else:
n = rois.shape[0]
offset = data.new_empty(0)
x = deform_roi_pooling(data, rois, offset, self.spatial_scale,
self.out_size, self.out_channels, True,
self.group_size, self.part_size,
self.sample_per_part, self.trans_std)
offset = self.offset_fc(x.view(n, -1))
offset = offset.view(n, 2, self.out_size[0], self.out_size[1])
return deform_roi_pooling(data, rois, offset, self.spatial_scale,
self.out_size, self.out_channels,
self.no_trans, self.group_size,
self.part_size, self.sample_per_part,
self.trans_std)
class ModulatedDeformRoIPoolingPack(DeformRoIPooling):
def __init__(self,
spatial_scale,
out_size,
out_channels,
no_trans,
group_size=1,
part_size=None,
sample_per_part=4,
trans_std=.0,
num_offset_fcs=3,
num_mask_fcs=2,
deform_fc_channels=1024):
super(ModulatedDeformRoIPoolingPack,
self).__init__(spatial_scale, out_size, out_channels, no_trans,
group_size, part_size, sample_per_part, trans_std)
self.num_offset_fcs = num_offset_fcs
self.num_mask_fcs = num_mask_fcs
self.deform_fc_channels = deform_fc_channels
if not no_trans:
offset_fc_seq = []
ic = self.out_size[0] * self.out_size[1] * self.out_channels
for i in range(self.num_offset_fcs):
if i < self.num_offset_fcs - 1:
oc = self.deform_fc_channels
else:
oc = self.out_size[0] * self.out_size[1] * 2
offset_fc_seq.append(nn.Linear(ic, oc))
ic = oc
if i < self.num_offset_fcs - 1:
offset_fc_seq.append(nn.ReLU(inplace=True))
self.offset_fc = nn.Sequential(*offset_fc_seq)
self.offset_fc[-1].weight.data.zero_()
self.offset_fc[-1].bias.data.zero_()
mask_fc_seq = []
ic = self.out_size[0] * self.out_size[1] * self.out_channels
for i in range(self.num_mask_fcs):
if i < self.num_mask_fcs - 1:
oc = self.deform_fc_channels
else:
oc = self.out_size[0] * self.out_size[1]
mask_fc_seq.append(nn.Linear(ic, oc))
ic = oc
if i < self.num_mask_fcs - 1:
mask_fc_seq.append(nn.ReLU(inplace=True))
else:
mask_fc_seq.append(nn.Sigmoid())
self.mask_fc = nn.Sequential(*mask_fc_seq)
self.mask_fc[-2].weight.data.zero_()
self.mask_fc[-2].bias.data.zero_()
def forward(self, data, rois):
assert data.size(1) == self.out_channels
if self.no_trans:
offset = data.new_empty(0)
return deform_roi_pooling(data, rois, offset, self.spatial_scale,
self.out_size, self.out_channels,
self.no_trans, self.group_size,
self.part_size, self.sample_per_part,
self.trans_std)
else:
n = rois.shape[0]
offset = data.new_empty(0)
x = deform_roi_pooling(data, rois, offset, self.spatial_scale,
self.out_size, self.out_channels, True,
self.group_size, self.part_size,
self.sample_per_part, self.trans_std)
offset = self.offset_fc(x.view(n, -1))
offset = offset.view(n, 2, self.out_size[0], self.out_size[1])
mask = self.mask_fc(x.view(n, -1))
mask = mask.view(n, 1, self.out_size[0], self.out_size[1])
return deform_roi_pooling(
data, rois, offset, self.spatial_scale, self.out_size,
self.out_channels, self.no_trans, self.group_size,
self.part_size, self.sample_per_part, self.trans_std) * mask
| 10,212 | 39.367589 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/dcn/deform_conv.py | import math
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import deform_conv_cuda
class DeformConvFunction(Function):
@staticmethod
def forward(ctx,
input,
offset,
weight,
stride=1,
padding=0,
dilation=1,
groups=1,
deformable_groups=1,
im2col_step=64):
if input is not None and input.dim() != 4:
raise ValueError(
"Expected 4D tensor as input, got {}D tensor instead.".format(
input.dim()))
ctx.stride = _pair(stride)
ctx.padding = _pair(padding)
ctx.dilation = _pair(dilation)
ctx.groups = groups
ctx.deformable_groups = deformable_groups
ctx.im2col_step = im2col_step
ctx.save_for_backward(input, offset, weight)
output = input.new_empty(
DeformConvFunction._output_size(input, weight, ctx.padding,
ctx.dilation, ctx.stride))
ctx.bufs_ = [input.new_empty(0), input.new_empty(0)] # columns, ones
if not input.is_cuda:
raise NotImplementedError
else:
cur_im2col_step = min(ctx.im2col_step, input.shape[0])
assert (input.shape[0] %
cur_im2col_step) == 0, 'im2col step must divide batchsize'
deform_conv_cuda.deform_conv_forward_cuda(
input, weight, offset, output, ctx.bufs_[0], ctx.bufs_[1],
weight.size(3), weight.size(2), ctx.stride[1], ctx.stride[0],
ctx.padding[1], ctx.padding[0], ctx.dilation[1],
ctx.dilation[0], ctx.groups, ctx.deformable_groups,
cur_im2col_step)
return output
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
input, offset, weight = ctx.saved_tensors
grad_input = grad_offset = grad_weight = None
if not grad_output.is_cuda:
raise NotImplementedError
else:
cur_im2col_step = min(ctx.im2col_step, input.shape[0])
assert (input.shape[0] %
cur_im2col_step) == 0, 'im2col step must divide batchsize'
if ctx.needs_input_grad[0] or ctx.needs_input_grad[1]:
grad_input = torch.zeros_like(input)
grad_offset = torch.zeros_like(offset)
deform_conv_cuda.deform_conv_backward_input_cuda(
input, offset, grad_output, grad_input,
grad_offset, weight, ctx.bufs_[0], weight.size(3),
weight.size(2), ctx.stride[1], ctx.stride[0],
ctx.padding[1], ctx.padding[0], ctx.dilation[1],
ctx.dilation[0], ctx.groups, ctx.deformable_groups,
cur_im2col_step)
if ctx.needs_input_grad[2]:
grad_weight = torch.zeros_like(weight)
deform_conv_cuda.deform_conv_backward_parameters_cuda(
input, offset, grad_output,
grad_weight, ctx.bufs_[0], ctx.bufs_[1], weight.size(3),
weight.size(2), ctx.stride[1], ctx.stride[0],
ctx.padding[1], ctx.padding[0], ctx.dilation[1],
ctx.dilation[0], ctx.groups, ctx.deformable_groups, 1,
cur_im2col_step)
return (grad_input, grad_offset, grad_weight, None, None, None, None,
None)
@staticmethod
def _output_size(input, weight, padding, dilation, stride):
channels = weight.size(0)
output_size = (input.size(0), channels)
for d in range(input.dim() - 2):
in_size = input.size(d + 2)
pad = padding[d]
kernel = dilation[d] * (weight.size(d + 2) - 1) + 1
stride_ = stride[d]
output_size += ((in_size + (2 * pad) - kernel) // stride_ + 1, )
if not all(map(lambda s: s > 0, output_size)):
raise ValueError(
"convolution input is too small (output would be {})".format(
'x'.join(map(str, output_size))))
return output_size
class ModulatedDeformConvFunction(Function):
@staticmethod
def forward(ctx,
input,
offset,
mask,
weight,
bias=None,
stride=1,
padding=0,
dilation=1,
groups=1,
deformable_groups=1):
ctx.stride = stride
ctx.padding = padding
ctx.dilation = dilation
ctx.groups = groups
ctx.deformable_groups = deformable_groups
ctx.with_bias = bias is not None
if not ctx.with_bias:
bias = input.new_empty(1) # fake tensor
if not input.is_cuda:
raise NotImplementedError
if weight.requires_grad or mask.requires_grad or offset.requires_grad \
or input.requires_grad:
ctx.save_for_backward(input, offset, mask, weight, bias)
output = input.new_empty(
ModulatedDeformConvFunction._infer_shape(ctx, input, weight))
ctx._bufs = [input.new_empty(0), input.new_empty(0)]
deform_conv_cuda.modulated_deform_conv_cuda_forward(
input, weight, bias, ctx._bufs[0], offset, mask, output,
ctx._bufs[1], weight.shape[2], weight.shape[3], ctx.stride,
ctx.stride, ctx.padding, ctx.padding, ctx.dilation, ctx.dilation,
ctx.groups, ctx.deformable_groups, ctx.with_bias)
return output
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
if not grad_output.is_cuda:
raise NotImplementedError
input, offset, mask, weight, bias = ctx.saved_tensors
grad_input = torch.zeros_like(input)
grad_offset = torch.zeros_like(offset)
grad_mask = torch.zeros_like(mask)
grad_weight = torch.zeros_like(weight)
grad_bias = torch.zeros_like(bias)
deform_conv_cuda.modulated_deform_conv_cuda_backward(
input, weight, bias, ctx._bufs[0], offset, mask, ctx._bufs[1],
grad_input, grad_weight, grad_bias, grad_offset, grad_mask,
grad_output, weight.shape[2], weight.shape[3], ctx.stride,
ctx.stride, ctx.padding, ctx.padding, ctx.dilation, ctx.dilation,
ctx.groups, ctx.deformable_groups, ctx.with_bias)
if not ctx.with_bias:
grad_bias = None
return (grad_input, grad_offset, grad_mask, grad_weight, grad_bias,
None, None, None, None, None)
@staticmethod
def _infer_shape(ctx, input, weight):
n = input.size(0)
channels_out = weight.size(0)
height, width = input.shape[2:4]
kernel_h, kernel_w = weight.shape[2:4]
height_out = (height + 2 * ctx.padding -
(ctx.dilation * (kernel_h - 1) + 1)) // ctx.stride + 1
width_out = (width + 2 * ctx.padding -
(ctx.dilation * (kernel_w - 1) + 1)) // ctx.stride + 1
return n, channels_out, height_out, width_out
deform_conv = DeformConvFunction.apply
modulated_deform_conv = ModulatedDeformConvFunction.apply
class DeformConv(nn.Module):
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
deformable_groups=1,
bias=False):
super(DeformConv, self).__init__()
assert not bias
assert in_channels % groups == 0, \
'in_channels {} cannot be divisible by groups {}'.format(
in_channels, groups)
assert out_channels % groups == 0, \
'out_channels {} cannot be divisible by groups {}'.format(
out_channels, groups)
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = _pair(kernel_size)
self.stride = _pair(stride)
self.padding = _pair(padding)
self.dilation = _pair(dilation)
self.groups = groups
self.deformable_groups = deformable_groups
self.weight = nn.Parameter(
torch.Tensor(out_channels, in_channels // self.groups,
*self.kernel_size))
self.reset_parameters()
def reset_parameters(self):
n = self.in_channels
for k in self.kernel_size:
n *= k
stdv = 1. / math.sqrt(n)
self.weight.data.uniform_(-stdv, stdv)
def forward(self, x, offset):
return deform_conv(x, offset, self.weight, self.stride, self.padding,
self.dilation, self.groups, self.deformable_groups)
class DeformConvPack(DeformConv):
def __init__(self, *args, **kwargs):
super(DeformConvPack, self).__init__(*args, **kwargs)
self.conv_offset = nn.Conv2d(
self.in_channels,
self.deformable_groups * 2 * self.kernel_size[0] *
self.kernel_size[1],
kernel_size=self.kernel_size,
stride=_pair(self.stride),
padding=_pair(self.padding),
bias=True)
self.init_offset()
def init_offset(self):
self.conv_offset.weight.data.zero_()
self.conv_offset.bias.data.zero_()
def forward(self, x):
offset = self.conv_offset(x)
return deform_conv(x, offset, self.weight, self.stride, self.padding,
self.dilation, self.groups, self.deformable_groups)
class ModulatedDeformConv(nn.Module):
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
deformable_groups=1,
bias=True):
super(ModulatedDeformConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = _pair(kernel_size)
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.deformable_groups = deformable_groups
self.with_bias = bias
self.weight = nn.Parameter(
torch.Tensor(out_channels, in_channels // groups,
*self.kernel_size))
if bias:
self.bias = nn.Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
n = self.in_channels
for k in self.kernel_size:
n *= k
stdv = 1. / math.sqrt(n)
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.zero_()
def forward(self, x, offset, mask):
return modulated_deform_conv(x, offset, mask, self.weight, self.bias,
self.stride, self.padding, self.dilation,
self.groups, self.deformable_groups)
class ModulatedDeformConvPack(ModulatedDeformConv):
def __init__(self, *args, **kwargs):
super(ModulatedDeformConvPack, self).__init__(*args, **kwargs)
self.conv_offset_mask = nn.Conv2d(
self.in_channels,
self.deformable_groups * 3 * self.kernel_size[0] *
self.kernel_size[1],
kernel_size=self.kernel_size,
stride=_pair(self.stride),
padding=_pair(self.padding),
bias=True)
self.init_offset()
def init_offset(self):
self.conv_offset_mask.weight.data.zero_()
self.conv_offset_mask.bias.data.zero_()
def forward(self, x):
out = self.conv_offset_mask(x)
o1, o2, mask = torch.chunk(out, 3, dim=1)
offset = torch.cat((o1, o2), dim=1)
mask = torch.sigmoid(mask)
return modulated_deform_conv(x, offset, mask, self.weight, self.bias,
self.stride, self.padding, self.dilation,
self.groups, self.deformable_groups)
| 12,468 | 35.890533 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/masked_conv/masked_conv.py | import math
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import masked_conv2d_cuda
class MaskedConv2dFunction(Function):
@staticmethod
def forward(ctx, features, mask, weight, bias, padding=0, stride=1):
assert mask.dim() == 3 and mask.size(0) == 1
assert features.dim() == 4 and features.size(0) == 1
assert features.size()[2:] == mask.size()[1:]
pad_h, pad_w = _pair(padding)
stride_h, stride_w = _pair(stride)
if stride_h != 1 or stride_w != 1:
raise ValueError(
'Stride could not only be 1 in masked_conv2d currently.')
if not features.is_cuda:
raise NotImplementedError
out_channel, in_channel, kernel_h, kernel_w = weight.size()
batch_size = features.size(0)
out_h = int(
math.floor((features.size(2) + 2 * pad_h -
(kernel_h - 1) - 1) / stride_h + 1))
out_w = int(
math.floor((features.size(3) + 2 * pad_w -
(kernel_h - 1) - 1) / stride_w + 1))
mask_inds = torch.nonzero(mask[0] > 0)
output = features.new_zeros(batch_size, out_channel, out_h, out_w)
if mask_inds.numel() > 0:
mask_h_idx = mask_inds[:, 0].contiguous()
mask_w_idx = mask_inds[:, 1].contiguous()
data_col = features.new_zeros(in_channel * kernel_h * kernel_w,
mask_inds.size(0))
masked_conv2d_cuda.masked_im2col_forward(features, mask_h_idx,
mask_w_idx, kernel_h,
kernel_w, pad_h, pad_w,
data_col)
masked_output = torch.addmm(1, bias[:, None], 1,
weight.view(out_channel, -1), data_col)
masked_conv2d_cuda.masked_col2im_forward(masked_output, mask_h_idx,
mask_w_idx, out_h, out_w,
out_channel, output)
return output
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
return (None, ) * 5
masked_conv2d = MaskedConv2dFunction.apply
class MaskedConv2d(nn.Conv2d):
"""A MaskedConv2d which inherits the official Conv2d.
The masked forward doesn't implement the backward function and only
supports the stride parameter to be 1 currently.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=True):
super(MaskedConv2d,
self).__init__(in_channels, out_channels, kernel_size, stride,
padding, dilation, groups, bias)
def forward(self, input, mask=None):
if mask is None: # fallback to the normal Conv2d
return super(MaskedConv2d, self).forward(input)
else:
return masked_conv2d(input, mask, self.weight, self.bias,
self.padding)
| 3,375 | 36.511111 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/sigmoid_focal_loss/sigmoid_focal_loss.py | import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from . import sigmoid_focal_loss_cuda
class SigmoidFocalLossFunction(Function):
@staticmethod
def forward(ctx, input, target, gamma=2.0, alpha=0.25):
ctx.save_for_backward(input, target)
num_classes = input.shape[1]
ctx.num_classes = num_classes
ctx.gamma = gamma
ctx.alpha = alpha
loss = sigmoid_focal_loss_cuda.forward(input, target, num_classes,
gamma, alpha)
return loss
@staticmethod
@once_differentiable
def backward(ctx, d_loss):
input, target = ctx.saved_tensors
num_classes = ctx.num_classes
gamma = ctx.gamma
alpha = ctx.alpha
d_loss = d_loss.contiguous()
d_input = sigmoid_focal_loss_cuda.backward(input, target, d_loss,
num_classes, gamma, alpha)
return d_input, None, None, None, None
sigmoid_focal_loss = SigmoidFocalLossFunction.apply
# TODO: remove this module
class SigmoidFocalLoss(nn.Module):
def __init__(self, gamma, alpha):
super(SigmoidFocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
def forward(self, logits, targets):
assert logits.is_cuda
loss = sigmoid_focal_loss(logits, targets, self.gamma, self.alpha)
return loss.sum()
def __repr__(self):
tmpstr = self.__class__.__name__ + '(gamma={}, alpha={})'.format(
self.gamma, self.alpha)
return tmpstr
| 1,637 | 28.781818 | 77 | py |
AlignShift | AlignShift-master/mmdet/ops/roi_align/roi_align.py | import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import roi_align_cuda
class RoIAlignFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale, sample_num=0):
out_h, out_w = _pair(out_size)
assert isinstance(out_h, int) and isinstance(out_w, int)
ctx.spatial_scale = spatial_scale
ctx.sample_num = sample_num
ctx.save_for_backward(rois)
ctx.feature_size = features.size()
batch_size, num_channels, data_height, data_width = features.size()
num_rois = rois.size(0)
output = features.new_zeros(num_rois, num_channels, out_h, out_w)
if features.is_cuda:
roi_align_cuda.forward(features, rois, out_h, out_w, spatial_scale,
sample_num, output)
else:
raise NotImplementedError
return output
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
feature_size = ctx.feature_size
spatial_scale = ctx.spatial_scale
sample_num = ctx.sample_num
rois = ctx.saved_tensors[0]
assert (feature_size is not None and grad_output.is_cuda)
batch_size, num_channels, data_height, data_width = feature_size
out_w = grad_output.size(3)
out_h = grad_output.size(2)
grad_input = grad_rois = None
if ctx.needs_input_grad[0]:
grad_input = rois.new_zeros(batch_size, num_channels, data_height,
data_width)
roi_align_cuda.backward(grad_output.contiguous(), rois, out_h,
out_w, spatial_scale, sample_num,
grad_input)
return grad_input, grad_rois, None, None, None
roi_align = RoIAlignFunction.apply
class RoIAlign(nn.Module):
def __init__(self,
out_size,
spatial_scale,
sample_num=0,
use_torchvision=False):
super(RoIAlign, self).__init__()
self.out_size = _pair(out_size)
self.spatial_scale = float(spatial_scale)
self.sample_num = int(sample_num)
self.use_torchvision = use_torchvision
def forward(self, features, rois):
if self.use_torchvision:
from torchvision.ops import roi_align as tv_roi_align
return tv_roi_align(features, rois, self.out_size,
self.spatial_scale, self.sample_num)
else:
return roi_align(features, rois, self.out_size, self.spatial_scale,
self.sample_num)
def __repr__(self):
format_str = self.__class__.__name__
format_str += '(out_size={}, spatial_scale={}, sample_num={}'.format(
self.out_size, self.spatial_scale, self.sample_num)
format_str += ', use_torchvision={})'.format(self.use_torchvision)
return format_str
| 3,068 | 33.875 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/roi_align/gradcheck.py | import os.path as osp
import sys
import numpy as np
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_align import RoIAlign # noqa: E402, isort:skip
feat_size = 15
spatial_scale = 1.0 / 8
img_size = feat_size / spatial_scale
num_imgs = 2
num_rois = 20
batch_ind = np.random.randint(num_imgs, size=(num_rois, 1))
rois = np.random.rand(num_rois, 4) * img_size * 0.5
rois[:, 2:] += img_size * 0.5
rois = np.hstack((batch_ind, rois))
feat = torch.randn(
num_imgs, 16, feat_size, feat_size, requires_grad=True, device='cuda:0')
rois = torch.from_numpy(rois).float().cuda()
inputs = (feat, rois)
print('Gradcheck for roi align...')
test = gradcheck(RoIAlign(3, spatial_scale), inputs, atol=1e-3, eps=1e-3)
print(test)
test = gradcheck(RoIAlign(3, spatial_scale, 2), inputs, atol=1e-3, eps=1e-3)
print(test)
| 879 | 27.387097 | 76 | py |
AlignShift | AlignShift-master/mmdet/ops/roi_pool/roi_pool.py | import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import roi_pool_cuda
class RoIPoolFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale):
assert features.is_cuda
out_h, out_w = _pair(out_size)
assert isinstance(out_h, int) and isinstance(out_w, int)
ctx.save_for_backward(rois)
num_channels = features.size(1)
num_rois = rois.size(0)
out_size = (num_rois, num_channels, out_h, out_w)
output = features.new_zeros(out_size)
argmax = features.new_zeros(out_size, dtype=torch.int)
roi_pool_cuda.forward(features, rois, out_h, out_w, spatial_scale,
output, argmax)
ctx.spatial_scale = spatial_scale
ctx.feature_size = features.size()
ctx.argmax = argmax
return output
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
assert grad_output.is_cuda
spatial_scale = ctx.spatial_scale
feature_size = ctx.feature_size
argmax = ctx.argmax
rois = ctx.saved_tensors[0]
assert feature_size is not None
grad_input = grad_rois = None
if ctx.needs_input_grad[0]:
grad_input = grad_output.new_zeros(feature_size)
roi_pool_cuda.backward(grad_output.contiguous(), rois, argmax,
spatial_scale, grad_input)
return grad_input, grad_rois, None, None
roi_pool = RoIPoolFunction.apply
class RoIPool(nn.Module):
def __init__(self, out_size, spatial_scale, use_torchvision=False):
super(RoIPool, self).__init__()
self.out_size = _pair(out_size)
self.spatial_scale = float(spatial_scale)
self.use_torchvision = use_torchvision
def forward(self, features, rois):
if self.use_torchvision:
from torchvision.ops import roi_pool as tv_roi_pool
return tv_roi_pool(features, rois, self.out_size,
self.spatial_scale)
else:
return roi_pool(features, rois, self.out_size, self.spatial_scale)
def __repr__(self):
format_str = self.__class__.__name__
format_str += '(out_size={}, spatial_scale={}'.format(
self.out_size, self.spatial_scale)
format_str += ', use_torchvision={})'.format(self.use_torchvision)
return format_str
| 2,544 | 32.486842 | 78 | py |
AlignShift | AlignShift-master/mmdet/ops/roi_pool/gradcheck.py | import os.path as osp
import sys
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_pool import RoIPool # noqa: E402, isort:skip
feat = torch.randn(4, 16, 15, 15, requires_grad=True).cuda()
rois = torch.Tensor([[0, 0, 0, 50, 50], [0, 10, 30, 43, 55],
[1, 67, 40, 110, 120]]).cuda()
inputs = (feat, rois)
print('Gradcheck for roi pooling...')
test = gradcheck(RoIPool(4, 1.0 / 8), inputs, eps=1e-5, atol=1e-3)
print(test)
| 513 | 29.235294 | 66 | py |
AlignShift | AlignShift-master/mmdet/ops/nms/nms_wrapper.py | import numpy as np
import torch
from . import nms_cpu, nms_cuda
from .soft_nms_cpu import soft_nms_cpu
def nms(dets, iou_thr, device_id=None):
"""Dispatch to either CPU or GPU NMS implementations.
The input can be either a torch tensor or numpy array. GPU NMS will be used
if the input is a gpu tensor or device_id is specified, otherwise CPU NMS
will be used. The returned type will always be the same as inputs.
Arguments:
dets (torch.Tensor or np.ndarray): bboxes with scores.
iou_thr (float): IoU threshold for NMS.
device_id (int, optional): when `dets` is a numpy array, if `device_id`
is None, then cpu nms is used, otherwise gpu_nms will be used.
Returns:
tuple: kept bboxes and indice, which is always the same data type as
the input.
Example:
>>> dets = np.array([[49.1, 32.4, 51.0, 35.9, 0.9],
>>> [49.3, 32.9, 51.0, 35.3, 0.9],
>>> [49.2, 31.8, 51.0, 35.4, 0.5],
>>> [35.1, 11.5, 39.1, 15.7, 0.5],
>>> [35.6, 11.8, 39.3, 14.2, 0.5],
>>> [35.3, 11.5, 39.9, 14.5, 0.4],
>>> [35.2, 11.7, 39.7, 15.7, 0.3]], dtype=np.float32)
>>> iou_thr = 0.7
>>> supressed, inds = nms(dets, iou_thr)
>>> assert len(inds) == len(supressed) == 3
"""
# convert dets (tensor or numpy array) to tensor
if isinstance(dets, torch.Tensor):
is_numpy = False
dets_th = dets
elif isinstance(dets, np.ndarray):
is_numpy = True
device = 'cpu' if device_id is None else 'cuda:{}'.format(device_id)
dets_th = torch.from_numpy(dets).to(device)
else:
raise TypeError(
'dets must be either a Tensor or numpy array, but got {}'.format(
type(dets)))
# execute cpu or cuda nms
if dets_th.shape[0] == 0:
inds = dets_th.new_zeros(0, dtype=torch.long)
else:
if dets_th.is_cuda:
inds = nms_cuda.nms(dets_th, iou_thr)
else:
inds = nms_cpu.nms(dets_th, iou_thr)
if is_numpy:
inds = inds.cpu().numpy()
return dets[inds, :], inds
def soft_nms(dets, iou_thr, method='linear', sigma=0.5, min_score=1e-3):
"""
Example:
>>> dets = np.array([[4., 3., 5., 3., 0.9],
>>> [4., 3., 5., 4., 0.9],
>>> [3., 1., 3., 1., 0.5],
>>> [3., 1., 3., 1., 0.5],
>>> [3., 1., 3., 1., 0.4],
>>> [3., 1., 3., 1., 0.0]], dtype=np.float32)
>>> iou_thr = 0.7
>>> supressed, inds = soft_nms(dets, iou_thr, sigma=0.5)
>>> assert len(inds) == len(supressed) == 3
"""
if isinstance(dets, torch.Tensor):
is_tensor = True
dets_np = dets.detach().cpu().numpy()
elif isinstance(dets, np.ndarray):
is_tensor = False
dets_np = dets
else:
raise TypeError(
'dets must be either a Tensor or numpy array, but got {}'.format(
type(dets)))
method_codes = {'linear': 1, 'gaussian': 2}
if method not in method_codes:
raise ValueError('Invalid method for SoftNMS: {}'.format(method))
new_dets, inds = soft_nms_cpu(
dets_np,
iou_thr,
method=method_codes[method],
sigma=sigma,
min_score=min_score)
if is_tensor:
return dets.new_tensor(new_dets), dets.new_tensor(
inds, dtype=torch.long)
else:
return new_dets.astype(np.float32), inds.astype(np.int64)
| 3,663 | 34.572816 | 79 | py |
deep_gen_msm | deep_gen_msm-master/prinz/deep_ml_0.py | import torch
import torch.nn as nn
from torch.autograd import Variable, grad, backward
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import torch.utils.data as Data
from math import pi,inf,log
import copy
from pyemma.plots import scatter_contour
from pyemma.msm import MSM,markov_model
from scipy import linalg
from approximate_diffusion_models import OneDimensionalModel
all_trajs=np.load('data/traj.npy')
all_trajs_val=np.load('data/traj_val.npy')
beta=1.
def potential_function(x):
return 4*(x**8+0.8*np.exp(-80*x*x)+0.2*np.exp(-80*(x-0.5)**2)+0.5*np.exp(-40*(x+0.5)**2))
lb=-1.
ub=1.
grid_num=100
delta_t=0.01
diffusion_model=OneDimensionalModel(potential_function,beta,lb,ub,grid_num,delta_t)
tau=5
def log_sum_exp(value, dim=None, keepdim=False):
"""Numerically stable implementation of the operation
value.exp().sum(dim, keepdim).log()
"""
# TODO: torch.max(value, dim=None) threw an error at time of writing
if dim is not None:
m, _ = torch.max(value, dim=dim, keepdim=True)
value0 = value - m
if keepdim is False:
m = m.squeeze(dim)
return m + torch.log(torch.sum(torch.exp(value0),
dim=dim, keepdim=keepdim))
else:
m = torch.max(value)
sum_exp = torch.sum(torch.exp(value - m))
return m + torch.log(sum_exp)
class EarlyStopping:
def __init__(self,p=0):
self.patience=p
self.j=0
self.v=inf
self.other_parameters=None
def reset(self):
self.j=0
self.v=inf
self.other_parameters=None
def read_validation_result(self,model,validation_cost,other_parameters=None):
if validation_cost<self.v:
self.j=0
self.model=copy.deepcopy(model)
self.v=validation_cost
self.other_parameters=other_parameters
else:
self.j+=1
if self.j>=self.patience:
return True
return False
def get_best_model(self):
return copy.deepcopy(self.model)
def get_best_other_parameters(self):
return self.other_parameters
class Net_P(nn.Module):
def __init__(self,input_dim,state_num,net_width=64,n_hidden_layer=4):
super(Net_P, self).__init__()
self.input_dim=input_dim
self.state_num=state_num
self.net_width=net_width
self.n_hidden_layer=n_hidden_layer
self.hidden_layer_list=nn.ModuleList([nn.Linear(input_dim,net_width)]+[nn.Linear(net_width, net_width) for i in range(n_hidden_layer-1)])
self.output_layer=nn.Linear(net_width,state_num)
self.bn_input=nn.BatchNorm1d(input_dim)
self.bn_hidden_list=nn.ModuleList([nn.BatchNorm1d(net_width) for i in range(n_hidden_layer)])
self.bn_output=nn.BatchNorm1d(state_num)
def forward(self,x):
x=self.bn_input(x)
for i in range(self.n_hidden_layer):
x=self.hidden_layer_list[i](x)
x=self.bn_hidden_list[i](x)
x=F.relu(x)
x=self.output_layer(x)
x=self.bn_output(x)
x=F.log_softmax(x,dim=1)
return x
class Net_G(nn.Module):
def __init__(self,input_dim,state_num,eps=0,net_width=64,n_hidden_layer=4):
super(Net_G, self).__init__()
self.input_dim=input_dim
self.state_num=state_num
self.net_width=net_width
self.n_hidden_layer=n_hidden_layer
self.eps=eps
self.hidden_layer_list=nn.ModuleList([nn.Linear(input_dim,net_width)]+[nn.Linear(net_width, net_width) for i in range(n_hidden_layer-1)])
self.output_layer=nn.Linear(net_width,state_num)
self.bn_input=nn.BatchNorm1d(input_dim)
self.bn_hidden_list=nn.ModuleList([nn.BatchNorm1d(net_width) for i in range(n_hidden_layer)])
def forward(self,x):
x=self.bn_input(x)
for i in range(self.n_hidden_layer):
x=self.hidden_layer_list[i](x)
x=self.bn_hidden_list[i](x)
x=F.relu(x)
x=self.output_layer(x)
return x
state_num=4
partition_mem=np.empty([3,diffusion_model.center_list.shape[0],state_num])
K_0_mem=np.empty([3,state_num,state_num])
its_0_mem=np.empty([3,3])
transition_density_0_mem=np.empty([3,diffusion_model.center_list.shape[0],diffusion_model.center_list.shape[0]])
stationary_density_0_mem=np.empty([3,diffusion_model.center_list.shape[0]])
for kk in range(3):
traj=all_trajs[kk]
traj_val=all_trajs_val[kk]
P=Net_P(1,state_num)
G=Net_G(1,state_num)
P.train()
G.train()
batch_size = 100
LR = 1e-3 # learning rate for generator
X_mem=torch.from_numpy(traj[:-tau]).float()
Y_mem=torch.from_numpy(traj[tau:]).float()
X_val=Variable(torch.from_numpy(traj_val[:-tau]).float())
Y_val=Variable(torch.from_numpy(traj_val[tau:]).float())
data_size=X_mem.shape[0]
data_size_val=traj_val.shape[0]-tau
'''
opt = torch.optim.Adam(list(P.parameters())+list(G.parameters()),lr=LR)
stopper=EarlyStopping(5)
for epoch in range(200):
idx_mem_0=torch.randperm(data_size)
idx=0
while True:
actual_batch_size=min(batch_size,data_size-idx)
if actual_batch_size<=0:
break
X_0=Variable(X_mem[idx_mem_0[idx:idx+actual_batch_size]])
Y_0=Variable(Y_mem[idx_mem_0[idx:idx+actual_batch_size]])
idx+=actual_batch_size
log_Chi_0=P(X_0)
log_Gamma_0=G(Y_0)
log_Gamma_0=log_Gamma_0-log_sum_exp(log_Gamma_0,0)+log(actual_batch_size+0.)
ll=log_sum_exp(log_Chi_0+log_Gamma_0,1)
loss=-torch.mean(ll)
opt.zero_grad()
backward(loss)
opt.step()
P.eval()
G.eval()
log_Chi_val=P(X_val)
log_Gamma_val=G(Y_val)
log_Gamma_val=log_Gamma_val-log_sum_exp(log_Gamma_val,0)+log(data_size_val+0.)
ll=log_sum_exp(log_Chi_val+log_Gamma_val,1)
loss_val=-torch.sum(ll).data[0]
print(epoch,loss_val)
P.train()
G.train()
if stopper.read_validation_result([P,G],loss_val):
break
P,G=stopper.get_best_model()
LR=1e-5
opt = torch.optim.Adam(list(G.parameters()),lr=LR)
stopper=EarlyStopping(5)
stopper.read_validation_result(G,loss_val)
P.eval()
G.train()
log_Chi=P(Variable(X_mem)).data
log_Chi_val=P(X_val)
for epoch in range(200):
idx_mem_0=torch.randperm(data_size)
idx=0
print(epoch)
while True:
actual_batch_size=min(batch_size,data_size-idx)
if actual_batch_size<=0:
break
Y_0=Variable(Y_mem[idx_mem_0[idx:idx+actual_batch_size]])
log_Chi_0=Variable(log_Chi[idx_mem_0[idx:idx+actual_batch_size]])
idx+=actual_batch_size
log_Gamma_0=G(Y_0)
log_Gamma_0=log_Gamma_0-log_sum_exp(log_Gamma_0,0)+log(actual_batch_size+0.)
ll=log_sum_exp(log_Chi_0+log_Gamma_0,1)
loss=-torch.mean(ll)
opt.zero_grad()
backward(loss)
opt.step()
G.eval()
Gamma_val=G(Y_val)
Gamma_val=Gamma_val/torch.mean(Gamma_val,0)
log_Gamma_val=G(Y_val)
log_Gamma_val=log_Gamma_val-log_sum_exp(log_Gamma_val,0)+log(data_size_val+0.)
ll=log_sum_exp(log_Chi_val+log_Gamma_val,1)
loss_val=-torch.sum(ll).data[0]
G.train()
print(epoch,loss_val)
if stopper.read_validation_result(G,loss_val):
break
G=stopper.get_best_model()
torch.save(P.state_dict(), 'data/ml/P_params_traj_'+str(kk)+'_tau_'+str(tau)+'.pkl')
torch.save(G.state_dict(), 'data/ml/G_params_traj_'+str(kk)+'_tau_'+str(tau)+'.pkl')
'''
P.load_state_dict(torch.load('data/ml/P_params_traj_'+str(kk)+'_tau_'+str(tau)+'.pkl'))
G.load_state_dict(torch.load('data/ml/G_params_traj_'+str(kk)+'_tau_'+str(tau)+'.pkl'))
P.eval()
G.eval()
xx=Variable(torch.from_numpy(diffusion_model.center_list.reshape(-1,1)).float())
pp=(torch.exp(P(xx))).data.numpy()
partition_mem[kk]=pp
Chi_1=torch.exp(P(Variable(Y_mem)))
log_Gamma=G(Variable(Y_mem))
Gamma=torch.exp(log_Gamma-log_sum_exp(log_Gamma))
Gamma=Gamma/torch.mean(Gamma,0)
K=torch.mm(torch.t(Gamma),Chi_1).data.numpy()/data_size
K=K/K.sum(1)[:,np.newaxis]
K_0_mem[kk]=K
its=-tau*delta_t/np.log(sorted(np.absolute(np.linalg.eigvals(K)), key=lambda x:np.absolute(x),reverse=True)[1:4])
its_0_mem[kk]=its
print(its)
print(diffusion_model.its[1:4])
hist_mem=np.empty([diffusion_model.center_list.shape[0],state_num])
for i in range(state_num):
hist_mem[:,i]=np.histogram(traj[tau:].reshape(-1),bins=grid_num,range=(lb,ub),density=True,weights=Gamma[:,i].data.numpy().reshape(-1))[0]
hist_mem[:,i]/=hist_mem[:,i].sum()
transition_density=pp.dot(hist_mem.T)
model=markov_model(K)
stationary_density=model.stationary_distribution.dot(hist_mem.T)
transition_density_0_mem[kk]=transition_density
stationary_density_0_mem[kk]=stationary_density
np.save('data/ml/partition_mem',partition_mem)
np.save('data/ml/K_0_mem',K_0_mem)
np.save('data/ml/its_0_mem',its_0_mem)
np.save('data/ml/transition_density_0_mem',transition_density_0_mem)
np.save('data/ml/stationary_density_0_mem',stationary_density_0_mem)
| 9,513 | 33.471014 | 146 | py |
deep_gen_msm | deep_gen_msm-master/prinz/deep_ed_0.py | import torch
import torch.nn as nn
from torch.autograd import Variable, grad, backward
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import torch.utils.data as Data
from math import pi,inf,log
import copy
from pyemma.plots import scatter_contour
from pyemma.msm import MSM,markov_model
from scipy import linalg
from approximate_diffusion_models import OneDimensionalModel
all_trajs=np.load('data/traj.npy')
all_trajs_val=np.load('data/traj_val.npy')
beta=1.
def potential_function(x):
return 4*(x**8+0.8*np.exp(-80*x*x)+0.2*np.exp(-80*(x-0.5)**2)+0.5*np.exp(-40*(x+0.5)**2))
lb=-1.
ub=1.
grid_num=100
delta_t=0.01
diffusion_model=OneDimensionalModel(potential_function,beta,lb,ub,grid_num,delta_t)
tau=5
class EarlyStopping:
def __init__(self,p=0):
self.patience=p
self.j=0
self.v=inf
self.other_parameters=None
def reset(self):
self.j=0
self.v=inf
self.other_parameters=None
def read_validation_result(self,model,validation_cost,other_parameters=None):
if validation_cost<self.v:
self.j=0
self.model=copy.deepcopy(model)
self.v=validation_cost
self.other_parameters=other_parameters
else:
self.j+=1
if self.j>=self.patience:
return True
return False
def get_best_model(self):
return copy.deepcopy(self.model)
def get_best_other_parameters(self):
return self.other_parameters
class Net_P(nn.Module):
def __init__(self,input_dim,state_num,net_width=64,n_hidden_layer=4):
super(Net_P, self).__init__()
self.input_dim=input_dim
self.state_num=state_num
self.net_width=net_width
self.n_hidden_layer=n_hidden_layer
self.hidden_layer_list=nn.ModuleList([nn.Linear(input_dim,net_width)]+[nn.Linear(net_width, net_width) for i in range(n_hidden_layer-1)])
self.output_layer=nn.Linear(net_width,state_num)
self.bn_input=nn.BatchNorm1d(input_dim)
self.bn_hidden_list=nn.ModuleList([nn.BatchNorm1d(net_width) for i in range(n_hidden_layer)])
def forward(self,x):
x=self.bn_input(x)
for i in range(self.n_hidden_layer):
x=self.hidden_layer_list[i](x)
x=self.bn_hidden_list[i](x)
x=F.relu(x)
x=self.output_layer(x)
return x
class Net_G(nn.Module):
def __init__(self,data_dim,state_num,noise_dim,eps=0,net_width=64,n_hidden_layer=4):
super(Net_G, self).__init__()
self.data_dim=data_dim
self.noise_dim=noise_dim
self.state_num=state_num
self.net_width=net_width
self.n_hidden_layer=n_hidden_layer
self.eps=eps
self.hidden_layer_list=nn.ModuleList([nn.Linear(state_num+noise_dim,net_width)]+[nn.Linear(net_width, net_width) for i in range(n_hidden_layer-1)])
self.output_layer=nn.Linear(net_width,data_dim)
self.bn_input=nn.BatchNorm1d(state_num+noise_dim)
self.bn_hidden_list=nn.ModuleList([nn.BatchNorm1d(net_width) for i in range(n_hidden_layer)])
def forward(self,x):
x=self.bn_input(x)
for i in range(self.n_hidden_layer):
x=self.hidden_layer_list[i](x)
x=self.bn_hidden_list[i](x)
x=F.relu(x)
x=self.output_layer(x)
return x
state_num=4
noise_dim=4
partition_mem=np.empty([3,diffusion_model.center_list.shape[0],state_num])
K_0_mem=np.empty([3,state_num,state_num])
its_0_mem=np.empty([3,3])
transition_density_0_mem=np.empty([3,diffusion_model.center_list.shape[0],diffusion_model.center_list.shape[0]])
stationary_density_0_mem=np.empty([3,diffusion_model.center_list.shape[0]])
for kk in range(3):
traj=all_trajs[kk]
traj_val=all_trajs_val[kk]
P=Net_P(1,state_num)
G=Net_G(1,state_num,noise_dim)
P.train()
G.train()
batch_size = 100
LR = 1e-3 # learning rate for generator
X_mem=torch.from_numpy(traj[:-tau]).float()
Y_mem=torch.from_numpy(traj[tau:]).float()
X_val=Variable(torch.from_numpy(traj_val[:-tau]).float())
Y_val=Variable(torch.from_numpy(traj_val[tau:]).float())
data_size=X_mem.shape[0]
data_size_val=traj_val.shape[0]-tau
opt_P = torch.optim.Adam(P.parameters(),lr=LR)
opt_G = torch.optim.Adam(G.parameters(),lr=LR)
stopper=EarlyStopping(5)
for epoch in range(200):
idx_mem_0=torch.randperm(data_size)
idx=0
while True:
actual_batch_size=min(batch_size,data_size-idx)
if actual_batch_size<=0:
break
X=Variable(X_mem[idx_mem_0[idx:idx+actual_batch_size]])
Y=Variable(Y_mem[idx_mem_0[idx:idx+actual_batch_size]])
idx+=actual_batch_size
O = P(X)
M = F.softmax(O,dim=1)
B0 = torch.eye(state_num)[(state_num-torch.sum(torch.cumsum(M,dim=1)>=Variable(torch.rand(actual_batch_size)).unsqueeze(1),1).long()).data].float()
B1 = torch.eye(state_num)[(state_num-torch.sum(torch.cumsum(M,dim=1)>=Variable(torch.rand(actual_batch_size)).unsqueeze(1),1).long()).data].float()
R0 = Variable(torch.cat((B0,torch.randn(actual_batch_size, noise_dim)),1))
R1 = Variable(torch.cat((B1,torch.randn(actual_batch_size, noise_dim)),1))
Y0 = G(R0)
Y1 = G(R1)
D = torch.abs(Y0-Y)+torch.abs(Y1-Y)-torch.abs(Y0-Y1)
G_loss = torch.mean(D)
opt_G.zero_grad()
G_loss.backward()
opt_G.step()
opt_P.zero_grad()
O.backward((B0+B1-2*M.data)*D.data/(actual_batch_size+0.))
opt_P.step()
P.eval()
G.eval()
O=P(X_val)
M = F.softmax(O,dim=1)
B0 = torch.eye(state_num)[(state_num-torch.sum(torch.cumsum(M,dim=1)>=Variable(torch.rand(data_size_val)).unsqueeze(1),1).long()).data].float()
B1 = torch.eye(state_num)[(state_num-torch.sum(torch.cumsum(M,dim=1)>=Variable(torch.rand(data_size_val)).unsqueeze(1),1).long()).data].float()
R0 = Variable(torch.cat((B0,torch.randn(data_size_val, noise_dim)),1))
R1 = Variable(torch.cat((B1,torch.randn(data_size_val, noise_dim)),1))
Y0 = G(R0)
Y1 = G(R1)
D = torch.abs(Y0-Y_val)+torch.abs(Y1-Y_val)-torch.abs(Y0-Y1)
loss_val=(torch.mean(D)).data[0]
P.train()
G.train()
print(epoch,loss_val)
if stopper.read_validation_result([P,G],loss_val):
break
P,G=stopper.get_best_model()
LR=1e-5
P.eval()
opt_G = torch.optim.Adam(G.parameters(),lr=LR)
stopper=EarlyStopping(5)
stopper.read_validation_result(G,loss_val)
M_mem = F.softmax(P(Variable(X_mem)),dim=1).data
M_val = F.softmax(P(X_val),dim=1)
for epoch in range(200):
idx_mem_0=torch.randperm(data_size)
idx=0
while True:
actual_batch_size=min(batch_size,data_size-idx)
if actual_batch_size<=0:
break
M=Variable(M_mem[idx_mem_0[idx:idx+actual_batch_size]])
Y=Variable(Y_mem[idx_mem_0[idx:idx+actual_batch_size]])
idx+=actual_batch_size
B0 = torch.eye(state_num)[(state_num-torch.sum(torch.cumsum(M,dim=1)>=Variable(torch.rand(actual_batch_size)).unsqueeze(1),1).long()).data].float()
B1 = torch.eye(state_num)[(state_num-torch.sum(torch.cumsum(M,dim=1)>=Variable(torch.rand(actual_batch_size)).unsqueeze(1),1).long()).data].float()
R0 = Variable(torch.cat((B0,torch.randn(actual_batch_size, noise_dim)),1))
R1 = Variable(torch.cat((B1,torch.randn(actual_batch_size, noise_dim)),1))
Y0 = G(R0)
Y1 = G(R1)
D = torch.abs(Y0-Y)+torch.abs(Y1-Y)-torch.abs(Y0-Y1)
G_loss = torch.mean(D)
opt_G.zero_grad()
G_loss.backward()
opt_G.step()
G.eval()
B0 = torch.eye(state_num)[(state_num-torch.sum(torch.cumsum(M_val,dim=1)>=Variable(torch.rand(data_size_val)).unsqueeze(1),1).long()).data].float()
B1 = torch.eye(state_num)[(state_num-torch.sum(torch.cumsum(M_val,dim=1)>=Variable(torch.rand(data_size_val)).unsqueeze(1),1).long()).data].float()
R0 = Variable(torch.cat((B0,torch.randn(data_size_val, noise_dim)),1))
R1 = Variable(torch.cat((B1,torch.randn(data_size_val, noise_dim)),1))
Y0 = G(R0)
Y1 = G(R1)
D = torch.abs(Y0-Y_val)+torch.abs(Y1-Y_val)-torch.abs(Y0-Y1)
loss_val=(torch.mean(D)).data[0]
G.train()
print(epoch,loss_val)
if stopper.read_validation_result(G,loss_val):
break
G=stopper.get_best_model()
torch.save(P.state_dict(), 'data/ed/P_params_traj_'+str(kk)+'_tau_'+str(tau)+'.pkl')
torch.save(G.state_dict(), 'data/ed/G_params_traj_'+str(kk)+'_tau_'+str(tau)+'.pkl')
P.load_state_dict(torch.load('data/ed/P_params_traj_'+str(kk)+'_tau_'+str(tau)+'.pkl'))
G.load_state_dict(torch.load('data/ed/G_params_traj_'+str(kk)+'_tau_'+str(tau)+'.pkl'))
P.eval()
G.eval()
xx=Variable(torch.from_numpy(diffusion_model.center_list.reshape(-1,1)).float())
pp=(F.softmax(P(xx),1)).data.numpy()
partition_mem[kk]=pp
TEST_BATCH_SIZE=10000
sample_mem=np.empty([TEST_BATCH_SIZE,state_num])
for idx in range(state_num):
B=torch.zeros([TEST_BATCH_SIZE,state_num])
B[:,idx]=1
R=Variable(torch.cat((B,torch.randn(TEST_BATCH_SIZE, noise_dim)),1))
sample_mem[:,idx]=G(R).data.numpy().reshape(-1)
K=np.empty([state_num,state_num])
for idx in range(state_num):
GR=Variable(torch.from_numpy(sample_mem[:,idx].reshape(-1,1)).float())
K[idx,:]=torch.mean(F.softmax(P(GR),1),0).data.numpy()
K=K/K.sum(1)[:,np.newaxis]
its=-tau*delta_t/np.log(sorted(np.absolute(np.linalg.eigvals(K)), key=lambda x:np.absolute(x),reverse=True)[1:4])
its_0_mem[kk]=its
print(its)
print(diffusion_model.its[1:4])
hist_mem=np.empty([diffusion_model.center_list.shape[0],state_num])
for i in range(state_num):
hist_mem[:,i]=np.histogram(sample_mem[:,i],bins=grid_num,range=(lb,ub),density=True,)[0]
hist_mem[:,i]/=hist_mem[:,i].sum()
transition_density=pp.dot(hist_mem.T)
model=markov_model(K)
stationary_density=model.stationary_distribution.dot(hist_mem.T)
transition_density_0_mem[kk]=transition_density
stationary_density_0_mem[kk]=stationary_density
np.save('data/ed/partition_mem',partition_mem)
np.save('data/ed/K_0_mem',K_0_mem)
np.save('data/ed/its_0_mem',its_0_mem)
np.save('data/ed/transition_density_0_mem',transition_density_0_mem)
np.save('data/ed/stationary_density_0_mem',stationary_density_0_mem)
for kk in range(3):
plt.figure()
plt.plot(partition_mem[kk])
plt.figure()
plt.plot(stationary_density_0_mem[kk])
plt.figure()
plt.contourf(transition_density_0_mem[kk]) | 11,120 | 37.085616 | 166 | py |
HPLFlowNet | HPLFlowNet-master/main.py | import os, sys
import os.path as osp
import time
from functools import partial
import gc
import traceback
import numpy as np
import torch
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import transforms
import datasets
import models
import cmd_args
from main_utils import *
from models import EPE3DLoss
from evaluation_bnn import evaluate
def main():
# ensure numba JIT is on
if 'NUMBA_DISABLE_JIT' in os.environ:
del os.environ['NUMBA_DISABLE_JIT']
# parse arguments
global args
args = cmd_args.parse_args_from_yaml(sys.argv[1])
# -------------------- logging args --------------------
if osp.exists(args.ckpt_dir):
to_continue = query_yes_no('Attention!!!, ckpt_dir already exists!\
Whether to continue?',
default=None)
if not to_continue:
sys.exit(1)
os.makedirs(args.ckpt_dir, mode=0o777, exist_ok=True)
logger = Logger(osp.join(args.ckpt_dir, 'log'))
logger.log('sys.argv:\n' + ' '.join(sys.argv))
os.environ['NUMBA_NUM_THREADS'] = str(args.workers)
logger.log('NUMBA NUM THREADS\t' + os.environ['NUMBA_NUM_THREADS'])
for arg in sorted(vars(args)):
logger.log('{:20s} {}'.format(arg, getattr(args, arg)))
logger.log('')
# -------------------- dataset & loader --------------------
if not args.evaluate:
train_dataset = datasets.__dict__[args.dataset](
train=True,
transform=transforms.Augmentation(args.aug_together,
args.aug_pc2,
args.data_process,
args.num_points,
args.allow_less_points),
gen_func=transforms.GenerateDataUnsymmetric(args),
args=args
)
logger.log('train_dataset: ' + str(train_dataset))
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.workers,
pin_memory=True,
worker_init_fn=lambda x: np.random.seed((torch.initial_seed()) % (2 ** 32))
)
val_dataset = datasets.__dict__[args.dataset](
train=False,
transform=transforms.ProcessData(args.data_process,
args.num_points,
args.allow_less_points),
gen_func=transforms.GenerateDataUnsymmetric(args),
args=args
)
logger.log('val_dataset: ' + str(val_dataset))
val_loader = torch.utils.data.DataLoader(
val_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
pin_memory=True,
worker_init_fn=lambda x: np.random.seed((torch.initial_seed()) % (2 ** 32))
)
# -------------------- create model --------------------
logger.log("=> creating model '{}'".format(args.arch))
model = models.__dict__[args.arch](args)
if not args.evaluate:
init_func = partial(init_weights_multi, init_type=args.init, gain=args.gain)
model.apply(init_func)
logger.log(model)
model = torch.nn.DataParallel(model).cuda()
criterion = EPE3DLoss().cuda()
if args.evaluate:
torch.backends.cudnn.enabled = False
else:
cudnn.benchmark = True
# https://discuss.pytorch.org/t/what-does-torch-backends-cudnn-benchmark-do/5936
# But if your input sizes changes at each iteration,
# then cudnn will benchmark every time a new size appears,
# possibly leading to worse runtime performances.
# -------------------- resume --------------------
if args.resume:
if osp.isfile(args.resume):
logger.log("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume)
args.start_epoch = checkpoint['epoch']
model.load_state_dict(checkpoint['state_dict'], strict=True)
logger.log("=> loaded checkpoint '{}' (start epoch {}, min loss {})"
.format(args.resume, checkpoint['epoch'], checkpoint['min_loss']))
else:
logger.log("=> no checkpoint found at '{}'".format(args.resume))
checkpoint = None
else:
args.start_epoch = 0
# -------------------- evaluation --------------------
if args.evaluate:
res_str = evaluate(val_loader, model, logger, args)
logger.close()
return res_str
# -------------------- optimizer --------------------
optimizer = torch.optim.Adam(params=filter(lambda p: p.requires_grad, model.parameters()),
lr=args.lr,
weight_decay=0)
if args.resume and (checkpoint is not None):
optimizer.load_state_dict(checkpoint['optimizer'])
if hasattr(args, 'reset_lr') and args.reset_lr:
print('reset lr')
reset_learning_rate(optimizer, args)
# -------------------- main loop --------------------
min_train_loss = None
best_train_epoch = None
best_val_epoch = None
do_eval = True
for epoch in range(args.start_epoch, args.epochs):
old_lr = optimizer.param_groups[0]['lr']
adjust_learning_rate(optimizer, epoch, args)
lr = optimizer.param_groups[0]['lr']
if old_lr != lr:
print('Switch lr!')
logger.log('lr: ' + str(optimizer.param_groups[0]['lr']))
train_loss = train(train_loader, model, criterion, optimizer, epoch, logger)
gc.collect()
is_train_best = True if best_train_epoch is None else (train_loss < min_train_loss)
if is_train_best:
min_train_loss = train_loss
best_train_epoch = epoch
if do_eval:
val_loss = validate(val_loader, model, criterion, logger)
gc.collect()
is_val_best = True if best_val_epoch is None else (val_loss < min_val_loss)
if is_val_best:
min_val_loss = val_loss
best_val_epoch = epoch
logger.log("New min val loss!")
min_loss = min_val_loss if do_eval else min_train_loss
is_best = is_val_best if do_eval else is_train_best
save_checkpoint({
'epoch': epoch + 1, # next start epoch
'arch': args.arch,
'state_dict': model.state_dict(),
'min_loss': min_loss,
'optimizer': optimizer.state_dict(),
}, is_best, args.ckpt_dir)
train_str = 'Best train loss: {:.5f} at epoch {:3d}'.format(min_train_loss, best_train_epoch)
logger.log(train_str)
if do_eval:
val_str = 'Best val loss: {:.5f} at epoch {:3d}'.format(min_val_loss, best_val_epoch)
logger.log(val_str)
logger.close()
result_str = val_str if do_eval else train_str
return result_str
def train(train_loader, model, criterion, optimizer, epoch, logger):
epe3d_losses = AverageMeter()
total_losses = AverageMeter()
model.train()
for i, (pc1, pc2, sf, generated_data, path) in enumerate(train_loader):
try:
cur_sf = sf.cuda(non_blocking=True)
output = model(pc1, pc2, generated_data)
epe3d_loss = criterion(input=output, target=cur_sf).mean()
optimizer.zero_grad()
epe3d_loss.backward()
optimizer.step()
epe3d_losses.update(epe3d_loss.item(), pc1.size(0)) # batch size can only be 1 for now
if i % args.print_freq == 0:
logger.log('Epoch: [{0}][{1}/{2}]\t'
'EPE3D Loss {epe3d_losses_.val:.4f} ({epe3d_losses_.avg:.4f})'
.format(
epoch + 1, i + 1, len(train_loader),
epe3d_losses_=epe3d_losses), end='')
logger.log('')
except RuntimeError as ex:
logger.log("in TRAIN, RuntimeError " + repr(ex))
logger.log("batch idx: " + str(i) + ' path: ' + path[0])
traceback.print_tb(ex.__traceback__, file=logger.out_fd)
traceback.print_tb(ex.__traceback__)
if "CUDA error: out of memory" in str(ex) or "cuda runtime error" in str(ex):
logger.log("out of memory, continue")
del pc1, pc2, sf, generated_data
if 'output' in locals():
del output
torch.cuda.empty_cache()
gc.collect()
else:
sys.exit(1)
logger.log(
' * Train EPE3D {epe3d_losses_.avg:.4f}'.format(epe3d_losses_=epe3d_losses))
return epe3d_losses.avg
def validate(val_loader, model, criterion, logger):
epe3d_losses = AverageMeter()
model.eval()
with torch.no_grad():
for i, (pc1, pc2, sf, generated_data, path) in enumerate(val_loader):
try:
cur_sf = sf.cuda(non_blocking=True)
output = model(pc1, pc2, generated_data)
epe3d_loss = criterion(input=output, target=cur_sf)
epe3d_losses.update(epe3d_loss.mean().item())
if i % args.print_freq == 0:
logger.log('Test: [{0}/{1}]\t'
'EPE3D loss {epe3d_losses_.val:.4f} ({epe3d_losses_.avg:.4f})'
.format(i + 1, len(val_loader),
epe3d_losses_=epe3d_losses))
except RuntimeError as ex:
logger.log("in VAL, RuntimeError " + repr(ex))
traceback.print_tb(ex.__traceback__, file=logger.out_fd)
traceback.print_tb(ex.__traceback__)
if "CUDA error: out of memory" in str(ex) or "cuda runtime error" in str(ex):
logger.log("out of memory, continue")
del pc1, pc2, sf, generated_data
torch.cuda.empty_cache()
gc.collect()
print('remained objects after OOM crash')
else:
sys.exit(1)
logger.log(' * EPE3D loss {epe3d_loss_.avg:.4f}'.format(epe3d_loss_=epe3d_losses))
return epe3d_losses.avg
if __name__ == '__main__':
main()
| 10,414 | 34.790378 | 99 | py |
HPLFlowNet | HPLFlowNet-master/main_utils.py | # helper functions for training
import os, sys
import shutil
import torch
from torch.nn import init
def reset_learning_rate(optimizer, args):
for param_group in optimizer.param_groups:
param_group['lr'] = args.lr
def adjust_learning_rate(optimizer, epoch, args):
# old_lr = optimizer.param_groups[0]['lr']
if args.custom_lr:
# lr = args.lr
# try:
pointer = next(x[0] for x in enumerate(args.lr_switch_epochs) if epoch >= x[1])
lr = args.lrs[pointer]
# except StopIteration:
# pass
else:
lr = args.lr * (args.lr_decay_rate ** (epoch // args.lr_decay_epochs))
lr = max(lr, args.lr_clip)
# logger.log('lr: ' + str(lr))
reset_learning_rate(optimizer, args)
# for param_group in optimizer.param_groups:
# param_group['lr'] = lr
def init_weights_multi(m, init_type, gain=1.):
classname = m.__class__.__name__
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
if init_type == 'normal':
init.normal_(m.weight.data, 0.0, gain)
elif init_type == 'xavier':
init.xavier_normal_(m.weight.data, gain=gain)
elif init_type == 'kaiming':
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
elif init_type == 'orthogonal':
init.orthogonal_(m.weight.data, gain=gain)
else:
raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
if hasattr(m, 'bias') and m.bias is not None:
init.constant_(m.bias.data, 0.0)
elif classname.find('BatchNorm') != -1:
init.normal_(m.weight.data, 1.0, gain)
init.constant_(m.bias.data, 0.0)
# ---------------- Pretty sure the following functions/classes are common ----------------
def save_checkpoint(state, is_best, ckpt_dir, filename='checkpoint.pth.tar'):
torch.save(state, os.path.join(ckpt_dir, filename))
if state['epoch'] % 10 == 1:
shutil.copyfile(
os.path.join(ckpt_dir, filename),
os.path.join(ckpt_dir, 'checkpoint_'+str(state['epoch'])+'.pth.tar'))
if is_best:
shutil.copyfile(
os.path.join(ckpt_dir, filename),
os.path.join(ckpt_dir, 'model_best.pth.tar'))
class Logger(object):
def __init__(self, out_fname):
self.out_fd = open(out_fname, 'w')
def log(self, out_str, end='\n'):
"""
out_str: single object now
"""
self.out_fd.write(str(out_str) + end)
self.out_fd.flush()
print(out_str, end=end, flush=True)
def close(self):
self.out_fd.close()
class MovingAverage(object):
def __init__(self, N):
self.cumsum = [0]
self.moving_avgs = []
self.N = N
self.counter = 1
def update(self, x):
self.cumsum.append(self.cumsum[self.counter - 1] + x)
if self.counter < self.N:
self.moving_avgs.append(self.cumsum[self.counter] / self.counter)
else:
moving_avg = (self.cumsum[self.counter] - self.cumsum[self.counter - self.N]) / self.N
self.moving_avgs.append(moving_avg)
self.counter += 1
return self.moving_avgs[-1]
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
| 4,763 | 30.342105 | 98 | py |
HPLFlowNet | HPLFlowNet-master/evaluation_bnn.py | import os, sys
import os.path as osp
import numpy as np
import pickle
import torch
import torch.optim
import torch.utils.data
from main_utils import *
from utils import geometry
from evaluation_utils import evaluate_2d, evaluate_3d
TOTAL_NUM_SAMPLES = 0
def evaluate(val_loader, model, logger, args):
save_idx = 0
num_sampled_batches = TOTAL_NUM_SAMPLES // args.batch_size
# sample data for visualization
if TOTAL_NUM_SAMPLES == 0:
sampled_batch_indices = []
else:
if len(val_loader) > num_sampled_batches:
print('num_sampled_batches', num_sampled_batches)
print('len(val_loader)', len(val_loader))
sep = len(val_loader) // num_sampled_batches
sampled_batch_indices = list(range(len(val_loader)))[::sep]
else:
sampled_batch_indices = range(len(val_loader))
save_dir = osp.join(args.ckpt_dir, 'visu_' + osp.split(args.ckpt_dir)[-1])
os.makedirs(save_dir, exist_ok=True)
path_list = []
epe3d_list = []
epe3ds = AverageMeter()
acc3d_stricts = AverageMeter()
acc3d_relaxs = AverageMeter()
outliers = AverageMeter()
# 2D
epe2ds = AverageMeter()
acc2ds = AverageMeter()
model.eval()
with torch.no_grad():
for i, items in enumerate(val_loader):
pc1, pc2, sf, generated_data, path = items
output = model(pc1, pc2, generated_data)
pc1_np = pc1.numpy()
pc1_np = pc1_np.transpose((0,2,1))
pc2_np = pc2.numpy()
pc2_np = pc2_np.transpose((0,2,1))
sf_np = sf.numpy()
sf_np = sf_np.transpose((0,2,1))
output_np = output.cpu().numpy()
output_np = output_np.transpose((0,2,1))
EPE3D, acc3d_strict, acc3d_relax, outlier = evaluate_3d(output_np, sf_np)
epe3ds.update(EPE3D)
acc3d_stricts.update(acc3d_strict)
acc3d_relaxs.update(acc3d_relax)
outliers.update(outlier)
# 2D evaluation metrics
flow_pred, flow_gt = geometry.get_batch_2d_flow(pc1_np,
pc1_np+sf_np,
pc1_np+output_np,
path)
EPE2D, acc2d = evaluate_2d(flow_pred, flow_gt)
epe2ds.update(EPE2D)
acc2ds.update(acc2d)
if i % args.print_freq == 0:
logger.log('Test: [{0}/{1}]\t'
'EPE3D {epe3d_.val:.4f} ({epe3d_.avg:.4f})\t'
'ACC3DS {acc3d_s.val:.4f} ({acc3d_s.avg:.4f})\t'
'ACC3DR {acc3d_r.val:.4f} ({acc3d_r.avg:.4f})\t'
'Outliers3D {outlier_.val:.4f} ({outlier_.avg:.4f})\t'
'EPE2D {epe2d_.val:.4f} ({epe2d_.avg:.4f})\t'
'ACC2D {acc2d_.val:.4f} ({acc2d_.avg:.4f})'
.format(i + 1, len(val_loader),
epe3d_=epe3ds,
acc3d_s=acc3d_stricts,
acc3d_r=acc3d_relaxs,
outlier_=outliers,
epe2d_=epe2ds,
acc2d_=acc2ds,
))
if i in sampled_batch_indices:
np.save(osp.join(save_dir, 'pc1_' + str(save_idx) + '.npy'), pc1_np)
np.save(osp.join(save_dir, 'sf_' + str(save_idx) + '.npy'), sf_np)
np.save(osp.join(save_dir, 'output_' + str(save_idx) + '.npy'), output_np)
np.save(osp.join(save_dir, 'pc2_' + str(save_idx) + '.npy'), pc2_np)
epe3d_list.append(EPE3D)
path_list.extend(path)
save_idx += 1
del pc1, pc2, sf, generated_data
if len(path_list) > 0:
np.save(osp.join(save_dir, 'epe3d_per_frame.npy'), np.array(epe3d_list))
with open(osp.join(save_dir, 'sample_path_list.pickle'), 'wb') as fd:
pickle.dump(path_list, fd)
res_str = (' * EPE3D {epe3d_.avg:.4f}\t'
'ACC3DS {acc3d_s.avg:.4f}\t'
'ACC3DR {acc3d_r.avg:.4f}\t'
'Outliers3D {outlier_.avg:.4f}\t'
'EPE2D {epe2d_.avg:.4f}\t'
'ACC2D {acc2d_.avg:.4f}'
.format(
epe3d_=epe3ds,
acc3d_s=acc3d_stricts,
acc3d_r=acc3d_relaxs,
outlier_=outliers,
epe2d_=epe2ds,
acc2d_=acc2ds,
))
logger.log(res_str)
return res_str
| 4,786 | 36.108527 | 90 | py |
HPLFlowNet | HPLFlowNet-master/models/HPLFlowNet.py | import torch
import torch.nn as nn
from .bilateralNN import BilateralConvFlex
from .bnn_flow import BilateralCorrelationFlex
from .module_utils import Conv1dReLU
__all__ = ['HPLFlowNet']
class HPLFlowNet(nn.Module):
def __init__(self, args):
super(HPLFlowNet, self).__init__()
self.scales_filter_map = args.scales_filter_map
assert len(self.scales_filter_map) == 7
self.chunk_size = -1 if args.evaluate else 1024 * 1024 * 25
conv_module = Conv1dReLU
self.conv1 = nn.Sequential(
conv_module(args.dim, 32, use_leaky=args.use_leaky),
conv_module(32, 32, use_leaky=args.use_leaky),
conv_module(32, 64, use_leaky=args.use_leaky), )
self.bcn1 = BilateralConvFlex(args.dim, self.scales_filter_map[0][1],
64 + args.dim + 1, [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn1_ = BilateralConvFlex(args.dim, self.scales_filter_map[0][1],
args.dim + 1 + 64 + 512, [1024, 1024],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn2 = BilateralConvFlex(args.dim, self.scales_filter_map[1][1],
64 + args.dim + 1, [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn2_ = BilateralConvFlex(args.dim, self.scales_filter_map[1][1],
args.dim + 1 + 64 + 256, [512, 512],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn3 = BilateralConvFlex(args.dim, self.scales_filter_map[2][1],
64 + args.dim + 1, [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn3_ = BilateralConvFlex(args.dim, self.scales_filter_map[2][1],
args.dim + 1 + 64 * 2 + 256, [256, 256],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.corr1 = BilateralCorrelationFlex(args.dim,
self.scales_filter_map[2][2], self.scales_filter_map[2][3],
64, [32, 32], [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
prev_corr_dim=0,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn4 = BilateralConvFlex(args.dim, self.scales_filter_map[3][1],
64 + args.dim + 1, [64, 64], args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn4_ = BilateralConvFlex(args.dim, self.scales_filter_map[3][1],
args.dim + 1 + 64 * 2 + 128, [256, 256],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.corr2 = BilateralCorrelationFlex(args.dim,
self.scales_filter_map[3][2], self.scales_filter_map[3][3],
64, [32, 32], [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
prev_corr_dim=64,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn5 = BilateralConvFlex(args.dim, self.scales_filter_map[4][1],
64 + args.dim + 1, [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn5_ = BilateralConvFlex(args.dim, self.scales_filter_map[4][1],
args.dim + 1 + 64 * 2 + 128, [128, 128],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.corr3 = BilateralCorrelationFlex(args.dim,
self.scales_filter_map[4][2], self.scales_filter_map[4][3],
64, [32, 32], [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
prev_corr_dim=64,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn6 = BilateralConvFlex(args.dim, self.scales_filter_map[5][1],
64 + args.dim + 1, [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn6_ = BilateralConvFlex(args.dim, self.scales_filter_map[5][1],
args.dim + 1 + 64 * 2 + 128, [128, 128],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.corr4 = BilateralCorrelationFlex(args.dim,
self.scales_filter_map[5][2], self.scales_filter_map[5][3],
64, [32, 32], [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
prev_corr_dim=64,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn7 = BilateralConvFlex(args.dim, self.scales_filter_map[6][1],
64 + args.dim + 1, [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.bcn7_ = BilateralConvFlex(args.dim, self.scales_filter_map[6][1],
64 * 2, [128, 128],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.corr5 = BilateralCorrelationFlex(args.dim,
self.scales_filter_map[6][2], self.scales_filter_map[6][3],
64, [32, 32], [64, 64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
prev_corr_dim=64,
last_relu=args.last_relu,
chunk_size=self.chunk_size)
self.conv2 = conv_module(1024, 1024, use_leaky=args.use_leaky)
self.conv3 = conv_module(1024, 512, use_leaky=args.use_leaky)
self.conv4 = nn.Conv1d(512, 3, kernel_size=1)
def forward(self, pc1, pc2, generated_data):
feat1 = self.conv1(pc1)
feat2 = self.conv1(pc2)
pc1_out1 = self.bcn1(torch.cat((generated_data[0]['pc1_el_minus_gr'], feat1), dim=1),
in_barycentric=generated_data[0]['pc1_barycentric'],
in_lattice_offset=generated_data[0]['pc1_lattice_offset'],
blur_neighbors=generated_data[0]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out1 = self.bcn1(torch.cat((generated_data[0]['pc2_el_minus_gr'], feat2), dim=1),
in_barycentric=generated_data[0]['pc2_barycentric'],
in_lattice_offset=generated_data[0]['pc2_lattice_offset'],
blur_neighbors=generated_data[0]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc1_out2 = self.bcn2(torch.cat((generated_data[1]['pc1_el_minus_gr'], pc1_out1), dim=1),
in_barycentric=generated_data[1]['pc1_barycentric'],
in_lattice_offset=generated_data[1]['pc1_lattice_offset'],
blur_neighbors=generated_data[1]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out2 = self.bcn2(torch.cat((generated_data[1]['pc2_el_minus_gr'], pc2_out1), dim=1),
in_barycentric=generated_data[1]['pc2_barycentric'],
in_lattice_offset=generated_data[1]['pc2_lattice_offset'],
blur_neighbors=generated_data[1]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc1_out3 = self.bcn3(torch.cat((generated_data[2]['pc1_el_minus_gr'], pc1_out2), dim=1),
in_barycentric=generated_data[2]['pc1_barycentric'],
in_lattice_offset=generated_data[2]['pc1_lattice_offset'],
blur_neighbors=generated_data[2]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out3 = self.bcn3(torch.cat((generated_data[2]['pc2_el_minus_gr'], pc2_out2), dim=1),
in_barycentric=generated_data[2]['pc2_barycentric'],
in_lattice_offset=generated_data[2]['pc2_lattice_offset'],
blur_neighbors=generated_data[2]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
corr_out1 = self.corr1(pc1_out3, pc2_out3, prev_corr_feat=None,
barycentric1=None,
lattice_offset1=None,
pc1_corr_indices=generated_data[2]['pc1_corr_indices'],
pc2_corr_indices=generated_data[2]['pc2_corr_indices'],
max_hash_cnt1=generated_data[2]['pc1_hash_cnt'].item(),
max_hash_cnt2=generated_data[2]['pc2_hash_cnt'].item(),
)
pc1_out4 = self.bcn4(torch.cat((generated_data[3]['pc1_el_minus_gr'], pc1_out3), dim=1),
in_barycentric=generated_data[3]['pc1_barycentric'],
in_lattice_offset=generated_data[3]['pc1_lattice_offset'],
blur_neighbors=generated_data[3]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out4 = self.bcn4(torch.cat((generated_data[3]['pc2_el_minus_gr'], pc2_out3), dim=1),
in_barycentric=generated_data[3]['pc2_barycentric'],
in_lattice_offset=generated_data[3]['pc2_lattice_offset'],
blur_neighbors=generated_data[3]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
corr_out2 = self.corr2(pc1_out4, pc2_out4, corr_out1,
barycentric1=generated_data[3]['pc1_barycentric'],
lattice_offset1=generated_data[3]['pc1_lattice_offset'],
pc1_corr_indices=generated_data[3]['pc1_corr_indices'],
pc2_corr_indices=generated_data[3]['pc2_corr_indices'],
max_hash_cnt1=generated_data[3]['pc1_hash_cnt'].item(),
max_hash_cnt2=generated_data[3]['pc2_hash_cnt'].item(),
)
pc1_out5 = self.bcn5(torch.cat((generated_data[4]['pc1_el_minus_gr'], pc1_out4), dim=1),
in_barycentric=generated_data[4]['pc1_barycentric'],
in_lattice_offset=generated_data[4]['pc1_lattice_offset'],
blur_neighbors=generated_data[4]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out5 = self.bcn5(torch.cat((generated_data[4]['pc2_el_minus_gr'], pc2_out4), dim=1),
in_barycentric=generated_data[4]['pc2_barycentric'],
in_lattice_offset=generated_data[4]['pc2_lattice_offset'],
blur_neighbors=generated_data[4]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
corr_out3 = self.corr3(pc1_out5, pc2_out5, corr_out2,
barycentric1=generated_data[4]['pc1_barycentric'],
lattice_offset1=generated_data[4]['pc1_lattice_offset'],
pc1_corr_indices=generated_data[4]['pc1_corr_indices'],
pc2_corr_indices=generated_data[4]['pc2_corr_indices'],
max_hash_cnt1=generated_data[4]['pc1_hash_cnt'].item(),
max_hash_cnt2=generated_data[4]['pc2_hash_cnt'].item(),
)
pc1_out6 = self.bcn6(torch.cat((generated_data[5]['pc1_el_minus_gr'], pc1_out5), dim=1),
in_barycentric=generated_data[5]['pc1_barycentric'],
in_lattice_offset=generated_data[5]['pc1_lattice_offset'],
blur_neighbors=generated_data[5]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out6 = self.bcn6(torch.cat((generated_data[5]['pc2_el_minus_gr'], pc2_out5), dim=1),
in_barycentric=generated_data[5]['pc2_barycentric'],
in_lattice_offset=generated_data[5]['pc2_lattice_offset'],
blur_neighbors=generated_data[5]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
corr_out4 = self.corr4(pc1_out6, pc2_out6, corr_out3,
barycentric1=generated_data[5]['pc1_barycentric'],
lattice_offset1=generated_data[5]['pc1_lattice_offset'],
pc1_corr_indices=generated_data[5]['pc1_corr_indices'],
pc2_corr_indices=generated_data[5]['pc2_corr_indices'],
max_hash_cnt1=generated_data[5]['pc1_hash_cnt'].item(),
max_hash_cnt2=generated_data[5]['pc2_hash_cnt'].item(),
)
pc1_out7 = self.bcn7(torch.cat((generated_data[6]['pc1_el_minus_gr'], pc1_out6), dim=1),
in_barycentric=generated_data[6]['pc1_barycentric'],
in_lattice_offset=generated_data[6]['pc1_lattice_offset'],
blur_neighbors=generated_data[6]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out7 = self.bcn7(torch.cat((generated_data[6]['pc2_el_minus_gr'], pc2_out6), dim=1),
in_barycentric=generated_data[6]['pc2_barycentric'],
in_lattice_offset=generated_data[6]['pc2_lattice_offset'],
blur_neighbors=generated_data[6]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
corr_out5 = self.corr5(pc1_out7, pc2_out7, corr_out4,
barycentric1=generated_data[6]['pc1_barycentric'],
lattice_offset1=generated_data[6]['pc1_lattice_offset'],
pc1_corr_indices=generated_data[6]['pc1_corr_indices'],
pc2_corr_indices=generated_data[6]['pc2_corr_indices'],
max_hash_cnt1=generated_data[6]['pc1_hash_cnt'].item(),
max_hash_cnt2=generated_data[6]['pc2_hash_cnt'].item(),
)
# upsample
pc1_out7_back = self.bcn7_(torch.cat((corr_out5, pc1_out7), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[6]['pc1_blur_neighbors'],
out_barycentric=generated_data[6]['pc1_barycentric'],
out_lattice_offset=generated_data[6]['pc1_lattice_offset'],
)
pc1_out6_back = self.bcn6_(
torch.cat((generated_data[6]['pc1_el_minus_gr'], pc1_out7_back, corr_out4, pc1_out6), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[5]['pc1_blur_neighbors'],
out_barycentric=generated_data[5]['pc1_barycentric'],
out_lattice_offset=generated_data[5]['pc1_lattice_offset'],
)
pc1_out5_back = self.bcn5_(
torch.cat((generated_data[5]['pc1_el_minus_gr'], pc1_out6_back, corr_out3, pc1_out5), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[4]['pc1_blur_neighbors'],
out_barycentric=generated_data[4]['pc1_barycentric'],
out_lattice_offset=generated_data[4]['pc1_lattice_offset'],
)
pc1_out4_back = self.bcn4_(
torch.cat((generated_data[4]['pc1_el_minus_gr'], pc1_out5_back, corr_out2, pc1_out4), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[3]['pc1_blur_neighbors'],
out_barycentric=generated_data[3]['pc1_barycentric'],
out_lattice_offset=generated_data[3]['pc1_lattice_offset'],
)
pc1_out3_back = self.bcn3_(
torch.cat((generated_data[3]['pc1_el_minus_gr'], pc1_out4_back, corr_out1, pc1_out3), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[2]['pc1_blur_neighbors'],
out_barycentric=generated_data[2]['pc1_barycentric'],
out_lattice_offset=generated_data[2]['pc1_lattice_offset'],
)
pc1_out2_back = self.bcn2_(torch.cat((generated_data[2]['pc1_el_minus_gr'], pc1_out3_back, pc1_out2), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[1]['pc1_blur_neighbors'],
out_barycentric=generated_data[1]['pc1_barycentric'],
out_lattice_offset=generated_data[1]['pc1_lattice_offset'],
)
pc1_out1_back = self.bcn1_(torch.cat((generated_data[1]['pc1_el_minus_gr'], pc1_out2_back, pc1_out1), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[0]['pc1_blur_neighbors'],
out_barycentric=generated_data[0]['pc1_barycentric'],
out_lattice_offset=generated_data[0]['pc1_lattice_offset'],
)
# FINAL
res = self.conv2(pc1_out1_back)
res = self.conv3(res)
res = self.conv4(res)
return res
| 25,890 | 59.071926 | 117 | py |
HPLFlowNet | HPLFlowNet-master/models/HPLFlowNet_shallow.py | import torch
import torch.nn as nn
from .bilateralNN import BilateralConvFlex
from .bnn_flow import BilateralCorrelationFlex
from .module_utils import Conv1dReLU
__all__ = ['HPLFlowNetShallow']
class HPLFlowNetShallow(nn.Module):
def __init__(self, args):
super(HPLFlowNetShallow, self).__init__()
self.scales_filter_map = args.scales_filter_map
assert len(self.scales_filter_map) == 5
conv_module = Conv1dReLU
self.conv1 = nn.Sequential(
conv_module(args.dim, 32, use_leaky=args.use_leaky),
conv_module(32, 32, use_leaky=args.use_leaky),
conv_module(32, 64, use_leaky=args.use_leaky), )
self.bcn1 = BilateralConvFlex(args.dim, self.scales_filter_map[0][1],
64 + args.dim + 1, [64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu)
self.bcn1_ = BilateralConvFlex(args.dim, self.scales_filter_map[0][1],
args.dim + 1 + 64 + 64, [128],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu)
self.bcn2 = BilateralConvFlex(args.dim, self.scales_filter_map[1][1],
64 + args.dim + 1, [64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu)
self.bcn2_ = BilateralConvFlex(args.dim, self.scales_filter_map[1][1],
args.dim + 1 + 64 + 64, [64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu)
self.bcn3 = BilateralConvFlex(args.dim, self.scales_filter_map[2][1],
64 + args.dim + 1, [64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu)
self.bcn3_ = BilateralConvFlex(args.dim, self.scales_filter_map[2][1],
args.dim + 1 + 64 * 2 + 64, [64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu)
self.corr1 = BilateralCorrelationFlex(args.dim,
self.scales_filter_map[2][2], self.scales_filter_map[2][3],
64, [32], [32],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
prev_corr_dim=0,
last_relu=args.last_relu)
self.corr1_refine = nn.Sequential(conv_module(32 + args.dim + 1, 64, use_leaky=args.use_leaky),
conv_module(64, 64, use_leaky=args.use_leaky),
conv_module(64, 64, use_leaky=args.use_leaky),
)
self.bcn4 = BilateralConvFlex(args.dim, self.scales_filter_map[3][1],
64 + args.dim + 1, [64], args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu)
self.bcn4_ = BilateralConvFlex(args.dim, self.scales_filter_map[3][1],
args.dim + 1 + 64 * 2 + 64, [64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu)
self.corr2 = BilateralCorrelationFlex(args.dim,
self.scales_filter_map[3][2], self.scales_filter_map[3][3],
64, [32], [32],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
prev_corr_dim=64,
last_relu=args.last_relu)
self.corr2_refine = nn.Sequential(conv_module(32 + args.dim + 1, 64, use_leaky=args.use_leaky),
conv_module(64, 64, use_leaky=args.use_leaky),
conv_module(64, 64, use_leaky=args.use_leaky),
)
self.bcn5 = BilateralConvFlex(args.dim, self.scales_filter_map[4][1],
64 + args.dim + 1, [64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=True,
do_slice=False,
last_relu=args.last_relu)
self.bcn5_ = BilateralConvFlex(args.dim, self.scales_filter_map[4][1],
64 + 64, [64],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
do_splat=False,
do_slice=True,
last_relu=args.last_relu)
self.corr3 = BilateralCorrelationFlex(args.dim,
self.scales_filter_map[4][2], self.scales_filter_map[4][3],
64, [32], [32],
args.DEVICE,
use_bias=args.bcn_use_bias,
use_leaky=args.use_leaky,
use_norm=args.bcn_use_norm,
prev_corr_dim=64,
last_relu=args.last_relu)
self.corr3_refine = nn.Sequential(conv_module(32, 64, use_leaky=args.use_leaky),
conv_module(64, 64, use_leaky=args.use_leaky),
conv_module(64, 64, use_leaky=args.use_leaky),
)
self.conv2 = conv_module(128, 1024, use_leaky=args.use_leaky)
self.conv3 = conv_module(1024, 512, use_leaky=args.use_leaky)
self.conv4 = nn.Conv1d(512, 3, kernel_size=1)
def forward(self, pc1, pc2, generated_data):
feat1 = self.conv1(pc1)
feat2 = self.conv1(pc2)
pc1_out1 = self.bcn1(torch.cat((generated_data[0]['pc1_el_minus_gr'], feat1), dim=1),
in_barycentric=generated_data[0]['pc1_barycentric'],
in_lattice_offset=generated_data[0]['pc1_lattice_offset'],
blur_neighbors=generated_data[0]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out1 = self.bcn1(torch.cat((generated_data[0]['pc2_el_minus_gr'], feat2), dim=1),
in_barycentric=generated_data[0]['pc2_barycentric'],
in_lattice_offset=generated_data[0]['pc2_lattice_offset'],
blur_neighbors=generated_data[0]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc1_out2 = self.bcn2(torch.cat((generated_data[1]['pc1_el_minus_gr'], pc1_out1), dim=1),
in_barycentric=generated_data[1]['pc1_barycentric'],
in_lattice_offset=generated_data[1]['pc1_lattice_offset'],
blur_neighbors=generated_data[1]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out2 = self.bcn2(torch.cat((generated_data[1]['pc2_el_minus_gr'], pc2_out1), dim=1),
in_barycentric=generated_data[1]['pc2_barycentric'],
in_lattice_offset=generated_data[1]['pc2_lattice_offset'],
blur_neighbors=generated_data[1]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc1_out3 = self.bcn3(torch.cat((generated_data[2]['pc1_el_minus_gr'], pc1_out2), dim=1),
in_barycentric=generated_data[2]['pc1_barycentric'],
in_lattice_offset=generated_data[2]['pc1_lattice_offset'],
blur_neighbors=generated_data[2]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out3 = self.bcn3(torch.cat((generated_data[2]['pc2_el_minus_gr'], pc2_out2), dim=1),
in_barycentric=generated_data[2]['pc2_barycentric'],
in_lattice_offset=generated_data[2]['pc2_lattice_offset'],
blur_neighbors=generated_data[2]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
corr_out1 = self.corr1(pc1_out3, pc2_out3, prev_corr_feat=None,
barycentric1=None,
lattice_offset1=None,
pc1_corr_indices=generated_data[2]['pc1_corr_indices'],
pc2_corr_indices=generated_data[2]['pc2_corr_indices'],
max_hash_cnt1=generated_data[2]['pc1_hash_cnt'].item(),
max_hash_cnt2=generated_data[2]['pc2_hash_cnt'].item(),
)
corr_out1 = self.corr1_refine(torch.cat((generated_data[3]['pc1_el_minus_gr'], corr_out1), dim=1))
pc1_out4 = self.bcn4(torch.cat((generated_data[3]['pc1_el_minus_gr'], pc1_out3), dim=1),
in_barycentric=generated_data[3]['pc1_barycentric'],
in_lattice_offset=generated_data[3]['pc1_lattice_offset'],
blur_neighbors=generated_data[3]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out4 = self.bcn4(torch.cat((generated_data[3]['pc2_el_minus_gr'], pc2_out3), dim=1),
in_barycentric=generated_data[3]['pc2_barycentric'],
in_lattice_offset=generated_data[3]['pc2_lattice_offset'],
blur_neighbors=generated_data[3]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
corr_out2 = self.corr2(pc1_out4, pc2_out4, corr_out1,
barycentric1=generated_data[3]['pc1_barycentric'],
lattice_offset1=generated_data[3]['pc1_lattice_offset'],
pc1_corr_indices=generated_data[3]['pc1_corr_indices'],
pc2_corr_indices=generated_data[3]['pc2_corr_indices'],
max_hash_cnt1=generated_data[3]['pc1_hash_cnt'].item(),
max_hash_cnt2=generated_data[3]['pc2_hash_cnt'].item(),
)
corr_out2 = self.corr2_refine(torch.cat((generated_data[4]['pc1_el_minus_gr'], corr_out2), dim=1))
pc1_out5 = self.bcn5(torch.cat((generated_data[4]['pc1_el_minus_gr'], pc1_out4), dim=1),
in_barycentric=generated_data[4]['pc1_barycentric'],
in_lattice_offset=generated_data[4]['pc1_lattice_offset'],
blur_neighbors=generated_data[4]['pc1_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
pc2_out5 = self.bcn5(torch.cat((generated_data[4]['pc2_el_minus_gr'], pc2_out4), dim=1),
in_barycentric=generated_data[4]['pc2_barycentric'],
in_lattice_offset=generated_data[4]['pc2_lattice_offset'],
blur_neighbors=generated_data[4]['pc2_blur_neighbors'],
out_barycentric=None, out_lattice_offset=None)
corr_out3 = self.corr3(pc1_out5, pc2_out5, corr_out2,
barycentric1=generated_data[4]['pc1_barycentric'],
lattice_offset1=generated_data[4]['pc1_lattice_offset'],
pc1_corr_indices=generated_data[4]['pc1_corr_indices'],
pc2_corr_indices=generated_data[4]['pc2_corr_indices'],
max_hash_cnt1=generated_data[4]['pc1_hash_cnt'].item(),
max_hash_cnt2=generated_data[4]['pc2_hash_cnt'].item(),
)
corr_out3 = self.corr3_refine(corr_out3)
# upsample
pc1_out5_back = self.bcn5_(torch.cat((corr_out3, pc1_out5), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[4]['pc1_blur_neighbors'],
out_barycentric=generated_data[4]['pc1_barycentric'],
out_lattice_offset=generated_data[4]['pc1_lattice_offset'],
)
pc1_out4_back = self.bcn4_(
torch.cat((generated_data[4]['pc1_el_minus_gr'], pc1_out5_back, corr_out2, pc1_out4), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[3]['pc1_blur_neighbors'],
out_barycentric=generated_data[3]['pc1_barycentric'],
out_lattice_offset=generated_data[3]['pc1_lattice_offset'],
)
pc1_out3_back = self.bcn3_(
torch.cat((generated_data[3]['pc1_el_minus_gr'], pc1_out4_back, corr_out1, pc1_out3), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[2]['pc1_blur_neighbors'],
out_barycentric=generated_data[2]['pc1_barycentric'],
out_lattice_offset=generated_data[2]['pc1_lattice_offset'],
)
pc1_out2_back = self.bcn2_(torch.cat((generated_data[2]['pc1_el_minus_gr'], pc1_out3_back, pc1_out2), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[1]['pc1_blur_neighbors'],
out_barycentric=generated_data[1]['pc1_barycentric'],
out_lattice_offset=generated_data[1]['pc1_lattice_offset'],
)
pc1_out1_back = self.bcn1_(torch.cat((generated_data[1]['pc1_el_minus_gr'], pc1_out2_back, pc1_out1), dim=1),
in_barycentric=None, in_lattice_offset=None,
blur_neighbors=generated_data[0]['pc1_blur_neighbors'],
out_barycentric=generated_data[0]['pc1_barycentric'],
out_lattice_offset=generated_data[0]['pc1_lattice_offset'],
)
# FINAL
res = self.conv2(pc1_out1_back)
res = self.conv3(res)
res = self.conv4(res)
return res
| 18,315 | 57.705128 | 117 | py |
HPLFlowNet | HPLFlowNet-master/models/bilateralNN.py | import torch
import torch.nn as nn
from .module_utils import Conv2dReLU
DELETE_TMP_VARIABLES = False
class SparseSum(torch.autograd.Function):
@staticmethod
def forward(ctx, indices, values, size, cuda):
"""
:param ctx:
:param indices: (1, B*d1*N)
:param values: (B*d1*N, feat_size)
:param size: (B*(H+1), feat_size)
:param cuda: bool
:return: (B*(H+1), feat_size)
"""
ctx.save_for_backward(indices)
if cuda:
output = torch.cuda.sparse.FloatTensor(indices, values, size)
else:
output = torch.sparse.FloatTensor(indices, values, size)
output = output.to_dense()
return output
@staticmethod
def backward(ctx, grad_output):
indices, = ctx.saved_tensors
grad_values = None
if ctx.needs_input_grad[1]:
grad_values = grad_output[indices.squeeze(0), :]
return None, grad_values, None, None
sparse_sum = SparseSum.apply
class BilateralConvFlex(nn.Module):
def __init__(self,
d, neighborhood_size,
num_input, num_output,
DEVICE,
use_bias,
use_leaky,
use_norm,
do_splat,
do_slice,
last_relu,
chunk_size=1024 * 1024 * 25):
"""
:param d: int. Original dim of position (3 in our case)
:param neighborhood_size: int.
:param num_input: int. C_in for convolution.
:param num_output: list. C_outs for convolution.
:param DEVICE: str, "cuda" or whatever.
:param use_bias: bool. Whether to use bias after slicing
:param use_leaky: bool. Whether to use LeakyReLU
:param use_norm: bool. Our normalization scheme. Always set it to be true for good performance.
:param do_slice: bool.
:param last_relu: bool. Whether to do relu for the last convolution layer in the blur/conv stage.
:param chunk_size: int. max size for convolution, when set to be -1, no chunking operation.
"""
super(BilateralConvFlex, self).__init__()
self.d = d
self.d1 = d + 1
self.neighborhood_size = neighborhood_size
self.filter_size = self.get_filter_size()
self.num_input = num_input
self.num_output = num_output
self.DEVICE = DEVICE
self.use_bias = use_bias # only useful when do_slice = True
self.do_splat = do_splat
self.do_slice = do_slice
self.last_relu = last_relu
self.use_norm = use_norm
self.MAX_SIZE = chunk_size # 1024 * 1024 * 25
num_final_output = num_output[-1]
self.register_buffer('feat_indices', torch.arange(num_input, dtype=torch.long))
if self.do_slice:
self.register_buffer('out_indices', torch.arange(num_final_output, dtype=torch.long))
sequential_list = []
n_in_channel = num_input
for idx, n_out_channel in enumerate(num_output[:-1]):
if idx == 0:
kernel_size = (self.filter_size, 1)
else:
kernel_size = (1, 1)
sequential_list.append(Conv2dReLU(n_in_channel, n_out_channel, kernel_size, use_leaky=use_leaky))
n_in_channel = n_out_channel
if len(num_output) == 1:
kernel_size = (self.filter_size, 1)
else:
kernel_size = (1, 1)
if not self.last_relu:
sequential_list.append(nn.Conv2d(n_in_channel, num_final_output, kernel_size=kernel_size))
else:
sequential_list.append(
Conv2dReLU(n_in_channel, num_final_output, kernel_size=kernel_size, use_leaky=use_leaky))
self.blur_conv = nn.Sequential(*sequential_list)
if self.do_slice and self.use_bias:
self.register_parameter('bias', nn.Parameter(data=torch.zeros((num_final_output,), dtype=torch.float32),
requires_grad=True))
def get_filter_size(self):
return (self.neighborhood_size + 1) ** self.d1 - self.neighborhood_size ** self.d1
def forward(self, features,
in_barycentric, in_lattice_offset,
blur_neighbors,
out_barycentric, out_lattice_offset):
"""
:param features: float32 (B, C_in, N_in)
:param in_barycentric: float32 (B, d1, N_in)
:param in_lattice_offset: int64 (B, d1, N_in)
:param blur_neighbors: int64 (B, filter_size, max_hash_cnt)
:param out_barycentric: float32 (B, d1, N_out)
:param out_lattice_offset: int64 (B, d1, N_out)
:return: float32 (B, C_out, N_out) if self.sliced else (B, C_out, max_hash_cnt)
"""
# -------------------- SLICE --------------------
# if given lattice, batch size can only be 1 for now
# need to add the batch effect when doing sparse sum, then minus the batch effect when slicing
# new_lattice_offset = out_lattice_offset - (batch_indices * (max_hash_cnt + 1))[:, None, None]
# !!! ATTENTION
batch_size = features.size(0)
batch_indices = torch.arange(batch_size, dtype=torch.long)
if self.DEVICE == 'cuda':
batch_indices = batch_indices.pin_memory()
batch_indices = batch_indices.cuda(non_blocking=True)
max_hash_cnt = blur_neighbors.size(-1)
# -------------------- SPLAT --------------------
if self.do_splat:
# barycentric: (B, 1, d1, N_in), features: (B, feat_size, 1, N_in)
# (B, feat_size, d1, N_in) -> (feat_size, B * d1 * N_in)
tmp = (in_barycentric[:, None, :, :] * features[:, :, None, :]). \
permute(1, 0, 2, 3).reshape(self.num_input, -1)
tmp = tmp.t() # (B * d1 * N_in, feat_size)
# There may be -1 in blur_neighbors indicating non-existing lattice point. So need +1
# +1 also makes the first element of splatted is 0 in all channels
# lattice_offset: (B, d1, N_in)
# sparse_sum: indices, values, size, cuda
splatted = sparse_sum((in_lattice_offset + 1).reshape(1, -1), tmp,
torch.Size([batch_size * (max_hash_cnt + 1), self.num_input]),
self.DEVICE == 'cuda')
splatted = splatted.reshape(batch_size, max_hash_cnt + 1, self.num_input).permute(0, 2, 1)
# (B, feat_size, H+1)
if self.use_norm:
# for density normalization
one_features = torch.ones((batch_size, 1, features.size(-1)), dtype=torch.float32)
if self.DEVICE == 'cuda':
one_features = one_features.pin_memory()
one_features = one_features.cuda(non_blocking=True)
# (B, d1, N_in), (B, 1=feat_size, N_in) -> (B, d1, N_in)
one_tmp = (in_barycentric * one_features).reshape(1, -1) # (1, B * d1 * N_in)
one_tmp = one_tmp.t() # (B * d1 * N_in, 1)
one_splatted = sparse_sum((in_lattice_offset + 1).reshape(1, -1), one_tmp,
torch.Size([batch_size * (max_hash_cnt + 1), 1]),
self.DEVICE == 'cuda')
one_splatted = one_splatted.reshape(batch_size, max_hash_cnt + 1)
# print('normalize!')
norm = 1. / (one_splatted + 1e-5)
splatted *= norm[:, None, :]
if DELETE_TMP_VARIABLES:
del one_features, one_tmp, one_splatted
else:
# features: (B, C, max_hash_cnt) -> (B, C, max_hash_cnt+1)
splatted = torch.cat((torch.zeros((batch_size, self.num_input, 1),
dtype=features.dtype,
device=features.device),
features),
dim=-1)
# -------------------- BLUR --------------------
if self.MAX_SIZE == -1:
chunk_size = max_hash_cnt
else:
chunk_size = max(1,
min(self.MAX_SIZE // self.num_input // self.filter_size,
max_hash_cnt))
num_chunks = (max_hash_cnt + chunk_size - 1) // chunk_size
feat_blurred = []
for cidx in range(num_chunks):
start_idx = cidx * chunk_size
end_idx = min(max_hash_cnt, start_idx + chunk_size)
# splatted: (B, feat_size, max_hash_cnt+1)
# blur_neighbors: (B, filter_size, max_hash_cnt), index in the range of [-1, max_hash_cnt-1]
# spread_out: (B, feat_size, filter_size, max_hash_cnt/chunk_size)
spread_out = splatted[batch_indices[:, None, None, None],
self.feat_indices[None, :, None, None],
(blur_neighbors + 1)[:, None, :, start_idx:end_idx]]
# (B, num_input, filter_size, chunk_size)
feat_blurred_chunk = self.blur_conv(spread_out).squeeze(2) # (B, num_output, 1(squeezed), chunk_size)
feat_blurred.append(feat_blurred_chunk)
feat_blurred = torch.cat(feat_blurred, dim=-1) # (B, num_output, max_hash_cnt)
if not self.do_slice:
return feat_blurred
tmp_feat_blurred = feat_blurred[batch_indices[:, None, None, None],
self.out_indices[None, :, None, None],
out_lattice_offset[:, None, :, :]]
# (B, num_output, d1, N_out)
# barycentric: (B, d1, N_out)
sliced = (out_barycentric[:, None, :, :] * tmp_feat_blurred).sum(dim=2)
# (B, num_output, d1, N_out) -> (B, num_output, N_out)
if self.use_bias:
sliced += self.bias[None, :, None]
return sliced
| 10,021 | 40.933054 | 116 | py |
HPLFlowNet | HPLFlowNet-master/models/bnn_flow.py | import torch
import torch.nn as nn
from .bilateralNN import sparse_sum
from .module_utils import Conv2dReLU, Conv3dReLU
DELETE_TMP_VARIABLES = False
class BilateralCorrelationFlex(nn.Module):
def __init__(self, d,
corr_filter_radius, corr_corr_radius,
num_input, num_corr_output, num_output,
DEVICE,
use_bias,
use_leaky,
use_norm,
prev_corr_dim,
last_relu,
chunk_size=1024 * 1024 * 25):
"""
:param d: int (in our case, 3)
:param corr_filter_radius: int
:param corr_corr_radius: int
:param num_input: int (C_in)
:param num_corr_output: list of ints
:param num_output: list of ints
:param DEVICE: str, 'cuda' or whatever
:param use_bias: bool. used after slicing, never used in this implementation.
:param use_leaky: bool. used for conv modules
:param use_norm: bool. whether to use our normalization scheme, always set it to be true for better performance.
:param prev_corr_dim: int.
"""
super(BilateralCorrelationFlex, self).__init__()
self.d = d
self.d1 = d + 1
self.corr_size = self.get_filter_size(corr_corr_radius)
self.filter_size = self.get_filter_size(corr_filter_radius)
self.num_input = num_input
self.prev_corr_dim = prev_corr_dim
self.num_output = num_output
self.DEVICE = DEVICE
# self.use_bias = use_bias
self.use_norm = use_norm
self.last_relu = last_relu
self.MAX_SIZE = chunk_size # 1024 * 1024 * 25
# define needed buffers
self.register_buffer('feat_indices', torch.arange(num_input, dtype=torch.long))
if prev_corr_dim != 0:
self.register_buffer('feat1_indices', torch.arange(num_input + prev_corr_dim, dtype=torch.long))
else:
self.feat1_indices = self.feat_indices
num_final_output = num_output[-1]
self.register_buffer('out_indices', torch.arange(num_final_output, dtype=torch.long))
# define corr conv modules (patch correlation)
corr_sequential_list = []
n_in_channel = num_input * 2 + prev_corr_dim
for idx, n_out_channel in enumerate(num_corr_output):
if idx == 0:
kernel_size = (1, self.corr_size, 1)
else:
kernel_size = (1, 1, 1)
corr_sequential_list.append(Conv3dReLU(n_in_channel, n_out_channel, kernel_size, use_leaky=use_leaky))
n_in_channel = n_out_channel
self.corr_conv = nn.Sequential(*corr_sequential_list)
# define filter conv modules (displacement filtering)
filter_sequential_list = []
n_in_channel = num_corr_output[-1]
for idx, n_out_channel in enumerate(num_output[:-1]):
if idx == 0:
kernel_size = (self.filter_size, 1)
else:
kernel_size = (1, 1)
filter_sequential_list.append(Conv2dReLU(n_in_channel, n_out_channel, kernel_size, use_leaky=use_leaky))
n_in_channel = n_out_channel
if len(num_output) == 1:
kernel_size = (self.filter_size, 1)
else:
kernel_size = (1, 1)
if not self.last_relu:
filter_sequential_list.append(nn.Conv2d(n_in_channel, num_final_output, kernel_size=kernel_size))
else:
filter_sequential_list.append(
Conv2dReLU(n_in_channel, num_final_output, kernel_size=kernel_size, use_leaky=use_leaky))
self.blur_conv = nn.Sequential(*filter_sequential_list)
def get_filter_size(self, dist):
return (dist + 1) ** self.d1 - dist ** self.d1
def forward(self, feat1, feat2, prev_corr_feat,
barycentric1, lattice_offset1,
pc1_corr_indices, pc2_corr_indices,
max_hash_cnt1, max_hash_cnt2):
"""
:param feat1: float (B, C, max_hash_cnt1)
:param feat2: float (B, C, max_hash_cnt2)
:param prev_corr_feat: float (B, C', N_in)
# need to splat prev_corr_feat to the new scale and vertices
:param barycentric1: float (B, d1, N_in)
:param lattice_offset1: int64 (B, d1, N_in)
:param pc1_corr_indices: int64 (B, corr_corr_size, max_hash_cnt1)
:param pc2_corr_indices: int64 (B, corr_filter_size, corr_corr_size, max_hash_cnt1)
:param max_hash_cnt1: int
:param max_hash_cnt2: int
:return:
"""
batch_size = feat1.size(0)
batch_indices = torch.arange(batch_size, dtype=torch.long)
if self.DEVICE == 'cuda':
batch_indices = batch_indices.pin_memory().cuda(non_blocking=True)
if prev_corr_feat is not None:
# -------------------- SPLAT --------------------
# barycentric: (B, 1, d1, N), features: (B, feat_size, 1, N)
tmp1 = (barycentric1[:, None, :, :] * prev_corr_feat[:, :, None, :]).permute(1, 0, 2, 3) \
.reshape(self.prev_corr_dim, -1)
# (B, feat_size, d1, N) -> (feat_size, B * d1 * N)
tmp1 = tmp1.t()
# plus one makes the first element of splatted is 0 in all channels
prev_splatted1 = sparse_sum((lattice_offset1 + 1).reshape(1, -1), tmp1,
torch.Size([batch_size * (max_hash_cnt1 + 1), self.prev_corr_dim]),
self.DEVICE == 'cuda')
prev_splatted1 = prev_splatted1.reshape(batch_size, max_hash_cnt1 + 1, self.prev_corr_dim).permute(0, 2, 1)
if self.use_norm:
# for density normalization
one_feat1 = torch.ones((batch_size, 1, prev_corr_feat.size(-1)), dtype=torch.float32)
if self.DEVICE == 'cuda':
one_feat1 = one_feat1.pin_memory().cuda(non_blocking=True)
# (B, d1, N), (B, 1=feat_size, N) -> (B, d1, N)
one_tmp1 = (barycentric1 * one_feat1).reshape(1, -1) # (1, B * d1 * N)
one_tmp1 = one_tmp1.t()
# FLOP (B=1): d1 * N_in_prev
one_splatted1 = sparse_sum((lattice_offset1 + 1).reshape(1, -1), one_tmp1,
torch.Size([batch_size * (max_hash_cnt1 + 1), 1]),
self.DEVICE == 'cuda')
one_splatted1 = one_splatted1.reshape(batch_size, max_hash_cnt1 + 1)
# print('normalize!')
norm1 = 1. / (one_splatted1 + 1e-5)
prev_splatted1 *= norm1[:, None, :]
if DELETE_TMP_VARIABLES:
del one_feat1, one_tmp1, one_splatted1
splatted1 = torch.cat((torch.zeros((batch_size, self.num_input, 1),
dtype=feat1.dtype,
device=feat1.device),
feat1),
dim=-1)
splatted2 = torch.cat((torch.zeros((batch_size, self.num_input, 1),
dtype=feat2.dtype,
device=feat2.device),
feat2),
dim=-1)
if prev_corr_feat is not None:
splatted1 = torch.cat((prev_splatted1, splatted1), dim=1)
# -------------------- BLUR --------------------
if self.MAX_SIZE == -1:
chunk_size = max_hash_cnt1
else:
chunk_size = max(1,
min(self.MAX_SIZE // (
self.num_input * 2 + self.prev_corr_dim) // self.filter_size // self.corr_size,
max_hash_cnt1))
num_chunks = (max_hash_cnt1 + chunk_size - 1) // chunk_size
corr_blurred = []
for cidx in range(num_chunks):
start = cidx * chunk_size
end = min(max_hash_cnt1, start + chunk_size)
# splatted: (B, feat_size, max_hash_cnt+1)
# pc1_corr_indices: (B, corr_corr_size, max_hash_cnt1)
# spread_out1: (B, feat_size, corr_corr_size, chunk_size/max_hash_cnt1+1)
spread_out1 = splatted1[batch_indices[:, None, None, None],
self.feat1_indices[None, :, None, None],
(pc1_corr_indices + 1)[:, None, :, start:end]]
spread_out1 = spread_out1[:, :, None, :, :].repeat(1, 1, self.filter_size, 1, 1)
# spread_out2: (B, feat_size, corr_filter_size, corr_corr_size, chunk_size/max_hash_cnt1+1)
spread_out2 = splatted2[batch_indices[:, None, None, None, None],
self.feat_indices[None, :, None, None, None],
(pc2_corr_indices + 1)[:, None, :, :, start:end]]
combined_input = torch.cat((spread_out1, spread_out2), dim=1)
# (B, 2*feat_size+prev_corr_size, corr_filter_size, corr_corr_size, chunk_size/max_hash_cnt1)
correlated = self.corr_conv(combined_input).squeeze(
3) # (B, num_corr_output[-1], filter_size, 1--squeezed, chunk_size/max_hash_cnt1)
corr_blurred_chunk = self.blur_conv(correlated).squeeze(2)
# (B, num_output, 1--squeezed, chunk_size/max_hash_cnt1)
corr_blurred.append(corr_blurred_chunk)
corr_blurred = torch.cat(corr_blurred, dim=-1) # (B, C_out, max_hash_cnt1)
return corr_blurred
| 9,641 | 44.267606 | 120 | py |
HPLFlowNet | HPLFlowNet-master/models/epe3d_loss.py | import torch
import torch.nn as nn
class EPE3DLoss(nn.Module):
def __init__(self):
super(EPE3DLoss, self).__init__()
def forward(self, input, target):
return torch.norm(input - target, p=2, dim=1) | 223 | 21.4 | 53 | py |
HPLFlowNet | HPLFlowNet-master/models/module_utils.py | import torch
import torch.nn as nn
__all__ = ['Conv1dReLU', 'Conv2dReLU', 'Conv3dReLU']
LEAKY_RATE = 0.1
class Conv1dReLU(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, use_leaky=False, bias=True):
super(Conv1dReLU, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
relu = nn.ReLU(inplace=True) if not use_leaky else nn.LeakyReLU(LEAKY_RATE, inplace=True)
self.composed_module = nn.Sequential(
nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias),
relu
)
def forward(self, x):
x = self.composed_module(x)
return x
class Conv2dReLU(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, use_leaky=False, bias=True):
super(Conv2dReLU, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
relu = nn.ReLU(inplace=True) if not use_leaky else nn.LeakyReLU(LEAKY_RATE, inplace=True)
self.composed_module = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias),
relu
)
def forward(self, x):
x = self.composed_module(x)
return x
class Conv3dReLU(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, use_leaky=False, bias=True):
super(Conv3dReLU, self).__init__()
relu = nn.ReLU(inplace=True) if not use_leaky else nn.LeakyReLU(LEAKY_RATE, inplace=True)
self.composed_module = nn.Sequential(
nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias),
relu
)
def forward(self, x):
x = self.composed_module(x)
return x
| 2,027 | 31.190476 | 117 | py |
HPLFlowNet | HPLFlowNet-master/datasets/kitti.py | import sys, os
import os.path as osp
import numpy as np
import torch.utils.data as data
__all__ = ['KITTI']
class KITTI(data.Dataset):
"""
Args:
train (bool): If True, creates dataset from training set, otherwise creates from test set.
transform (callable):
gen_func (callable):
args:
"""
def __init__(self,
train,
transform,
gen_func,
args
):
self.root = osp.join(args.data_root, 'KITTI_processed_occ_final')
assert train is False
self.train = train
self.transform = transform
self.gen_func = gen_func
self.num_points = args.num_points
self.remove_ground = args.remove_ground
self.samples = self.make_dataset()
if len(self.samples) == 0:
raise (RuntimeError("Found 0 files in subfolders of: " + self.root + "\n"))
def __len__(self):
return len(self.samples)
def __getitem__(self, index):
pc1_loaded, pc2_loaded = self.pc_loader(self.samples[index])
pc1_transformed, pc2_transformed, sf_transformed = self.transform([pc1_loaded, pc2_loaded])
if pc1_transformed is None:
print('path {} get pc1 is None'.format(self.samples[index]), flush=True)
index = np.random.choice(range(self.__len__()))
return self.__getitem__(index)
pc1, pc2, sf, generated_data = self.gen_func([pc1_transformed,
pc2_transformed,
sf_transformed])
return pc1, pc2, sf, generated_data, self.samples[index]
def __repr__(self):
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Number of points per point cloud: {}\n'.format(self.num_points)
fmt_str += ' is removing ground: {}\n'.format(self.remove_ground)
fmt_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str
def make_dataset(self):
do_mapping = True
root = osp.realpath(osp.expanduser(self.root))
all_paths = sorted(os.walk(root))
useful_paths = [item[0] for item in all_paths if len(item[1]) == 0]
try:
assert (len(useful_paths) == 200)
except AssertionError:
print('assert (len(useful_paths) == 200) failed!', len(useful_paths))
if do_mapping:
mapping_path = osp.join(osp.dirname(__file__), 'KITTI_mapping.txt')
print('mapping_path', mapping_path)
with open(mapping_path) as fd:
lines = fd.readlines()
lines = [line.strip() for line in lines]
useful_paths = [path for path in useful_paths if lines[int(osp.split(path)[-1])] != '']
res_paths = useful_paths
return res_paths
def pc_loader(self, path):
"""
Args:
path:
Returns:
pc1: ndarray (N, 3) np.float32
pc2: ndarray (N, 3) np.float32
"""
pc1 = np.load(osp.join(path, 'pc1.npy')) #.astype(np.float32)
pc2 = np.load(osp.join(path, 'pc2.npy')) #.astype(np.float32)
if self.remove_ground:
is_ground = np.logical_and(pc1[:,1] < -1.4, pc2[:,1] < -1.4)
not_ground = np.logical_not(is_ground)
pc1 = pc1[not_ground]
pc2 = pc2[not_ground]
return pc1, pc2
| 3,701 | 33.277778 | 105 | py |
HPLFlowNet | HPLFlowNet-master/datasets/flyingthings3d_subset.py | import sys, os
import os.path as osp
import numpy as np
import torch.utils.data as data
__all__ = ['FlyingThings3DSubset']
class FlyingThings3DSubset(data.Dataset):
"""
Args:
train (bool): If True, creates dataset from training set, otherwise creates from test set.
transform (callable):
gen_func (callable):
args:
"""
def __init__(self,
train,
transform,
gen_func,
args):
self.root = osp.join(args.data_root, 'FlyingThings3D_subset_processed_35m')
self.train = train
self.transform = transform
self.gen_func = gen_func
self.num_points = args.num_points
full = hasattr(args, 'full') and args.full
self.samples = self.make_dataset(full)
if len(self.samples) == 0:
raise (RuntimeError("Found 0 files in subfolders of: " + self.root + "\n"))
def __len__(self):
return len(self.samples)
def __getitem__(self, index):
pc1_loaded, pc2_loaded = self.pc_loader(self.samples[index])
pc1_transformed, pc2_transformed, sf_transformed = self.transform([pc1_loaded, pc2_loaded])
if pc1_transformed is None:
print('path {} get pc1 is None'.format(self.samples[index]), flush=True)
index = np.random.choice(range(self.__len__()))
return self.__getitem__(index)
pc1, pc2, sf, generated_data = self.gen_func([pc1_transformed,
pc2_transformed,
sf_transformed])
return pc1, pc2, sf, generated_data, self.samples[index]
def __repr__(self):
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Number of points per point cloud: {}\n'.format(self.num_points)
fmt_str += ' is training: {}\n'.format(self.train)
fmt_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str
def make_dataset(self, full):
root = osp.realpath(osp.expanduser(self.root))
root = osp.join(root, 'train') if self.train else osp.join(root, 'val')
all_paths = os.walk(root)
useful_paths = sorted([item[0] for item in all_paths if len(item[1]) == 0])
try:
if self.train:
assert (len(useful_paths) == 19640)
else:
assert (len(useful_paths) == 3824)
except AssertionError:
print('len(useful_paths) assert error', len(useful_paths))
sys.exit(1)
if not full:
res_paths = useful_paths[::4]
else:
res_paths = useful_paths
return res_paths
def pc_loader(self, path):
"""
Args:
path: path to a dir, e.g., home/xiuye/share/data/Driving_processed/35mm_focallength/scene_forwards/slow/0791
Returns:
pc1: ndarray (N, 3) np.float32
pc2: ndarray (N, 3) np.float32
"""
pc1 = np.load(osp.join(path, 'pc1.npy'))
pc2 = np.load(osp.join(path, 'pc2.npy'))
# multiply -1 only for subset datasets
pc1[..., -1] *= -1
pc2[..., -1] *= -1
pc1[..., 0] *= -1
pc2[..., 0] *= -1
return pc1, pc2
| 3,536 | 33.676471 | 120 | py |
HPLFlowNet | HPLFlowNet-master/transforms/functional.py | import torch
def to_tensor(array):
"""Convert a 2D `numpy.ndarray`` to tensor, do transpose first.
See ``ToTensor`` for more details.
Args:
array (numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
assert len(array.shape) == 2
array = array.transpose((1, 0))
return torch.from_numpy(array)
| 381 | 18.1 | 67 | py |
HPLFlowNet | HPLFlowNet-master/transforms/transforms.py | import os, sys
import os.path as osp
from collections import defaultdict
import numbers
import math
import numpy as np
import traceback
import time
import torch
import numba
from numba import njit, cffi_support
from . import functional as F
sys.path.append(osp.join(osp.dirname(osp.dirname(osp.abspath(__file__))), 'models'))
import _khash_ffi
cffi_support.register_module(_khash_ffi)
khash_init = _khash_ffi.lib.khash_int2int_init
khash_get = _khash_ffi.lib.khash_int2int_get
khash_set = _khash_ffi.lib.khash_int2int_set
khash_destroy = _khash_ffi.lib.khash_int2int_destroy
# ---------- BASIC operations ----------
class Compose(object):
"""Composes several transforms together.
Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
Example:
>>> transforms.Compose([
>>> transforms.CenterCrop(10),
>>> transforms.ToTensor(),
>>> ])
"""
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, data):
for t in self.transforms:
data = t(data)
return data
def __repr__(self):
format_string = self.__class__.__name__ + '('
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
class ToTensor(object):
def __call__(self, pic):
if not isinstance(pic, np.ndarray):
return pic
else:
return F.to_tensor(pic)
def __repr__(self):
return self.__class__.__name__ + '()'
# ---------- Build permutalhedral lattice ----------
@njit(numba.int64(numba.int64[:], numba.int64, numba.int64[:], numba.int64[:], ))
def key2int(key, dim, key_maxs, key_mins):
"""
:param key: np.array
:param dim: int
:param key_maxs: np.array
:param key_mins: np.array
:return:
"""
tmp_key = key - key_mins
scales = key_maxs - key_mins + 1
res = 0
for idx in range(dim):
res += tmp_key[idx]
res *= scales[idx + 1]
res += tmp_key[dim]
return res
@njit(numba.int64[:](numba.int64, numba.int64, numba.int64[:], numba.int64[:], ))
def int2key(int_key, dim, key_maxs, key_mins):
key = np.empty((dim + 1,), dtype=np.int64)
scales = key_maxs - key_mins + 1
for idx in range(dim, 0, -1):
key[idx] = int_key % scales[idx]
int_key -= key[idx]
int_key //= scales[idx]
key[0] = int_key
key += key_mins
return key
@njit
def advance_in_dimension(d1, increment, adv_dim, key):
key_cp = key.copy()
key_cp -= increment
key_cp[adv_dim] += increment * d1
return key_cp
class Traverse:
def __init__(self, neighborhood_size, d):
self.neighborhood_size = neighborhood_size
self.d = d
def go(self, start_key, hash_table_list):
walking_keys = np.empty((self.d + 1, self.d + 1), dtype=np.long)
self.walk_cuboid(start_key, 0, False, walking_keys, hash_table_list)
def walk_cuboid(self, start_key, d, has_zero, walking_keys, hash_table_list):
if d <= self.d:
walking_keys[d] = start_key.copy()
range_end = self.neighborhood_size + 1 if (has_zero or (d < self.d)) else 1
for i in range(range_end):
self.walk_cuboid(walking_keys[d], d + 1, has_zero or (i == 0), walking_keys, hash_table_list)
walking_keys[d] = advance_in_dimension(self.d + 1, 1, d, walking_keys[d])
else:
hash_table_list.append(start_key.copy())
@njit
def build_unsymmetric(pc1_num_points, pc2_num_points,
d1, bcn_filter_size, corr_filter_size, corr_corr_size,
pc1_keys_np, pc2_keys_np,
key_maxs, key_mins,
pc1_lattice_offset, pc2_lattice_offset,
bcn_filter_offsets,
pc1_blur_neighbors, pc2_blur_neighbors,
corr_filter_offsets, corr_corr_offsets,
pc1_corr_indices, pc2_corr_indices,
last_pc1, last_pc2,
assign_last):
"""
:param pc1_num_points: int. Given
:param pc2_num_points: int. Given
:param d1: int. Given
:param bcn_filter_size: int. Given. -1 indicates "do not filter"
:param corr_filter_size: int. Displacement filtering radius. Given. -1 indicates "do not filter"
:param corr_corr_size: int. Patch correlation radius. Given. -1 indicates "do not filter"
:param pc1_keys_np: (d1, N, d1) long. Given. lattice points coordinates
:param pc2_keys_np:
:param key_maxs: (d1,) long. Given
:param key_mins:
:param pc1_lattice_offset: (d1, N) long. hash indices for pc1_keys_np
:param pc2_lattice_offset:
:param bcn_filter_offsets: (bcn_filter_size, d1) long. Given.
:param pc1_blur_neighbors: (bcn_filter_size, pc1_hash_cnt) long. hash indices. -1 means not in the hash table
:param pc2_blur_neighbors: (bcn_filter_size, pc2_hash_cnt)
:param corr_filter_offsets: (corr_filter_size, d1) long. Given.
:param corr_corr_offsets: (corr_corr_size, d1) long. Given.
:param pc1_corr_indices: (corr_corr_size, pc1_hash_cnt) long. hash indices
:param pc2_corr_indices: (corr_filter_size, corr_corr_size, pc1_hash_cnt) long. hash indices
:param last_pc1: (d1, pc1_hash_cnt). permutohedral coordiantes for the next scale.
:param last_pc2: (d1, pc2_hash_cnt)
:return:
"""
# build hash table
hash_table1 = khash_init() # key to hash index
key_hash_table1 = khash_init() # hash index to key
hash_table2 = khash_init()
if bcn_filter_size != -1:
key_hash_table2 = khash_init()
hash_cnt1 = 0
hash_cnt2 = 0
for point_idx in range(pc1_num_points):
for remainder in range(d1):
key_int1 = key2int(pc1_keys_np[:, point_idx, remainder], d1 - 1, key_maxs, key_mins)
hash_idx1 = khash_get(hash_table1, key_int1, -1)
if hash_idx1 == -1:
# insert lattice into hash table
khash_set(hash_table1, key_int1, hash_cnt1)
khash_set(key_hash_table1, hash_cnt1, key_int1)
hash_idx1 = hash_cnt1
if assign_last:
last_pc1[:, hash_idx1] = pc1_keys_np[:, point_idx, remainder]
hash_cnt1 += 1
pc1_lattice_offset[remainder, point_idx] = hash_idx1
for point_idx in range(pc2_num_points):
for remainder in range(d1):
key_int2 = key2int(pc2_keys_np[:, point_idx, remainder], d1 - 1, key_maxs, key_mins)
hash_idx2 = khash_get(hash_table2, key_int2, -1)
if hash_idx2 == -1:
khash_set(hash_table2, key_int2, hash_cnt2)
if bcn_filter_size != -1:
khash_set(key_hash_table2, hash_cnt2, key_int2)
hash_idx2 = hash_cnt2
if assign_last:
last_pc2[:, hash_idx2] = pc2_keys_np[:, point_idx, remainder]
hash_cnt2 += 1
pc2_lattice_offset[remainder, point_idx] = hash_idx2
for hash_idx in range(hash_cnt1):
pc1_int_key = khash_get(key_hash_table1, hash_idx, -1)
pc1_key = int2key(pc1_int_key, d1 - 1, key_maxs, key_mins)
if bcn_filter_size != -1:
neighbor_keys = pc1_key + bcn_filter_offsets # (#pts in the filter, d)
for bcn_filter_index in range(bcn_filter_size):
pc1_blur_neighbors[bcn_filter_index, hash_idx] = khash_get(hash_table1,
key2int(neighbor_keys[bcn_filter_index, :],
d1 - 1,
key_maxs,
key_mins),
-1)
if corr_filter_size != -1:
corr_pc1_keys = pc1_key + corr_corr_offsets # (#pts in the filter, d)
for corr_index in range(corr_corr_size):
corr_pc1_key = corr_pc1_keys[corr_index, :]
pc1_corr_indices[corr_index, hash_idx] = khash_get(hash_table1,
key2int(corr_pc1_key, d1 - 1,
key_maxs,
key_mins),
-1)
corr_pc2_keys = corr_pc1_key + corr_filter_offsets
for filter_index in range(corr_filter_size):
corr_pc2_key = corr_pc2_keys[filter_index, :]
pc2_corr_indices[filter_index, corr_index, hash_idx] = khash_get(hash_table2,
key2int(corr_pc2_key,
d1 - 1,
key_maxs,
key_mins),
-1)
if bcn_filter_size != -1:
for hash_idx in range(hash_cnt2):
pc2_int_key = khash_get(key_hash_table2, hash_idx, -1)
pc2_key = int2key(pc2_int_key, d1 - 1, key_maxs, key_mins)
neighbor_keys = pc2_key + bcn_filter_offsets
for bcn_filter_index in range(bcn_filter_size):
pc2_blur_neighbors[bcn_filter_index, hash_idx] = khash_get(hash_table2,
key2int(neighbor_keys[bcn_filter_index, :],
d1 - 1,
key_maxs,
key_mins),
-1)
# destroy hash table
khash_destroy(hash_table1)
khash_destroy(key_hash_table1)
khash_destroy(hash_table2)
if bcn_filter_size != -1:
khash_destroy(key_hash_table2)
class GenerateDataUnsymmetric(object):
def __init__(self, args):
self.d = args.dim
d = args.dim
self.d1 = self.d + 1
self.scales_filter_map = args.scales_filter_map
elevate_left = torch.ones((self.d1, self.d), dtype=torch.float32).triu()
elevate_left[1:, ] += torch.diag(torch.arange(-1, -d - 1, -1, dtype=torch.float32))
elevate_right = torch.diag(1. / (torch.arange(1, d + 1, dtype=torch.float32) *
torch.arange(2, d + 2, dtype=torch.float32)).sqrt())
self.expected_std = (d + 1) * math.sqrt(2 / 3)
self.elevate_mat = torch.mm(elevate_left, elevate_right)
# (d+1,d)
del elevate_left, elevate_right
# canonical
canonical = torch.arange(d + 1, dtype=torch.long)[None, :].repeat(d + 1, 1)
# (d+1, d+1)
for i in range(1, d + 1):
canonical[-i:, i] = i - d - 1
self.canonical = canonical
self.dim_indices = torch.arange(d + 1, dtype=torch.long)[:, None]
self.radius2offset = {}
radius_set = set([item for line in self.scales_filter_map for item in line[1:] if item != -1])
for radius in radius_set:
hash_table = []
center = np.array([0] * self.d1, dtype=np.long)
traversal = Traverse(radius, self.d)
traversal.go(center, hash_table)
self.radius2offset[radius] = np.vstack(hash_table)
def get_keys_and_barycentric(self, pc):
"""
:param pc: (self.d, N -- undefined)
:return:
"""
num_points = pc.size(-1)
point_indices = torch.arange(num_points, dtype=torch.long)[None, :]
elevated = torch.matmul(self.elevate_mat, pc) * self.expected_std # (d+1, N)
# find 0-remainder
greedy = torch.round(elevated / self.d1) * self.d1 # (d+1, N)
el_minus_gr = elevated - greedy
rank = torch.sort(el_minus_gr, dim=0, descending=True)[1]
# the following advanced indexing is different in PyTorch 0.4.0 and 1.0.0
#rank[rank, point_indices] = self.dim_indices # works in PyTorch 0.4.0 but fail in PyTorch 1.x
index = rank.clone()
rank[index, point_indices] = self.dim_indices # works both in PyTorch 1.x(has tested in PyTorch 1.2) and PyTorch 0.4.0
del index
remainder_sum = greedy.sum(dim=0, keepdim=True) / self.d1
rank_float = rank.type(torch.float32)
cond_mask = ((rank_float >= self.d1 - remainder_sum) * (remainder_sum > 0) + \
(rank_float < -remainder_sum) * (remainder_sum < 0)) \
.type(torch.float32)
sum_gt_zero_mask = (remainder_sum > 0).type(torch.float32)
sum_lt_zero_mask = (remainder_sum < 0).type(torch.float32)
sign_mask = -1 * sum_gt_zero_mask + sum_lt_zero_mask
greedy += self.d1 * sign_mask * cond_mask
rank += (self.d1 * sign_mask * cond_mask).type_as(rank)
rank += remainder_sum.type(torch.long)
# barycentric
el_minus_gr = elevated - greedy
greedy = greedy.type(torch.long)
barycentric = torch.zeros((self.d1 + 1, num_points), dtype=torch.float32)
barycentric[self.d - rank, point_indices] += el_minus_gr
barycentric[self.d1 - rank, point_indices] -= el_minus_gr
barycentric /= self.d1
barycentric[0, point_indices] += 1. + barycentric[self.d1, point_indices]
barycentric = barycentric[:-1, :]
keys = greedy[:, :, None] + self.canonical[rank, :] # (d1, num_points, d1)
# rank: rearrange the coordinates of the canonical
keys_np = keys.numpy()
del elevated, greedy, rank, remainder_sum, rank_float, \
cond_mask, sum_gt_zero_mask, sum_lt_zero_mask, sign_mask
return keys_np, barycentric, el_minus_gr
def get_filter_size(self, radius):
return (radius + 1) ** self.d1 - radius ** self.d1
def __call__(self, data):
pc1, pc2, sf = data
if pc1 is None:
return None, None, None, None
with torch.no_grad():
pc1 = torch.from_numpy(pc1.T)
pc2 = torch.from_numpy(pc2.T)
sf = torch.from_numpy(sf.T)
generated_data = []
last_pc1 = pc1.clone()
last_pc2 = pc2.clone()
pc1_num_points = pc1.size(-1)
pc2_num_points = pc2.size(-1)
for idx, (scale, bcn_filter_raidus, corr_filter_radius, corr_corr_radius) in enumerate(
self.scales_filter_map):
last_pc1[:3, :] *= scale
last_pc2[:3, :] *= scale
pc1_keys_np, pc1_barycentric, pc1_el_minus_gr = self.get_keys_and_barycentric(last_pc1)
pc2_keys_np, pc2_barycentric, pc2_el_minus_gr = self.get_keys_and_barycentric(last_pc2)
# keys: (d1, N, d1) [[:, point_idx, remainder_idx]], barycentric: (d1, N), el_minus_gr: (d1, N)
key_maxs = np.maximum(pc1_keys_np.max(-1).max(-1), pc2_keys_np.max(-1).max(-1))
key_mins = np.minimum(pc1_keys_np.min(-1).min(-1), pc2_keys_np.min(-1).min(-1))
pc1_keys_set = set(map(tuple, pc1_keys_np.reshape(self.d1, -1).T))
pc2_keys_set = set(map(tuple, pc2_keys_np.reshape(self.d1, -1).T))
pc1_hash_cnt = len(pc1_keys_set)
pc2_hash_cnt = len(pc2_keys_set)
pc1_lattice_offset = np.empty((self.d1, pc1_num_points), dtype=np.int64)
pc2_lattice_offset = np.empty((self.d1, pc2_num_points), dtype=np.int64)
if bcn_filter_raidus != -1:
bcn_filter_size = self.get_filter_size(bcn_filter_raidus)
pc1_blur_neighbors = np.empty((bcn_filter_size, pc1_hash_cnt), dtype=np.int64)
pc1_blur_neighbors.fill(-1)
pc2_blur_neighbors = np.empty((bcn_filter_size, pc2_hash_cnt), dtype=np.int64)
pc2_blur_neighbors.fill(-1)
bcn_filter_offsets = self.radius2offset[bcn_filter_raidus]
else:
bcn_filter_size = -1
pc1_blur_neighbors = np.zeros((1, 1), dtype=np.int64)
pc2_blur_neighbors = np.zeros((1, 1), dtype=np.int64)
bcn_filter_offsets = np.zeros((1, 1), dtype=np.int64)
if corr_filter_radius != -1:
corr_filter_size = self.get_filter_size(corr_filter_radius)
corr_corr_size = self.get_filter_size(corr_corr_radius)
pc1_corr_indices = np.empty((corr_corr_size, pc1_hash_cnt), dtype=np.int64)
pc1_corr_indices.fill(-1)
pc2_corr_indices = np.empty((corr_filter_size, corr_corr_size, pc1_hash_cnt), dtype=np.int64)
pc2_corr_indices.fill(-1)
corr_filter_offsets, corr_corr_offsets = self.radius2offset[corr_filter_radius], \
self.radius2offset[corr_corr_radius]
else:
corr_filter_size = -1
corr_corr_size = -1
pc1_corr_indices = np.zeros((1, 1, 1), dtype=np.int64)
pc2_corr_indices = np.zeros((1, 1, 1), dtype=np.int64)
corr_filter_offsets, corr_corr_offsets = np.zeros((1, 1), dtype=np.int64), np.zeros((1, 1),
dtype=np.int64)
if idx != len(self.scales_filter_map) - 1:
last_pc1 = np.empty((self.d1, pc1_hash_cnt), dtype=np.float32)
last_pc2 = np.empty((self.d1, pc2_hash_cnt), dtype=np.float32)
else:
last_pc1 = np.zeros((1, 1), dtype=np.float32)
last_pc2 = np.zeros((1, 1), dtype=np.float32)
build_unsymmetric(pc1_num_points, pc2_num_points,
self.d1, bcn_filter_size, corr_filter_size, corr_corr_size,
pc1_keys_np, pc2_keys_np,
key_maxs, key_mins,
pc1_lattice_offset, pc2_lattice_offset,
bcn_filter_offsets,
pc1_blur_neighbors, pc2_blur_neighbors,
corr_filter_offsets, corr_corr_offsets,
pc1_corr_indices, pc2_corr_indices,
last_pc1, last_pc2,
idx != len(self.scales_filter_map) - 1)
pc1_lattice_offset = torch.from_numpy(pc1_lattice_offset)
pc2_lattice_offset = torch.from_numpy(pc2_lattice_offset)
if bcn_filter_size != -1:
pc1_blur_neighbors = torch.from_numpy(pc1_blur_neighbors)
pc2_blur_neighbors = torch.from_numpy(pc2_blur_neighbors)
else:
pc1_blur_neighbors = torch.zeros(1, dtype=torch.long)
pc2_blur_neighbors = torch.zeros(1, dtype=torch.long)
if corr_filter_size != -1:
pc1_corr_indices = torch.from_numpy(pc1_corr_indices)
pc2_corr_indices = torch.from_numpy(pc2_corr_indices)
else:
pc1_corr_indices = torch.zeros(1, dtype=torch.long)
pc2_corr_indices = torch.zeros(1, dtype=torch.long)
if idx != len(self.scales_filter_map) - 1:
last_pc1 = torch.from_numpy(last_pc1)
last_pc2 = torch.from_numpy(last_pc2)
last_pc1 /= self.expected_std * scale
last_pc2 /= self.expected_std * scale
last_pc1 = torch.matmul(self.elevate_mat.t(), last_pc1)
last_pc2 = torch.matmul(self.elevate_mat.t(), last_pc2)
pc1_num_points = pc1_hash_cnt
pc2_num_points = pc2_hash_cnt
generated_data.append({'pc1_barycentric': pc1_barycentric,
'pc2_barycentric': pc2_barycentric,
'pc1_el_minus_gr': pc1_el_minus_gr,
'pc2_el_minus_gr': pc2_el_minus_gr,
'pc1_lattice_offset': pc1_lattice_offset,
'pc2_lattice_offset': pc2_lattice_offset,
'pc1_blur_neighbors': pc1_blur_neighbors,
'pc2_blur_neighbors': pc2_blur_neighbors,
'pc1_corr_indices': pc1_corr_indices,
'pc2_corr_indices': pc2_corr_indices,
'pc1_hash_cnt': pc1_hash_cnt,
'pc2_hash_cnt': pc2_hash_cnt,
})
return pc1, pc2, sf, generated_data
def __repr__(self):
format_string = self.__class__.__name__ + '\n(scales_filter_map: {}\n'.format(self.scales_filter_map)
format_string += ')'
return format_string
# ---------- MAIN operations ----------
class ProcessData(object):
def __init__(self, data_process_args, num_points, allow_less_points):
self.DEPTH_THRESHOLD = data_process_args['DEPTH_THRESHOLD']
self.no_corr = data_process_args['NO_CORR']
self.num_points = num_points
self.allow_less_points = allow_less_points
def __call__(self, data):
pc1, pc2 = data
if pc1 is None:
return None, None, None,
sf = pc2[:, :3] - pc1[:, :3]
if self.DEPTH_THRESHOLD > 0:
near_mask = np.logical_and(pc1[:, 2] < self.DEPTH_THRESHOLD, pc2[:, 2] < self.DEPTH_THRESHOLD)
else:
near_mask = np.ones(pc1.shape[0], dtype=np.bool)
indices = np.where(near_mask)[0]
if len(indices) == 0:
print('indices = np.where(mask)[0], len(indices) == 0')
return None, None, None
if self.num_points > 0:
try:
sampled_indices1 = np.random.choice(indices, size=self.num_points, replace=False, p=None)
if self.no_corr:
sampled_indices2 = np.random.choice(indices, size=self.num_points, replace=False, p=None)
else:
sampled_indices2 = sampled_indices1
except ValueError:
if not self.allow_less_points:
print('Cannot sample {} points'.format(self.num_points))
return None, None, None
else:
sampled_indices1 = indices
sampled_indices2 = indices
else:
sampled_indices1 = indices
sampled_indices2 = indices
pc1 = pc1[sampled_indices1]
sf = sf[sampled_indices1]
pc2 = pc2[sampled_indices2]
return pc1, pc2, sf
def __repr__(self):
format_string = self.__class__.__name__ + '\n(data_process_args: \n'
format_string += '\tDEPTH_THRESHOLD: {}\n'.format(self.DEPTH_THRESHOLD)
format_string += '\tNO_CORR: {}\n'.format(self.no_corr)
format_string += '\tallow_less_points: {}\n'.format(self.allow_less_points)
format_string += '\tnum_points: {}\n'.format(self.num_points)
format_string += ')'
return format_string
class Augmentation(object):
def __init__(self, aug_together_args, aug_pc2_args, data_process_args, num_points, allow_less_points=False):
self.together_args = aug_together_args
self.pc2_args = aug_pc2_args
self.DEPTH_THRESHOLD = data_process_args['DEPTH_THRESHOLD']
self.no_corr = data_process_args['NO_CORR']
self.num_points = num_points
self.allow_less_points = allow_less_points
def __call__(self, data):
pc1, pc2 = data
if pc1 is None:
return None, None, None
# together, order: scale, rotation, shift, jitter
# scale
scale = np.diag(np.random.uniform(self.together_args['scale_low'],
self.together_args['scale_high'],
3).astype(np.float32))
# rotation
angle = np.random.uniform(-self.together_args['degree_range'],
self.together_args['degree_range'])
cosval = np.cos(angle)
sinval = np.sin(angle)
rot_matrix = np.array([[cosval, 0, sinval],
[0, 1, 0],
[-sinval, 0, cosval]], dtype=np.float32)
matrix = scale.dot(rot_matrix.T)
# shift
shifts = np.random.uniform(-self.together_args['shift_range'],
self.together_args['shift_range'],
(1, 3)).astype(np.float32)
# jitter
jitter = np.clip(self.together_args['jitter_sigma'] * np.random.randn(pc1.shape[0], 3),
-self.together_args['jitter_clip'],
self.together_args['jitter_clip']).astype(np.float32)
bias = shifts + jitter
pc1[:, :3] = pc1[:, :3].dot(matrix) + bias
pc2[:, :3] = pc2[:, :3].dot(matrix) + bias
# pc2, order: rotation, shift, jitter
# rotation
angle2 = np.random.uniform(-self.pc2_args['degree_range'],
self.pc2_args['degree_range'])
cosval2 = np.cos(angle2)
sinval2 = np.sin(angle2)
matrix2 = np.array([[cosval2, 0, sinval2],
[0, 1, 0],
[-sinval2, 0, cosval2]], dtype=pc1.dtype)
# shift
shifts2 = np.random.uniform(-self.pc2_args['shift_range'],
self.pc2_args['shift_range'],
(1, 3)).astype(np.float32)
pc2[:, :3] = pc2[:, :3].dot(matrix2.T) + shifts2
sf = pc2[:, :3] - pc1[:, :3]
if not self.no_corr:
jitter2 = np.clip(self.pc2_args['jitter_sigma'] * np.random.randn(pc1.shape[0], 3),
-self.pc2_args['jitter_clip'],
self.pc2_args['jitter_clip']).astype(np.float32)
pc2[:, :3] += jitter2
if self.DEPTH_THRESHOLD > 0:
near_mask = np.logical_and(pc1[:, 2] < self.DEPTH_THRESHOLD, pc2[:, 2] < self.DEPTH_THRESHOLD)
else:
near_mask = np.ones(pc1.shape[0], dtype=np.bool)
indices = np.where(near_mask)[0]
if len(indices) == 0:
print('indices = np.where(mask)[0], len(indices) == 0')
return None, None, None
if self.num_points > 0:
try:
sampled_indices1 = np.random.choice(indices, size=self.num_points, replace=False, p=None)
if self.no_corr:
sampled_indices2 = np.random.choice(indices, size=self.num_points, replace=False, p=None)
else:
sampled_indices2 = sampled_indices1
except ValueError:
if not self.allow_less_points:
print('Cannot sample {} points'.format(self.num_points))
return None, None, None
else:
sampled_indices1 = indices
sampled_indices2 = indices
else:
sampled_indices1 = indices
sampled_indices2 = indices
pc1 = pc1[sampled_indices1]
pc2 = pc2[sampled_indices2]
sf = sf[sampled_indices1]
return pc1, pc2, sf
def __repr__(self):
format_string = self.__class__.__name__ + '\n(together_args: \n'
for key in sorted(self.together_args.keys()):
format_string += '\t{:10s} {}\n'.format(key, self.together_args[key])
format_string += '\npc2_args: \n'
for key in sorted(self.pc2_args.keys()):
format_string += '\t{:10s} {}\n'.format(key, self.pc2_args[key])
format_string += '\ndata_process_args: \n'
format_string += '\tDEPTH_THRESHOLD: {}\n'.format(self.DEPTH_THRESHOLD)
format_string += '\tNO_CORR: {}\n'.format(self.no_corr)
format_string += '\tallow_less_points: {}\n'.format(self.allow_less_points)
format_string += '\tnum_points: {}\n'.format(self.num_points)
format_string += ')'
return format_string
| 29,266 | 43.010526 | 127 | py |
arx | arx-master/arx/cv.py |
import chex
import jax.numpy as jnp
class CVScheme:
"""Generic CV scheme class
Methods:
name: name of the scheme suitable for plots and output
n_folds: number of folds, always numbered from 0
test_mask: boolean mask for test data for fold i
train_mask: boolean mask for train data for fold i
S_test: selection matrix for testing data for fold i
S_train: selection matrix for training data for fold i
"""
def __init__(self, T: int) -> None:
super().__init__()
self.T = T
def name(self) -> str:
raise NotImplementedError()
def n_folds(self) -> int:
raise NotImplementedError()
def test_mask(self, i: int) -> chex.Array:
raise NotImplementedError()
def train_mask(self, i: int) -> chex.Array:
raise NotImplementedError()
def S_test(self, i: int) -> chex.Array:
"""Selection matrix for test data for this scheme
Args:
i: fold number, 0-based
"""
mask = self.test_mask(i)
chex.assert_shape(mask, (self.T,))
chex.assert_type(mask, jnp.bool_)
S = jnp.diag(1.0 * mask)
return S[mask, :]
def S_train(self, i: int) -> chex.Array:
"""Selection matrix for training data for this scheme
Args:
i: fold number, 0-based
"""
mask = self.train_mask(i)
chex.assert_shape(mask, (self.T,))
chex.assert_type(mask, jnp.bool_)
S = jnp.diag(1.0 * mask)
return S[mask, :]
class LOOCVScheme(CVScheme):
"""Leave-one-out CV scheme"""
def name(self) -> str:
return "LOO"
def n_folds(self) -> int:
return self.T
def train_mask(self, i: int) -> chex.Array:
return jnp.arange(self.T) != i # type: ignore
def test_mask(self, i: int) -> chex.Array:
return jnp.arange(self.T) == i # type: ignore
class KFoldCVScheme(CVScheme):
"""K-fold CV scheme"""
def __init__(self, T: int, k: int) -> None:
self.k = k
self.block_size = T // k
super().__init__(T)
def name(self) -> str:
return f"{self.k}-fold"
def n_folds(self) -> int:
return self.k
def train_mask(self, i: int) -> chex.Array:
return jnp.arange(self.T) // self.block_size != i
def test_mask(self, i: int) -> chex.Array:
return jnp.arange(self.T) // self.block_size == i
class PointwiseKFoldCVScheme(CVScheme):
"""Pointwise K-fold scheme.
This is an (inefficient) scheme for evaluating K-fold pointwise. It's like
LOO but it uses the training sets from K-fold.
Best use with lengths T that are multiples of the block size
"""
def __init__(self, T: int, k: int) -> None:
self.k = k
self.block_size = T // k
super().__init__(T)
def name(self) -> str:
return f"Pointwise {self.k}-fold"
def n_folds(self) -> int:
return self.T
def train_mask(self, t: int) -> chex.Array:
# The k-fold training set: missing the whole block
block = t // self.block_size
return jnp.arange(self.T) // self.block_size != block
def test_mask(self, t: int) -> chex.Array:
# The LOO testing set: just one variate
return jnp.arange(self.T) == t
class HVBlockCVScheme(CVScheme):
"""H-block and HV-block CV schemes"""
def __init__(self, T: int, h: int, v: int) -> None:
super().__init__(T)
self.h = h
self.v = v
@classmethod
def from_delta(cls, T: int, delta: float) -> "HVBlockCVScheme":
"""Create HV-block scheme from delta hyperparameter"""
h = jnp.floor(T**delta)
v = jnp.floor(min(0.1 * T, (T - T ^ delta - 2 * h - 1) / 2))
return cls(T, h, v)
def name(self) -> str:
return f"hv-block (h={self.h}, v={self.v})" if self.v > 0 else "h-block(h={self.h})"
def n_folds(self) -> int:
return self.T
def train_mask(self, i: int) -> chex.Array:
idxs = jnp.arange(self.T)
return jnp.logical_or(
idxs < i - self.v - self.h,
idxs > i + self.v + self.h)
def test_mask(self, i: int) -> chex.Array:
idxs = jnp.arange(self.T)
return jnp.logical_and(
idxs >= i - self.v,
idxs <= i + self.v)
class LFOCVScheme(CVScheme):
"""LFO CV scheme
Attrs:
T: number of time points
h: size of the halo
v: size of the validation block
w: size of the initial margin
"""
def __init__(self, T: int, h: int, v: int, w: int) -> None:
super().__init__(T)
self.h = h
self.v = v
self.w = w
def name(self) -> str:
return f"LFO (h={self.h}, v={self.v}, w={self.w})"
def n_folds(self) -> int:
return self.T - self.w
def train_mask(self, i: int) -> chex.Array:
idxs = jnp.arange(self.T)
return (idxs < i + self.w - self.v - self.h)
def test_mask(self, i: int) -> chex.Array:
idxs = jnp.arange(self.T)
return jnp.logical_and(
idxs >= i + self.w - self.v,
idxs <= i + self.w + self.v)
| 5,192 | 26.331579 | 92 | py |
arx | arx-master/arx/sarx_test.py | import unittest
import cv
import jax.numpy as jnp
from sarx import *
class TestSARX(unittest.TestCase):
def setUp(self) -> None:
self.T = 100
self.phi_star = jnp.array([0.4])
self.sigsq_star = 1.5
self.beta_star = jnp.array([1.0, 2.0, 0.5])
self.Z = make_Z(q=3, T=self.T, prng_key=jax.random.PRNGKey(0))
self.sarx = SARX(
self.T,
phi_star=self.phi_star,
sigsq_star=self.sigsq_star,
beta_star=self.beta_star,
Z=self.Z,
mu_beta0=jnp.zeros(3),
sigma_beta0=jnp.eye(3),
)
return super().setUp()
def testMisspecify(self):
m1 = self.sarx.misspecify(q=2)
self.assertEqual(m1.q, 2)
self.assertEqual(m1.Z.shape, (self.T, 2))
self.assertEqual(m1.mu_beta0.shape, (2,))
def testOptSigsqPhi(self):
# Won't be the same, but should be closeish
phi_hat, sigsq_hat = opt_sigsq_phi(m=self.sarx, dgp=self.sarx)
self.assertTrue(jnp.linalg.norm(phi_hat - self.sarx.phi_star) < 0.01)
self.assertTrue(jnp.abs(sigsq_hat - self.sarx.sigsq_star) < 0.01)
# Should be a little less close
m1 = self.sarx.misspecify(q=2)
phi_hat, sigsq_hat = opt_sigsq_phi(m=m1, dgp=self.sarx)
phi_abserr = jnp.linalg.norm(phi_hat - self.sarx.phi_star)
sigsq_abserr = jnp.abs(sigsq_hat - self.sarx.sigsq_star)
self.assertTrue(phi_abserr < 0.5)
self.assertTrue(sigsq_abserr < 1.0)
def testSimulate(self):
keys = jax.random.split(jax.random.PRNGKey(0), 5)
y = self.sarx.simulate(keys[0]) # debugger entry point
ys = jax.vmap(self.sarx.simulate)(keys)
self.assertEqual(ys.shape, (5, 100))
def testPolyArithmetic(self):
A1 = jax.random.normal(jax.random.PRNGKey(0), shape=(100, 100))
A2 = jax.random.normal(jax.random.PRNGKey(1), shape=(100, 100))
b1 = jax.random.normal(jax.random.PRNGKey(0), shape=(100,))
b2 = jax.random.normal(jax.random.PRNGKey(1), shape=(100,))
c1, c2 = jnp.array(3), jnp.array(4.0)
p1 = Poly(A1, b1, c1, self.sarx)
p2 = Poly(A2, b2, c2, self.sarx)
p3 = p1 + p2
self.assertTrue(jnp.allclose(p3.A, A1 + A2))
self.assertTrue(jnp.allclose(p3.b, b1 + b2))
self.assertTrue(jnp.allclose(p3.c, c1 + c2))
p4 = p1 - p2
self.assertTrue(jnp.allclose(p4.A, A1 - A2))
self.assertTrue(jnp.allclose(p4.b, b1 - b2))
self.assertTrue(jnp.allclose(p4.c, c1 - c2))
def testPolyMoments(self):
"""Check polynomial moments by simulation"""
p = self.sarx.eljpd(jnp.eye(self.sarx.T))
A, b, c = p.A, p.b, p.c
# theoretical values
m, sd = p.mean(), jnp.sqrt(p.var())
# check with simulation
keys = jax.random.split(jax.random.PRNGKey(0), 1000)
ys = jax.vmap(self.sarx.simulate)(keys)
vals = jax.vmap(lambda y: y.T @ A @ y + y.T @ b + c)(ys)
mhat, sdhat = jnp.mean(vals), jnp.std(vals)
# 5% rel error should be doable
self.assertTrue(jnp.abs((m - mhat) / m) < 0.01)
self.assertTrue(jnp.abs((sd - sdhat) / sd) < 0.05)
# check class's simulation function
mhat2, sdhat2 = p.sim_moments(1000, jax.random.PRNGKey(0))
# 5% rel error should be doable
self.assertTrue(jnp.abs((m - mhat2) / m) < 0.01)
self.assertTrue(jnp.abs((sd - sdhat2) / sd) < 0.05)
def testEljpd(self):
# full-data eljpd
elpd_p = self.sarx.eljpd(jnp.eye(self.sarx.T))
self.assertIsInstance(elpd_p, Poly)
elpd = elpd_p.mean()
# rough eljpd range to expect
self.assertTrue(-180.0 < elpd < -120.0)
# eljpd from simulation
reps = 1000
post_key, rep_key = jax.random.split(jax.random.PRNGKey(0))
ys = jax.vmap(self.sarx.simulate)(jax.random.split(post_key, reps))
ytildes = jax.vmap(self.sarx.simulate)(jax.random.split(rep_key, reps))
def rep_contrib(y, ytilde):
# posterior predictive distribution for a single replicate
post = self.sarx.full_data_post(y)
return post.log_pred_dens(ytilde)
elpd_contribs = jax.vmap(rep_contrib)(ys, ytildes)
elpd_hat = jnp.mean(elpd_contribs)
self.assertTrue(jnp.abs((elpd_hat - elpd) / elpd) < 0.001)
def testAnalyticalEljpd(self):
# test full-data eljpd conditional on a single y,
# this time for a misspecified model vs true dgp
m1 = self.sarx.misspecify(p=1, q=2)
elpd_p = m1.eljpd(jnp.eye(self.sarx.T))
self.assertIsInstance(elpd_p, Poly)
elpd = elpd_p.mean()
# rough eljpd range to expect
self.assertTrue(-180.0 < elpd < -120.0)
# eljpd from simulation
reps = 500
ys = jax.vmap(self.sarx.simulate)(jax.random.split(jax.random.PRNGKey(0), reps))
def rep_eljpd(y):
post = m1.full_data_post(y)
return post.eljpd(self.sarx)
elpd_contribs = jax.vmap(rep_eljpd)(ys)
elpd_hat = jnp.mean(elpd_contribs)
self.assertTrue(jnp.abs((elpd_hat - elpd) / elpd) < 0.001)
def testCV(self):
# smoke tests for CV functions
m = self.sarx.misspecify(q=2)
loo = cv.LOOCVScheme(self.sarx.T)
elpdhat_loo = m.eljpdhat_cv(loo)
self.assertIsInstance(elpdhat_loo, Poly)
mean = elpdhat_loo.mean()
std = elpdhat_loo.std()
# we'll check values by simulation in the next test
self.assertTrue(jnp.isfinite(mean), jnp.isfinite(std))
def testCVMomentsBySimulation(self):
# scheme = cv.LOOCVScheme(self.sarx.T)
scheme = cv.HVBlockCVScheme(self.sarx.T, 5, 10)
cvp = self.sarx.eljpdhat_cv(scheme)
cvp_mean = cvp.mean()
# check CV algo by simulation
reps = 500
N = scheme.n_folds()
# we just generate one set of ys, there's no independent test data
ykeys = jax.random.split(jax.random.PRNGKey(1), reps)
ys = jax.vmap(self.sarx.simulate)(ykeys)
contribs = []
for i in range(N):
# get training and test data
Strain, Stest = scheme.S_train(i), scheme.S_test(i)
v = jnp.sum(Stest)
# compute benchmark for each replicate
def rep_contrib(y, ytilde):
post = self.sarx.post(y, Strain)
return post.log_pred_dens_subset(ytilde, Stest) / v
elpd_contribs = jax.vmap(rep_contrib)(ys, ys)
elpd_contrib = jnp.mean(elpd_contribs)
contribs.append(elpd_contrib)
norm_contribs = jnp.array(contribs) * self.sarx.T / N
cv_mean_hat = jnp.sum(norm_contribs)
self.assertTrue(
jnp.abs((cvp_mean - cv_mean_hat) / cvp_mean) < 0.01,
f"{cvp_mean} != {cv_mean_hat}",
)
def testJointBenchmarkDummy(self):
# most basic test for benchmark imaginable: 1 fold, full data, full test
class DummyCVScheme(cv.CVScheme):
def __init__(self, T):
self.T = T
self.n = 1
self.indices = [(0, T)]
def n_folds(self) -> int:
return 1
def test_mask(self, i: int) -> chex.Array:
return jnp.ones(self.T, dtype=bool)
def train_mask(self, i: int) -> chex.Array:
return jnp.ones(self.T, dtype=bool)
dummy = DummyCVScheme(self.T)
bm = self.sarx.eljpd_cv_benchmark(dummy)
e = self.sarx.eljpd(jnp.eye(self.T))
self.assertAlmostEqual(bm.mean(), e.mean())
self.assertAlmostEqual(bm.std(), e.std())
def testBenchmarkCVMeasureBySimulation(self):
# scheme = cv.LOOCVScheme(self.sarx.T)
scheme = cv.HVBlockCVScheme(self.sarx.T, 5, 10)
elpd_bm = self.sarx.eljpd_cv_benchmark(scheme)
m_bm = elpd_bm.mean()
# check benchmark by simulation
reps = 400
N = scheme.n_folds()
ykeys = jax.random.split(jax.random.PRNGKey(1), reps)
ytildekeys = jax.random.split(jax.random.PRNGKey(2), reps)
ys = jax.vmap(self.sarx.simulate)(ykeys)
ytildes = jax.vmap(self.sarx.simulate)(ytildekeys)
contribs = []
for i in range(N):
# get training and test data
Strain, Stest = scheme.S_train(i), scheme.S_test(i)
v = jnp.sum(Stest)
# compute benchmark for each replicate
def rep_contrib(y, ytilde):
post = self.sarx.post(y, Strain)
return post.log_pred_dens_subset(ytilde, Stest) / v
elpd_contribs = jax.vmap(rep_contrib)(ys, ytildes)
elpd_contrib = jnp.mean(elpd_contribs)
contribs.append(elpd_contrib)
norm_contribs = jnp.array(contribs) * self.sarx.T / N
m_bm_hat = jnp.sum(norm_contribs)
self.assertTrue(
jnp.abs((m_bm - m_bm_hat) / m_bm) < 0.01, f"{m_bm} != {m_bm_hat}"
)
class TestSupportFunctions(unittest.TestCase):
def test_make_Z(self):
Z = make_Z(q=3, T=100, prng_key=jax.random.PRNGKey(0))
self.assertEqual(Z.shape, (100, 3))
Z = make_Z(q=1, T=100, prng_key=jax.random.PRNGKey(0))
self.assertEqual(Z.shape, (100, 1))
| 9,344 | 38.935897 | 88 | py |
arx | arx-master/arx/sarx_experiments.py | import jax.numpy as jnp
import pandas as pd
from arx.cv import *
from arx.experiments import *
from arx.sarx import *
def by_excluded_effect(filename, ex_no: int, variant: str, T: int = 100, seed: int = 0):
"""Simplified model selection experiment, varying beta2 (the excluded effect)
Args:
filename: File to save results to (csv)
ex_no: The experiment number
variant: Which variant (hard/easy)
T: The length of the data
seed: The random seed.
"""
key, sim_key = jax.random.split(jax.random.PRNGKey(seed))
ex = make_simplified_experiment(ex_no, variant)
results = []
for alpha in ALPHA_SM:
for beta2 in EFFECT_SIZES:
beta_star = jnp.array([1.0, 1.0, beta2])
ei = ex.make_simplified_instance(
alpha, prng_key=key, model_params=dict(beta_star=beta_star)
)
schemes = [
LOOCVScheme(ei.dgp.T),
HVBlockCVScheme(ei.dgp.T, h=3, v=3),
HVBlockCVScheme(ei.dgp.T, h=3, v=0),
KFoldCVScheme(ei.dgp.T, k=5),
KFoldCVScheme(ei.dgp.T, k=10),
LFOCVScheme(ei.dgp.T, h=0, v=0, w=10),
LFOCVScheme(ei.dgp.T, h=3, v=3, w=10),
]
for scheme in schemes:
bm = ei.mA.eljpd_cv_benchmark(scheme) - ei.mB.eljpd_cv_benchmark(scheme)
cv = ei.mA.eljpdhat_cv(scheme) - ei.mB.eljpdhat_cv(scheme)
cv_qs, cv_ns = cv.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
bm_qs, bm_ns = bm.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
err = cv - bm
res = dict(
scheme=scheme.name(),
beta2=beta2,
alpha=alpha,
bmark_mean=bm.mean(),
bmark_std=bm.std(),
cv_mean=cv.mean(),
cv_std=cv.std(),
err_mean=err.mean(),
err_std=err.std(),
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
cv_lower_q=cv_qs[0],
cv_upper_q=cv_qs[-1],
cv_negshare=cv_ns,
bm_lower_q=bm_qs[0],
bm_upper_q=bm_qs[-1],
bm_negshare=bm_ns,
)
for i, ph in enumerate(ei.dgp.phi_star):
res[f"phi_star_{i+1}"] = float(ph)
results.append(res)
# cumulatively checkpoint results
pd.DataFrame(results).to_csv(filename, index=False)
return pd.DataFrame(results)
def by_included_effect(filename, ex_no: int, variant: str, T: int = 100, seed: int = 0):
"""Simplified model selection experiment, varying beta1 (the included effect)
Args:
filename: File to save results to (csv)
ex_no: The experiment number
variant: Which variant (hard/easy)
T: The length of the data
seed: The random seed.
"""
key, sim_key = jax.random.split(jax.random.PRNGKey(seed))
ex = make_simplified_experiment(ex_no, variant)
results = []
for alpha in ALPHA_SM:
for beta0 in EFFECT_SIZES:
beta_star = jnp.array([beta0, 1.0, 1.0])
ei = ex.make_simplified_instance(
alpha, prng_key=key, model_params=dict(beta_star=beta_star)
)
schemes = [
LOOCVScheme(ei.dgp.T),
HVBlockCVScheme(ei.dgp.T, h=3, v=3),
HVBlockCVScheme(ei.dgp.T, h=3, v=0),
KFoldCVScheme(ei.dgp.T, k=5),
KFoldCVScheme(ei.dgp.T, k=10),
LFOCVScheme(ei.dgp.T, h=0, v=0, w=10),
LFOCVScheme(ei.dgp.T, h=3, v=3, w=10),
]
for scheme in schemes:
bm = ei.mA.eljpd_cv_benchmark(scheme) - ei.mB.eljpd_cv_benchmark(scheme)
cv = ei.mA.eljpdhat_cv(scheme) - ei.mB.eljpdhat_cv(scheme)
err = cv - bm
cv_qs, cv_ns = cv.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
bm_qs, bm_ns = bm.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
res = dict(
scheme=scheme.name(),
alpha=alpha,
beta0=beta0,
bmark_mean=bm.mean(),
bmark_std=bm.std(),
cv_mean=cv.mean(),
cv_std=cv.std(),
err_mean=err.mean(),
err_std=err.std(),
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
cv_lower_q=cv_qs[0],
cv_upper_q=cv_qs[-1],
cv_negshare=cv_ns,
bm_lower_q=bm_qs[0],
bm_upper_q=bm_qs[-1],
bm_negshare=bm_ns,
)
for i, ph in enumerate(ei.dgp.phi_star):
res[f"phi_star_{i+1}"] = float(ph)
results.append(res)
# cumulatively checkpoint results
pd.DataFrame(results).to_csv(filename, index=False)
return pd.DataFrame(results)
def by_data_length(filename, ex_no: int, variant: str, seed: int = 0):
"""Simplified model selection experiment, varying time
Args:
filename: File to save results to (csv)
ex_no: The experiment number
variant: Which variant (hard/easy)
seed: The random seed.
"""
key = jax.random.PRNGKey(seed)
ex = make_simplified_experiment(ex_no, variant)
# support restarts by loading existing results
existing_results = pd.read_csv(filename) if os.path.exists(filename) else None
results = existing_results.to_dict('records') if existing_results is not None else []
done = set(f"{r['scheme']}-{r['T']}-{r['alpha']:.2f}" for r in results)
zkey, ekey = jax.random.split(key)
# we do it this way to keep zkey the same for all experiments
model_key, sim_key = jax.random.split(ekey)
Zall = load_Z(q=ex.model_params['q'], T=max(DATA_LENGTHS))
for alpha in ALPHA_SM:
for t in DATA_LENGTHS:
this_Z = Zall[:t,:]
ei = ex.make_simplified_instance(
alpha, prng_key=model_key, model_params=dict(T=t, Z=this_Z)
)
schemes = [
LOOCVScheme(ei.dgp.T),
HVBlockCVScheme(ei.dgp.T, h=3, v=3),
# HVBlockCVScheme(ei.dgp.T, h=3, v=0),
# KFoldCVScheme(ei.dgp.T, k=5),
# KFoldCVScheme(ei.dgp.T, k=10),
# LFOCVScheme(ei.dgp.T, h=0, v=0, m=10),
# LFOCVScheme(ei.dgp.T, h=3, v=3, m=10),
]
for scheme in schemes:
if f"{scheme.name()}-{t}-{alpha:.2f}" in done:
print(f"Skipping {scheme.name()} for T={t}, alpha={alpha:.2f}")
continue
else:
print(f"{scheme.name()} for T={t}, alpha={alpha:.2f}")
bm = ei.mA.eljpd_cv_benchmark(scheme) - ei.mB.eljpd_cv_benchmark(scheme)
cv = ei.mA.eljpdhat_cv(scheme) - ei.mB.eljpdhat_cv(scheme)
err = cv - bm
cv_qs, cv_ns = cv.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
bm_qs, bm_ns = bm.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
res = dict(
T=t,
alpha=alpha,
scheme=scheme.name(),
bmark_mean=bm.mean(),
bmark_std=bm.std(),
cv_mean=cv.mean(),
cv_std=cv.std(),
err_mean=err.mean(),
err_std=err.std(),
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
cv_lower_q=cv_qs[0],
cv_upper_q=cv_qs[-1],
cv_negshare=cv_ns,
bm_lower_q=bm_qs[0],
bm_upper_q=bm_qs[-1],
bm_negshare=bm_ns,
)
for i, ph in enumerate(ei.dgp.phi_star):
res[f"phi_star_{i+1}"] = float(ph)
results.append(res)
done.add(f"{scheme.name()}-{t}-{alpha:.2f}")
# cumulatively checkpoint results
pd.DataFrame(results).to_csv(filename, index=False)
return pd.DataFrame(results)
def length_search(filename: str, ex_no: int, variant: str, threshold_alpha=0.01, seed: int = 0):
"""Simplified model selection experiment, varying time
Args:
filename: File to save results to (csv)
ex_no: The experiment number
variant: Which variant (hard/easy)
threshold_alpha: separatedness threshold (default 0.01)
seed: The random seed
"""
key = jax.random.PRNGKey(seed)
ex = make_simplified_experiment(ex_no, variant)
existing_results = pd.read_csv(filename) if os.path.exists(filename) else None
results = existing_results.to_dict('records') if existing_results is not None else []
is_done = set(f'{r["scheme"]}-{r["alpha"]}' for r in results)
zkey, ekey = jax.random.split(key)
# we do it this way to keep zkey the same for all experiments
model_key, sim_key = jax.random.split(ekey)
Zall = load_Z(q=ex.model_params['q'], T=5000)
scheme_factories = [ # ~~java vibes~~
('LOO', lambda t: LOOCVScheme(t)),
('hv-block', lambda t: HVBlockCVScheme(t, h=3, v=3)),
('h-block', lambda t: HVBlockCVScheme(t, h=3, v=0)),
('5-fold', lambda t: KFoldCVScheme(t, k=5)),
('10-fold', lambda t: KFoldCVScheme(t, k=10)),
('LFO-pw', lambda t: LFOCVScheme(t, h=0, v=0, w=10)),
('LFO-joint', lambda t: LFOCVScheme(t, h=3, v=3, w=10)),
]
lbounds = {scheme_name: 4 for scheme_name, _ in scheme_factories}
for alpha in [0.0, 0.25, 0.5, 0.75, 1.0]:
for scheme_name, scheme_factory in scheme_factories:
def is_well_separated_for_len(t):
this_Z = Zall[:t,:]
ei = ex.make_simplified_instance(
alpha, prng_key=model_key, model_params=dict(T=t, Z=this_Z)
)
scheme = scheme_factory(int(ei.dgp.T))
cv = ei.mA.eljpdhat_cv(scheme) - ei.mB.eljpdhat_cv(scheme)
_, cv_ns = cv.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
is_sep = bool(cv_ns < threshold_alpha) # manually unbox jax value
del cv_ns, cv, scheme, ei, this_Z # pray to memory leak deities
return is_sep
if f'{scheme_name}-{alpha}' in is_done:
print(f"*** skipping search for alpha={alpha}, scheme={scheme_name}")
existing_Tmin = existing_results[(existing_results.alpha==alpha) & (existing_results.scheme==scheme_name)]['Tmin'].min()
lbounds[scheme_name] = max(lbounds[scheme_name], existing_Tmin)
continue
# binaryish search - first cutpoint is off-center at 300 to speed up better cases
# and search window starts close to previous minimum
L, R, m = max(4, lbounds[scheme_name]-10), 2400, max(300, lbounds[scheme_name] + 100)
print(f"*** starting search for alpha={alpha}, scheme={scheme_name}, {L}-{R}")
while L < R:
print(f" L={L}, R={R}, m={m}")
if is_well_separated_for_len(m):
R = m
else:
L = m + 1
m = int((L + R) // 2)
print(f"alpha={alpha}, scheme={scheme_name}, Tmin = {m}")
lbounds[scheme_name] = m
results.append(dict(
alpha=float(alpha),
scheme=scheme_name,
Tmin=m,
threshold_alpha=threshold_alpha,
ex_no=ex_no,
variant=variant,
seed=seed,
))
is_done.add(f'{scheme_name}-{alpha}') # we don't actually read this back in
pd.DataFrame(results).to_csv(filename, index=False)
del is_well_separated_for_len
def pointwise_comparison(filename: str, ex_no: int, variant: str, t=100, seed: int = 0):
"""Compare joint and pointwise performance of various schemes
Args:
filename: File to save results to (csv)
ex_no: The experiment number
t: Data length
variant: Which variant (hard/easy)
seed: The random seed
"""
key, sim_key = jax.random.split(jax.random.PRNGKey(seed))
ex = make_simplified_experiment(ex_no, variant)
results = []
for alpha in [0.0, 0.25, 0.5, 0.75, 1.0]:
ei = ex.make_simplified_instance(
alpha, prng_key=key, model_params=dict(T=t)
)
schemes = [
HVBlockCVScheme(ei.dgp.T, h=3, v=3),
KFoldCVScheme(ei.dgp.T, k=5),
KFoldCVScheme(ei.dgp.T, k=10),
LFOCVScheme(ei.dgp.T, h=3, v=3, w=10),
]
for scheme in schemes:
joint = ei.mA.eljpdhat_cv(scheme) - ei.mB.eljpdhat_cv(scheme)
pw = ei.mA.eljpdhat_cv(scheme, pointwise=True) - ei.mB.eljpdhat_cv(scheme, pointwise=True)
j_qs, j_ns = joint.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
pw_qs, pw_ns = pw.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
res = dict(
scheme=scheme.name(),
alpha=alpha,
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
j_lower_q=j_qs[0],
j_upper_q=j_qs[-1],
j_negshare=j_ns,
pw_lower_q=pw_qs[0],
pw_upper_q=pw_qs[-1],
pw_negshare=pw_ns,
)
results.append(res)
pd.DataFrame(results).to_csv(filename, index=False)
def by_halo(filename, ex_no: int, variant: str, use_lfo: bool = False, T: int = 100, seed: int = 0):
"""Simplified model selection experiment, varying h (halo)
Args:
filename: File to save results to (csv)
ex_no: The experiment number
variant: Which variant (hard/easy)
use_lfo: Use LFO instead of hv-block
T: The length of the data
seed: The random seed.
"""
key, sim_key = jax.random.split(jax.random.PRNGKey(seed))
ex = make_simplified_experiment(ex_no, variant)
results = []
for alpha in ALPHA_SM:
for v in [0, 3]:
for h in HALOS:
ei = ex.make_simplified_instance(
alpha, prng_key=key, model_params=dict())
if use_lfo:
scheme = LFOCVScheme(ei.dgp.T, h=h, v=v, w=10)
else:
scheme = HVBlockCVScheme(ei.dgp.T, h=h, v=v)
bm = ei.mA.eljpd_cv_benchmark(scheme) - ei.mB.eljpd_cv_benchmark(scheme)
cv = ei.mA.eljpdhat_cv(scheme) - ei.mB.eljpdhat_cv(scheme)
cv_qs, cv_ns = cv.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
bm_qs, bm_ns = bm.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
err = cv - bm
res = dict(
h=h,
v=v,
alpha=alpha,
scheme=scheme.name(),
bmark_mean=bm.mean(),
bmark_std=bm.std(),
cv_mean=cv.mean(),
cv_std=cv.std(),
err_mean=err.mean(),
err_std=err.std(),
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
cv_lower_q=cv_qs[0],
cv_upper_q=cv_qs[-1],
cv_negshare=cv_ns,
bm_lower_q=bm_qs[0],
bm_upper_q=bm_qs[-1],
bm_negshare=bm_ns,
)
for i, ph in enumerate(ei.dgp.phi_star):
res[f"phi_star_{i+1}"] = float(ph)
results.append(res)
# cumulatively checkpoint results
pd.DataFrame(results).to_csv(filename, index=False)
return pd.DataFrame(results)
def by_dimension(filename, ex_no: int, variant: str, use_lfo: bool = False, T: int = 100, seed: int = 0):
"""Simplified model selection experiment, varying h (halo)
Args:
filename: File to save results to (csv)
ex_no: The experiment number
variant: Which variant (hard/easy)
use_lfo: Use LFO instead of hv-block
T: The length of the data
seed: The random seed.
"""
key, sim_key = jax.random.split(jax.random.PRNGKey(seed))
ex = make_simplified_experiment(ex_no, variant)
results = []
for alpha in ALPHA_SM:
for h in [0, 3]:
for v in DIMENSIONS:
ei = ex.make_simplified_instance(
alpha, prng_key=key, model_params=dict())
if use_lfo:
scheme = LFOCVScheme(ei.dgp.T, h=h, v=v, w=10)
else:
scheme = HVBlockCVScheme(ei.dgp.T, h=h, v=v)
bm = ei.mA.eljpd_cv_benchmark(scheme) - ei.mB.eljpd_cv_benchmark(scheme)
cv = ei.mA.eljpdhat_cv(scheme) - ei.mB.eljpdhat_cv(scheme)
cv_qs, cv_ns = cv.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
bm_qs, bm_ns = bm.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
err = cv - bm
res = dict(
v=v,
h=h,
alpha=alpha,
scheme=scheme.name(),
bmark_mean=bm.mean(),
bmark_std=bm.std(),
cv_mean=cv.mean(),
cv_std=cv.std(),
err_mean=err.mean(),
err_std=err.std(),
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
cv_lower_q=cv_qs[0],
cv_upper_q=cv_qs[-1],
cv_negshare=cv_ns,
bm_lower_q=bm_qs[0],
bm_upper_q=bm_qs[-1],
bm_negshare=bm_ns,
)
for i, ph in enumerate(ei.dgp.phi_star):
res[f"phi_star_{i+1}"] = float(ph)
results.append(res)
# cumulatively checkpoint results
pd.DataFrame(results).to_csv(filename, index=False)
return pd.DataFrame(results)
def by_alpha(filename, ex_no: int, variant: str, T: int = 100, seed: int = 0):
"""Simplified model selection experiment, varying alpha
Args:
filename: File to save results to (csv)
ex_no: The experiment number
variant: Which variant (hard/easy)
T: The length of the data
seed: The random seed.
"""
key, sim_key = jax.random.split(jax.random.PRNGKey(seed))
ex = make_simplified_experiment(ex_no, variant)
results = []
def save():
pd.DataFrame(results).to_csv(filename, index=False)
cv_schemes = [
LOOCVScheme(T),
HVBlockCVScheme(T, h=3, v=3),
HVBlockCVScheme(T, h=3, v=0),
KFoldCVScheme(T, k=5),
KFoldCVScheme(T, k=10),
LFOCVScheme(T, h=0, v=0, w=10),
LFOCVScheme(T, h=3, v=3, w=10),
]
for alpha in ALPHA_RANGE:
ei = ex.make_simplified_instance(
alpha, prng_key=key, model_params=dict())
# joint difference
I_T = jnp.eye(ei.dgp.T)
jd : Poly = ei.mA.eljpd(I_T) - ei.mB.eljpd(I_T)
qs, negshare = jd.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
res = dict(
method='theoretical',
scheme='eljpd',
alpha=alpha,
bmark_mean=jd.mean(),
bmark_std=jd.std(),
cv_mean=None,
cv_std=None,
err_mean=None,
err_std=None,
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
lower_q=qs[0],
upper_q=qs[-1],
negshare=negshare,
)
results.append(res)
# hack to construct elppd
loo = LOOCVScheme(T)
pwd = ei.mA.eljpd_cv_benchmark(loo) - ei.mB.eljpd_cv_benchmark(loo)
qs, negshare = pwd.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
res = dict(
method='theoretical',
scheme='elppd',
alpha=alpha,
bmark_mean=pwd.mean(),
bmark_std=pwd.std(),
cv_mean=None,
cv_std=None,
err_mean=None,
err_std=None,
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
lower_q=qs[0],
upper_q=qs[-1],
negshare=negshare,
)
results.append(res)
for sch in cv_schemes:
bm = ei.mA.eljpd_cv_benchmark(sch) - ei.mB.eljpd_cv_benchmark(sch)
cv = ei.mA.eljpdhat_cv(sch) - ei.mB.eljpdhat_cv(sch)
err = cv - bm
qs, negshare = cv.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
res = dict(
method='cv',
scheme=sch.name(),
alpha=alpha,
bmark_mean=bm.mean(),
bmark_std=bm.std(),
cv_mean=cv.mean(),
cv_std=cv.std(),
err_mean=err.mean(),
err_std=err.std(),
sigsq_star=ei.dgp.sigsq_star,
sigsq_mA=ei.mA.sigsq_hat,
sigsq_mB=ei.mB.sigsq_hat,
phi_mA=ei.mA.phi_hat,
phi_mB=ei.mB.phi_hat,
lower_q=qs[0],
upper_q=qs[-1],
negshare=negshare,
)
for i, ph in enumerate(ei.dgp.phi_star):
res[f"phi_star_{i+1}"] = float(ph)
results.append(res)
save()
return pd.DataFrame(results)
def loss(filename, ex_no: int, variant: str, T: int = 100, nreps=5_000, seed: int = 0):
"""Simplified model selection experiment computing losses by alpha
Args:
filename: output file
ex_no: experiment number
variant: variant (hard/easy)
T: length of data
nreps: number of monte carlo simulations to run
seed: random seed
"""
ex = make_simplified_experiment(ex_no, variant)
model_key, y_key = jax.random.split(jax.random.PRNGKey(seed))
y_keys = jax.random.split(y_key, nreps)
schemes = [
LOOCVScheme(T),
HVBlockCVScheme(T, h=3, v=0),
HVBlockCVScheme(T, h=3, v=3),
KFoldCVScheme(T, k=5),
KFoldCVScheme(T, k=10),
LFOCVScheme(T, h=0, v=0, w=10),
LFOCVScheme(T, h=3, v=3, w=10),
]
results = []
for alpha in ALPHA_RANGE:
for scheme in schemes:
ei = ex.make_simplified_instance(alpha, prng_key=model_key, model_params=dict())
ys = jax.vmap(ei.dgp.simulate)(y_keys)
# utility of a particular posterior with respect to the true dgp
util_m1 = jax.vmap(lambda y: ei.mA.full_data_post(y).eljpd(ei.dgp))(ys)
util_m2 = jax.vmap(lambda y: ei.mB.full_data_post(y).eljpd(ei.dgp))(ys)
# CV-based model selection statistic
sel_stats = jax.vmap(lambda y: ei.mA.cv(y, scheme) - ei.mB.cv(y, scheme))(ys)
# note m1 clearly better
# compute overall losses
zeroone = jnp.mean(sel_stats < 0.0)
# "lost log utility" from choosing m2
logloss = jnp.mean((sel_stats < 0.0) * (util_m1 - util_m2))
res = {
"alpha": alpha,
"scheme": scheme.name(),
"zeroone": float(zeroone),
"logloss": float(logloss),
}
results.append(res)
df = pd.DataFrame(results)
df.to_csv(filename)
def supplementary(filename, t: int = 100, seed: int = 0):
"""Run supplementary experiments"""
model_key, sim_key = jax.random.split(jax.random.PRNGKey(seed))
results = []
for i in range(1,6+1):
for variant in ['hard', 'easy']:
print(f"Experiment {i} '{variant}' variant")
ex = make_simplified_experiment(i, variant)
for alpha in ALPHA_SM:
ei = ex.make_simplified_instance(alpha, prng_key=model_key, model_params=dict())
cv_schemes = [
LOOCVScheme(t),
HVBlockCVScheme(t, h=3, v=3),
]
for sch in cv_schemes:
cv = ei.mA.eljpdhat_cv(sch) - ei.mB.eljpdhat_cv(sch)
qs, negshare = cv.sim_quantiles_neg_share(qs=QUANTILES, n=10_000, rng_key=sim_key)
res = dict(
ex_no=i,
variant=variant,
alpha=alpha,
scheme=sch.name(),
cv_mean=cv.mean(),
cv_std=cv.std(),
lower_q=qs[0],
upper_q=qs[-1],
negshare=negshare,
)
results.append(res)
pd.DataFrame(results).to_csv(filename)
| 26,848 | 41.149137 | 136 | py |
arx | arx-master/arx/sarx.py | from typing import Tuple
import chex
import jax
from jax import numpy as jnp
from jax.numpy.linalg import inv, slogdet, solve
from jax.scipy.linalg import solve_triangular
from jax.scipy.stats import multivariate_normal
from scipy import optimize
from arx.arx import make_L
from arx.cv import CVScheme
class Poly:
"""Second-degree polynomial in y.
Contains the coefficients A, b, and c, as well as methods for computing
their moments. See Lemma 3 in the paper.
"""
def __init__(self, A, b, c, dgp: "SARX") -> None:
self.A = A # TxT
self.b = b # Tx1
self.c = c # scalar
self.T = A.shape[0]
self.Vstar = dgp.L_inv @ dgp.L_inv.T
self.sigsq = dgp.sigsq_star
self.mstar = dgp.L_star_invZ @ dgp.beta_star
self.dgp = dgp
def mean(self) -> float:
Atilde = 0.5 * (self.A + self.A.T)
return (
self.sigsq * jnp.trace(Atilde @ self.Vstar)
+ self.c
+ self.b.T @ self.mstar
+ self.mstar.T @ Atilde @ self.mstar
)
def var(self) -> float:
Atilde = 0.5 * (self.A + self.A.T)
return (
2.0 * self.sigsq**2 * jnp.trace(Atilde @ self.Vstar @ Atilde @ self.Vstar)
+ self.sigsq * self.b.T @ self.Vstar @ self.b
+ 4.0 * self.sigsq * self.b.T @ self.Vstar @ Atilde @ self.mstar
+ 4.0
* self.sigsq
* self.mstar.T
@ Atilde
@ self.Vstar
@ Atilde
@ self.mstar
)
def std(self) -> float:
return self.var() ** 0.5
def simulate(self, rng_key) -> float:
y = self.dgp.simulate(rng_key)
return y.T @ self.A @ y + self.b.T @ y + self.c
def sim_moments(self, n, rng_key) -> Tuple[float, float]:
"""Simulate n draws of the polynomial and compute its mean and sd."""
rng_keys = jax.random.split(rng_key, n)
zs = jax.vmap(self.simulate)(rng_keys)
return float(jnp.mean(zs)), float(jnp.std(zs))
def sim_quantiles_neg_share(self, qs, n, rng_key) -> Tuple[chex.Array, float]:
"""Simulate quantiles and negative share drawn from this quadratic expression
This is useful in experiments.
"""
zs = jax.vmap(self.simulate)(jax.random.split(rng_key, n))
quantiles = jnp.quantile(a=zs, q=qs)
neg_share = jnp.mean(zs < 0)
return quantiles, neg_share
def __str__(self) -> str:
return f"T = {self.T} mean = {self.mean() :.2f} sd = {self.var() ** 0.5 :.2f}"
def __repr__(self) -> str:
return str(self)
def __sub__(self, x: "Poly") -> "Poly":
"""Subtract two polynomials."""
return Poly(self.A - x.A, self.b - x.b, self.c - x.c, self.dgp)
def __add__(self, x: "Poly") -> "Poly":
"""Add two polynomials."""
return Poly(self.A + x.A, self.b + x.b, self.c + x.c, self.dgp)
class SARX:
"""Simplified ARX model class."""
def __init__(
self,
T,
phi_star,
sigsq_star,
beta_star,
Z,
mu_beta0,
sigma_beta0=None,
dgp=None,
):
self.T = T
self.phi_star = phi_star
self.sigsq_star = sigsq_star
self.beta_star = beta_star
self.q = Z.shape[1]
self.Z = Z
self.L_star = make_L(phi_star, T)
self.L_star_invZ = solve_triangular(self.L_star, self.Z, lower=True)
self.L_inv = solve_triangular(self.L_star, jnp.eye(self.T), lower=True)
self.mu_beta0 = mu_beta0
self.sigma_beta0 = sigma_beta0
if self.sigma_beta0 is None:
self.sigma_beta0 = jnp.eye(self.q)
self.sigma_beta0_inv = jnp.linalg.inv(self.sigma_beta0)
self.dgp = dgp or self
self._opt_sigsq_phi = False
def misspecify(
self,
phi_star=None,
sigsq_star=None,
beta_star=None,
p=None,
q=None,
mu_beta0=None,
sigma_beta0=None,
):
phi_star = phi_star or self.phi_star
sigsq_star = sigsq_star or self.sigsq_star
beta_star = beta_star or self.beta_star
mu_beta0 = mu_beta0 or self.mu_beta0
sigma_beta0 = sigma_beta0 or self.sigma_beta0
Z = self.Z
if p is not None:
if p > len(phi_star):
phi_star = jnp.hstack([phi_star, jnp.zeros(p - len(phi_star))])
else:
phi_star = phi_star[:p]
if q:
mu_beta0 = mu_beta0[:q]
sigma_beta0 = sigma_beta0[:q, :q]
beta_star = beta_star[:q]
Z = Z[:, :q]
return SARX(
T=self.T,
phi_star=phi_star,
sigsq_star=sigsq_star,
beta_star=beta_star,
Z=Z,
mu_beta0=mu_beta0,
sigma_beta0=sigma_beta0,
dgp=self.dgp,
)
def full_data_post(self, y) -> "SARXPost":
return FullDataSARXPost(self, y)
def post(self, y, Strain) -> "SARXPost":
return PartialDataSARXPost(self, y, Strain)
def simulate(self, prng_key) -> chex.Array:
eps = jax.random.normal(prng_key, (self.T,))
return (
self.L_star_invZ @ self.beta_star
+ jnp.sqrt(self.sigsq_star) * self.L_inv @ eps
)
def eljpd(self, Stest: chex.Array) -> Poly:
"""Compute polynomial associated with eljpd of model.
This version uses the full training data, which keeps calculations
a little simpler.
"""
phi_hat, sigsq_hat = self.memoize_opt_sigsq_phi()
L = make_L(phi_hat, self.T)
Wphi = jnp.linalg.inv(L.T @ L)
LinvZ = solve_triangular(L, self.Z, lower=True)
# simplified full-data version of sigma_beta
sigma_beta = jnp.linalg.inv(self.sigma_beta0_inv + self.Z.T @ self.Z)
Dk = LinvZ @ sigma_beta @ self.Z.T @ L
mstar = self.dgp.L_star_invZ @ self.dgp.beta_star
ek = LinvZ @ sigma_beta @ self.sigma_beta0_inv @ self.mu_beta0
Vk = Wphi + LinvZ @ sigma_beta @ LinvZ.T
v = jnp.sum(Stest)
prec = jnp.linalg.inv(Stest @ Vk @ Stest.T)
Ak = -0.5 * Dk.T @ Stest.T @ prec @ Stest @ Dk / sigsq_hat
bk = -Dk.T @ Stest.T @ prec @ Stest @ (ek - mstar) / sigsq_hat
ck = -0.5 * (
v * jnp.log(2 * jnp.pi * sigsq_hat)
- jnp.linalg.slogdet(prec)[1]
+ self.dgp.sigsq_star / sigsq_hat * jnp.trace(prec @ Stest @ Wphi @ Stest.T)
+ (ek - mstar).T @ Stest.T @ prec @ Stest @ (ek - mstar) / sigsq_hat
)
return Poly(Ak, bk, ck, self.dgp)
def memoized_opt_sigsq_phi(self):
"""Memoize copy of sigsq and phi so we only have to do this once per sarx object."""
if not self.sigsq_phi_memoized:
self.phi_hat, self.sigsq_hat = opt_sigsq_phi(self, self.dgp)
self.sigsq_phi_memoized = True
return self.phi_hat, self.sigsq_hat
def eljpdhat_cv(self, cv_scheme: CVScheme, pointwise: bool = False) -> Poly:
"""Compute (parameters of) distribution of the CV estimate of eljpdhat
Args:
cv_scheme: Cross-validation scheme to use
pointwise: If True, return pointwise elppdhat instead of eljpdhat
Returns Poly object representing the distribution of the CV estimate of eljpdhat
"""
phi_hat, sigsq_hat = self.memoize_opt_sigsq_phi()
L = make_L(phi_hat, self.T)
Wphi = inv(L.T @ L)
LinvZ = solve_triangular(L, self.Z, lower=True)
I = jnp.eye(self.T)
N = cv_scheme.n_folds()
Ak, bk, ck = 0.0, 0.0, 0.0
for i in range(N):
Strain, Stest = cv_scheme.S_train(i), cv_scheme.S_test(i)
sigma_beta = inv(
self.sigma_beta0_inv
+ LinvZ.T @ Strain.T @ solve(Strain @ Wphi @ Strain.T, Strain @ LinvZ)
)
Dki = (
LinvZ
@ sigma_beta
@ LinvZ.T
@ Strain.T
@ solve(Strain @ Wphi @ Strain.T, Strain)
)
eki = LinvZ @ sigma_beta @ self.sigma_beta0_inv @ self.mu_beta0
Vk = Wphi + LinvZ @ sigma_beta @ LinvZ.T # TxT
if pointwise:
# "diagonalize" Vk
Vk = Vk * jnp.eye(self.T)
v = jnp.sum(Stest)
prec = inv(Stest @ Vk @ Stest.T)
Ak += (
-0.5
* self.T
/ (N * v * sigsq_hat)
* (I - Dki).T
@ Stest.T
@ prec
@ Stest
@ (I - Dki)
)
bk += (
self.T
/ (N * v * sigsq_hat)
* (I - Dki).T
@ Stest.T
@ prec
@ Stest
@ eki
)
ck += -0.5 * (
self.T / N * jnp.log(2 * jnp.pi * sigsq_hat)
+ self.T / (N * v) * slogdet(Stest @ Vk @ Stest.T)[1]
+ self.T / (N * v * sigsq_hat) * eki.T @ Stest.T @ prec @ Stest @ eki
)
return Poly(Ak, bk, ck, self.dgp)
def eljpd_cv_benchmark(self, cv_scheme: CVScheme) -> Poly:
"""Compute eljpd using same structure as CV scheme.
Excludes the same training observations that the CV scheme does
but uses fresh data rather than reusing y.
"""
phi_hat, sigsq_hat = self.memoize_opt_sigsq_phi()
L = make_L(phi_hat, self.T)
Wphi = inv(L.T @ L)
LinvZ = solve_triangular(L, self.Z, lower=True)
mstar = self.dgp.L_star_invZ @ self.dgp.beta_star
N = cv_scheme.n_folds()
# we can't use vmap because some of the Stests have different shapes
# means, stds = [], []
Ak, bk, ck = 0.0, 0.0, 0.0
for i in range(N):
Strain, Stest = cv_scheme.S_train(i), cv_scheme.S_test(i)
v = jnp.sum(Stest)
# simplified full-data version of sigma_beta
cov = Strain.T @ inv(Strain @ Wphi @ Strain.T) @ Strain
sigma_beta = inv(
self.sigma_beta0_inv
+ LinvZ.T @ Strain.T @ solve(Strain @ Wphi @ Strain.T, Strain @ LinvZ)
)
SteDk = Stest @ LinvZ @ sigma_beta @ LinvZ.T @ cov
Steekm = Stest @ (
LinvZ @ sigma_beta @ self.sigma_beta0_inv @ self.mu_beta0 - mstar
)
Vk = Wphi + LinvZ @ sigma_beta @ LinvZ.T
prec = inv(Stest @ Vk @ Stest.T)
Aki = -0.5 * SteDk.T @ prec @ SteDk / sigsq_hat
bki = -SteDk.T @ prec @ Steekm / sigsq_hat
cki = -0.5 * (
v * jnp.log(2 * jnp.pi * sigsq_hat)
+ slogdet(Stest @ Vk @ Stest.T)[1]
+ self.dgp.sigsq_star
* jnp.trace(prec @ Stest @ Wphi @ Stest.T)
/ sigsq_hat
+ Steekm.T @ prec @ Steekm / sigsq_hat
)
Ak += Aki / v
bk += bki / v
ck += cki / v
# normalize to "sum length"
Ak *= 1.0 * self.T / N
bk *= 1.0 * self.T / N
ck *= 1.0 * self.T / N
return Poly(Ak, bk, ck, self.dgp) # , means, stds
def eljpd_cv_error(self, cv_scheme: CVScheme) -> Poly:
"""Compute error associated with data reuse in CV scheme"""
return self.eljpdhat_cv(cv_scheme) - self.eljpd_cv_benchmark(cv_scheme)
def memoize_opt_sigsq_phi(self) -> Tuple[chex.Array, chex.Array]:
if not self._opt_sigsq_phi:
self._opt_sigsq_phi = True
self.phi_hat, self.sigsq_hat = opt_sigsq_phi(self, self.dgp)
return self.phi_hat, self.sigsq_hat
def cv(self, y: chex.Array, cv_scheme: CVScheme) -> float:
"""Estimate eljpd using CV.
This is plan cross-validation, conditioned on a single y draw.
Args:
y: T-vector of observations
cv_scheme: CV scheme
"""
N = cv_scheme.n_folds()
contribs = []
for i in range(N):
# get training and test data
Strain, Stest = cv_scheme.S_train(i), cv_scheme.S_test(i)
v = jnp.sum(Stest)
post = self.post(y, Strain)
dens = post.log_pred_dens_subset(y, Stest) / v
contribs.append(dens)
return jnp.sum(jnp.array(contribs) * self.T / N)
def opt_sigsq_phi(m: SARX, dgp: SARX) -> Tuple[chex.Array, chex.Array]:
"""Find oracle plug-in sigsq and phi for a given model, with respect to its DGP.
This minimizes the full process KL divergence between model predictive and dgp.
"""
m_star = dgp.L_star_invZ @ dgp.beta_star
I_T = jnp.eye(dgp.T)
# The following are *dgp* parameters. These stay constant
V_star = jnp.linalg.inv(dgp.L_star.T @ dgp.L_star)
log_det_V_star = jnp.linalg.slogdet(V_star)[1]
def EKLD(x):
# The following are the *model* parameters we're optimizing over
phi, sigsq = x[:-1], x[-1]
L = make_L(phi, m.T)
LinvZ = solve_triangular(L, m.Z, lower=True)
Wphi = jnp.linalg.inv(L.T @ L)
sigma_beta = jnp.linalg.inv(
m.Z.T @ m.Z + m.sigma_beta0_inv
) # simplified version
Dk = LinvZ @ sigma_beta @ m.Z.T @ L
ek = LinvZ @ sigma_beta @ m.sigma_beta0_inv @ m.mu_beta0
Vk = Wphi + LinvZ @ sigma_beta @ LinvZ.T
mtilde = (Dk - I_T) @ m_star + ek
return 0.5 * (
m.T * jnp.log(sigsq)
- m.T * jnp.log(dgp.sigsq_star)
+ jnp.linalg.slogdet(Vk)[1]
- log_det_V_star
- m.T
+ dgp.sigsq_star
/ sigsq
* jnp.trace(jnp.linalg.solve(Vk, (V_star + Dk @ V_star @ Dk.T)))
+ mtilde @ jnp.linalg.solve(Vk, mtilde) / sigsq
)
x0 = jnp.concatenate([m.phi_star, jnp.array([m.sigsq_star])])
bounds = [(-1.0, 1.0)] * len(m.phi_star) + [(1e-6, None)]
f = jax.jit(EKLD)
res = optimize.minimize(f, x0=x0, method="L-BFGS-B", bounds=bounds)
phi_hat, sigsq_hat = res.x[:-1], res.x[-1]
# differences should never be too wild
# thresholds are a bit arbitrary, intended to stop unintended bad cases
assert jnp.linalg.norm(phi_hat, ord=1) < 1.1
assert jnp.linalg.norm(phi_hat - m.phi_star, ord=1) < 0.7
# assert jnp.abs(sigsq_hat - m.sigsq_star) < 10
return phi_hat, sigsq_hat
class SARXPost:
def __init__(self, m, y, mk, sigsq_hat, phi_hat, Vk, mu_beta, sigma_beta) -> None:
self.m = m
self.y = y
self.mk = mk
self.sigsq_hat = sigsq_hat
self.phi_hat = phi_hat
self.Vk = Vk
self.mu_beta = mu_beta
self.sigma_beta = sigma_beta
def log_pred_dens(self, ytilde):
"""Predictive density
Args:
ytilde: replicate data to evaluate predictive density at
"""
return multivariate_normal.logpdf(
ytilde, mean=self.mk, cov=self.sigsq_hat * self.Vk
)
def log_pred_dens_subset(self, ytilde, Stest):
"""Predictive density for subset of data
Args:
ytilde: full-length replicate data to evaluate predictive density at
Stest: selection matrix for subset of data
"""
sy, sm, sV = Stest @ ytilde, Stest @ self.mk, Stest @ self.Vk @ Stest.T
return multivariate_normal.logpdf(sy, mean=sm, cov=self.sigsq_hat * sV)
def eljpd(self, dgp: SARX) -> float:
"""Expected joint log predictive density
This is $\\int dgp(ytilde) * log p(ytilde | mk, sigsq_hat * Vk) dytilde.$
"""
mstar = dgp.L_star_invZ @ dgp.beta_star
V_star = inv(dgp.L_star.T @ dgp.L_star)
return -0.5 * (
jnp.log(2 * jnp.pi) * self.m.T
+ jnp.linalg.slogdet(self.sigsq_hat * self.Vk)[1]
+ dgp.sigsq_star / self.sigsq_hat * jnp.trace(solve(self.Vk, V_star))
+ (self.mk - mstar).T @ solve(self.Vk, self.mk - mstar) / self.sigsq_hat
)
def __str__(self):
return (
f"Posterior: T = {self.m.T}, sigsq_hat = {self.sigsq_hat:.3f}, "
f"phi_hat = {self.phi_hat}, mu_beta = {self.mu_beta}, sigma_beta = {self.sigma_beta}"
)
def __repr__(self) -> str:
return self.__str__()
class PartialDataSARXPost(SARXPost):
"""SARX posterior class with data subsetting"""
def __init__(self, m: SARX, y: chex.Array, Strain: chex.Array) -> None:
self.Strain = Strain
phi_hat, sigsq_hat = m.memoize_opt_sigsq_phi()
L = make_L(phi_hat, m.T)
LinvZ = solve_triangular(L, m.Z, lower=True)
Wphi = inv(L.T @ L)
# this is where we differ from the full-data case
prec = Strain @ Wphi @ Strain.T
sigma_beta = inv(
m.sigma_beta0_inv + LinvZ.T @ Strain.T @ solve(prec, Strain @ LinvZ)
)
mu_beta = sigma_beta @ (
LinvZ.T @ Strain.T @ solve(prec, Strain @ y)
+ m.sigma_beta0_inv @ m.mu_beta0
)
# whole data predictive mean & covariance, which will be subset later
mk = LinvZ @ mu_beta
Vk = Wphi + LinvZ @ sigma_beta @ LinvZ.T
super().__init__(m, y, mk, sigsq_hat, phi_hat, Vk, mu_beta, sigma_beta)
class FullDataSARXPost(SARXPost):
"""SARX posterior class without data subsetting"""
def __init__(self, m: SARX, y: chex.Array) -> None:
phi_hat, sigsq_hat = m.memoize_opt_sigsq_phi()
L = make_L(phi_hat, m.T)
LinvZ = solve_triangular(L, m.Z, lower=True)
sigma_beta = jnp.linalg.inv(m.sigma_beta0_inv + m.Z.T @ m.Z)
mu_beta = sigma_beta @ (m.Z.T @ L @ y + m.sigma_beta0_inv @ m.mu_beta0)
mk = LinvZ @ mu_beta
Wphi = jnp.linalg.inv(L.T @ L)
Vk = Wphi + LinvZ @ sigma_beta @ LinvZ.T
super().__init__(m, y, mk, sigsq_hat, phi_hat, Vk, mu_beta, sigma_beta)
| 17,979 | 35.470588 | 97 | py |
arx | arx-master/arx/experiments.py | from typing import Any, Callable, Dict
import jax.numpy as jnp
from chex import Array, PRNGKey
import numpy as np
import os
import jax
import chex
from arx import sarx, arx
EFFECT_SIZES = jnp.array([0.0, 0.5, 1.0, 2.0, 5.0, 10.0])
# \beta_*^{easy}
EASY_EFFECTS = jnp.array([1.0, 2.0, 1.0])
# \beta_*^{hard}
HARD_EFFECTS = jnp.array([1.0, 0.5, 1.0])
# \sigma^2_*
NOISE_VARIANCE = 1.0
DATA_LENGTHS = [
2, 5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100,
110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
250, 300, 400, 500, 750, 1000, 1500, 2000]
# alpha values for plotting (finer grid)
ALPHA_RANGE = jnp.linspace(0.0, 1.0, 21)
# alpha values for small multiple plots
ALPHA_SM = [0.0, 0.5, 0.75, 1.0]
HALOS = jnp.arange(31)
DIMENSIONS = jnp.arange(31)
QUANTILES = jnp.array([0.01, 0.99])
ZFILE = os.path.join(os.path.dirname(__file__), "Z.csv")
def make_Z(q: int, T: int, prng_key: chex.PRNGKey):
"""Construct exogenous covariate matrix"""
if q > 1:
Z = jnp.hstack(
[
jnp.ones((T, 1)),
jax.random.normal(key=prng_key, shape=(T, q - 1)),
]
)
else:
Z = jnp.ones((T, 1))
return Z
def save_Z(max_len, max_q, seed):
"""Construct and save Z for use across experiments
Args:
q: number of columns, including 1s in first column
max_len: maximum size T (ie number of rows)
max_q: maximum aerodynamic^H^H^H number of columns
seed: random number generator seed
"""
prng_key = jax.random.PRNGKey(seed)
Z = make_Z(max_q, max_len, prng_key)
np.savetxt(ZFILE, Z, delimiter=",")
def load_Z(q, T):
"""Load Z from a csv file
Args:
q: number of columns, including a vector of ones
T: number of rows
"""
Z = np.loadtxt(ZFILE, delimiter=",")
return Z[:T, :q]
class ExperimentInstance:
"""An instance of an experiment"""
def __init__(self, experiment, dgp, mA, mB):
self.experiment = experiment
self.dgp = dgp
self.mA = mA
self.mB = mB
def optimal_params_mA(self):
return self.mA.optimal_params(self.dgp)
def optimal_params_mB(self):
return self.mB.optimal_params(self.dgp)
class Experiment:
"""An experiment shown in the paper"""
def __init__(
self,
name: str,
model_params: Dict[str, Any],
mA_p_q,
mB_p_q,
make_phi: Callable[[float], Array],
) -> None:
self.name = name
self.model_params = model_params
self.make_phi = make_phi
self.mA_p_q = mA_p_q
self.mB_p_q = mB_p_q
def make_simplified_instance(
self, alpha, prng_key: PRNGKey, model_params: dict
) -> ExperimentInstance:
phi = self.make_phi(alpha)
this_params = self.model_params.copy()
this_params.update(model_params)
if "Z" not in this_params:
this_params["Z"] = load_Z(this_params["q"], this_params["T"])
del this_params["q"]
dgp = sarx.SARX(phi_star=phi, **this_params) # type: ignore
mA = dgp.misspecify(p=self.mA_p_q[0], q=self.mA_p_q[1])
mB = dgp.misspecify(p=self.mB_p_q[0], q=self.mB_p_q[1])
return ExperimentInstance(self, dgp, mA, mB)
def make_full_instance(
self, alpha, prng_key: PRNGKey, model_params: dict
) -> ExperimentInstance:
phi = self.make_phi(alpha)
this_params = self.model_params.copy()
this_params.update(model_params)
if "Z" not in this_params:
this_params["Z"] = load_Z(this_params["q"], this_params["T"])
del this_params["q"]
dgp = arx.ARX(phi_star=phi, **this_params) # type: ignore
mA = dgp.misspecify(p=self.mA_p_q[0], q=self.mA_p_q[1])
mB = dgp.misspecify(p=self.mB_p_q[0], q=self.mB_p_q[1])
return ExperimentInstance(self, dgp, mA, mB)
def make_full_experiment(number: int, variant: str) -> Experiment:
"""Make an experiment with a given name and variant"""
param = EXPERIMENTS[number]
beta_star = {"easy": EASY_EFFECTS, "hard": HARD_EFFECTS}[variant]
e = Experiment(
name=f"ex{number}-{variant}",
model_params=dict(
beta_star=beta_star,
sigsq_star=NOISE_VARIANCE,
q=3,
mu_beta0=beta_star,
T=param["T"],
),
make_phi=param["make_phi"],
mA_p_q=param["mA_p_q"],
mB_p_q=param["mB_p_q"],
)
return e
def make_simplified_experiment(number: int, variant: str) -> Experiment:
"""Make an experiment with a given name and variant"""
param = EXPERIMENTS[number]
beta_star = {"easy": EASY_EFFECTS, "hard": HARD_EFFECTS}[variant]
e = Experiment(
name=f"ex{number}-{variant}",
model_params=dict(
beta_star=beta_star,
sigsq_star=NOISE_VARIANCE,
q=3,
mu_beta0=beta_star,
T=param["T"],
),
make_phi=param["make_phi"],
mA_p_q=param["mA_p_q"],
mB_p_q=param["mB_p_q"],
)
return e
EXPERIMENTS = {
1: dict(
q=3,
make_phi=lambda alpha: alpha * jnp.array([0.75, 0.2]),
mA_p_q=(1, 2),
mB_p_q=(1, 1),
T=100,
),
2: dict(
q=3,
make_phi=lambda alpha: alpha * jnp.array([0.95]),
mA_p_q=(1, 3),
mB_p_q=(1, 2),
T=100,
),
3: dict(
q=3,
make_phi=lambda alpha: alpha * jnp.array([0.95]),
mA_p_q=(1, 2),
mB_p_q=(1, 1),
T=100,
),
4: dict(
q=3,
make_phi=lambda alpha: alpha * jnp.array([0.95]),
mA_p_q=(0, 2),
mB_p_q=(0, 1),
T=100,
),
5: dict(
q=3,
make_phi=lambda alpha: alpha * jnp.array([0.95]),
mA_p_q=(1, 2),
mB_p_q=(0, 2),
T=100,
),
6: dict(
q=3,
make_phi=lambda alpha: alpha * jnp.array([0.75, 0.20]),
mA_p_q=(1, 3),
mB_p_q=(1, 1),
T=100,
),
}
| 6,039 | 25.964286 | 73 | py |
arx | arx-master/arx/arx_test.py | from jax.config import config
config.update("jax_enable_x64", True)
import unittest
import cv
import jax
import jax.numpy as jnp
from chex import assert_equal, assert_shape, assert_tree_all_finite
from scipy.integrate import quad
import arx
class TestArx(unittest.TestCase):
def setUp(self) -> None:
key = jax.random.PRNGKey(123)
self.m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.9]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=key,
) # type: ignore
self.y = self.m0.simulate()
def test_misspecify(self):
assert_shape(self.y, (100,))
m1 = self.m0.misspecify(phi_star=jnp.array([0.8]))
assert_equal(m1.T, 100)
assert_equal(m1.sigsq_star, 1.0)
assert_equal(m1.phi_star, jnp.array([0.8]))
y = m1.simulate()
assert_shape(y, (100,))
m2 = m1.misspecify(phi_star=jnp.array([0.8]), q=2, sigsq_star=2.0)
assert_equal(m2.sigsq_star, 2.0)
assert_equal(m2.phi_star, jnp.array([0.8]))
assert_shape(m2.mu_beta0, (2,))
assert_shape(m2.sigma_beta0, (2, 2))
assert_shape(m2.sigma_beta0_inv, (2, 2))
y = m2.simulate()
assert_shape(y, (100,))
def test_p_y_phi(self):
for phi in [0.005, 0.5, 0.995]:
dens = self.m0.p_y_phi(phi=0.5, y=self.y)
assert not jnp.isnan(dens), f"nan result for phi={phi}"
assert dens >= 0, f"negative density for phi={phi}"
def test_post_and_pred(self):
postf, log_py = self.m0.post_dens(self.y)
assert not jnp.isnan(log_py)
assert not jnp.isnan(
postf(phi=jnp.array([0.5]), beta=jnp.array([1.0, 1, 1]), sigsq=1.0)
)
y_tilde = self.m0.simulate()
post = self.m0.post(self.y)
p_y_tilde = post.log_p_y_tilde(y_tilde)
assert not jnp.isnan(p_y_tilde)
def test_marg_post_phi(self):
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.9]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
m1 = m0.misspecify(p=1, q=2)
m1post = m1.post(y)
# if we get this far the integration worked, but is it valid density?
p = quad(m1post.marg_post_phi, -1, 1)[0]
assert jnp.abs(p - 1.0) < 1e-5
def test_ols(self):
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.9]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
beta_hat = m0.ols(y)
assert_shape(beta_hat, (4,))
assert_tree_all_finite(beta_hat)
def test_post(self):
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.9]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
post = m0.post(y)
y_tilde = m0.simulate()
assert not jnp.isnan(post.log_p_y_tilde(y_tilde))
class TestPred(unittest.TestCase):
# joint and pointwise should be the same when phi = 0 exactly, although
# the model doesn't know that's the dgp parameter, so we'll specify a
# strong prior concentrated around phi = 0 and hopefully the two results
# are relatively similar
def test_j_pw_indep(self):
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.0]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
a_sigsq0=100,
b_sigsq0=100,
) # type: ignore
y = m0.simulate()
post = m0.post(y)
y_tilde = m0.simulate()
p_j = post.log_p_pred_joint(y_tilde)
p_pw = post.log_p_pred_pointwise(y_tilde)
assert not jnp.isnan(p_j)
assert not jnp.isnan(p_pw)
assert jnp.abs((p_j - p_pw) / p_pw) < 0.01
# everything should still work when phi is close to 1
def test_j_pw_corr(self):
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.95]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
post = m0.post(y)
y_tilde = m0.simulate()
p_j = post.log_p_pred_joint(y_tilde)
p_pw = post.log_p_pred_pointwise(y_tilde)
assert not jnp.isnan(p_j)
assert not jnp.isnan(p_pw)
def test_fast_fd_predictive(self):
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.95]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
post = m0.post(
y
) # full data CV predictive, can compute p(y_tilde|y) the slow way
y_tilde = m0.simulate()
fdpost = arx.FullDataPosterior(m0, y)
log_guess = -140.0
fast_est = fdpost.log_p_y_tilde(y_tilde, log_guess)
I_T = jnp.eye(m0.T)
def joint_dens(phi):
return jnp.exp(fdpost.log_y_tilde_phi(y_tilde, phi, I_T) - log_guess)
integral = quad(joint_dens, -1, 1)[0]
slow_est = jnp.log(integral) + log_guess
assert jnp.abs((fast_est - slow_est) / slow_est) < 0.01
class TestPost(unittest.TestCase):
def test_log_p_y(self):
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.9]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
# check a few sensible values of phi
for phi in [-0.995, -0.5, 0, 0.005, 0.5, 0.995]:
log_p_y_phi = m0.log_p_y_phi(phi, y)
assert jnp.isfinite(log_p_y_phi)
assert log_p_y_phi <= 0
log_p_y = m0.log_p_y(y)
assert jnp.isfinite(log_p_y)
assert log_p_y <= 0
def test_fold_post(self):
# actually a full posterior test, using CV fold machinery
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.5]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
post = m0.post(y)
full_fold_post = arx.CVPosterior(
m=m0, y=y, S_test=jnp.eye(m0.T), S_train=jnp.eye(m0.T)
)
# check p(y, phi) a few sensible values of phi
for phi in [-0.995, -0.5, 0, 0.005, 0.5, 0.995]:
log_p_y_phi = full_fold_post.log_p_y_phi(phi)
assert jnp.isfinite(log_p_y_phi)
assert log_p_y_phi <= 0
assert jnp.isfinite(full_fold_post.log_p_y) and jnp.isfinite(post.log_p_y)
assert jnp.isclose(full_fold_post.log_p_y, post.log_p_y, atol=1e-5)
def test_loo_fold(self):
# one loo fold (not scrunch obvs)
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.5]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
loo = cv.LOOCVScheme(T=m0.T)
lf_post = arx.CVPosterior(
m=m0, y=y, S_test=loo.S_test(37), S_train=loo.S_train(37)
)
assert_equal(lf_post.v, 1)
assert_equal(lf_post.n, 99)
assert lf_post.log_p_y < 0
y_tilde = m0.simulate()
lpdens = lf_post.log_p_y_tilde(y_tilde)
lpdens_l = lf_post.log_p_y_tilde_laplace(y_tilde)
assert lpdens < 0 and lpdens_l < 0
# relative log difference <1%
assert jnp.abs((lpdens_l - lpdens) / lpdens) < 1e-2
def test_loo(self):
m0 = arx.ARX(
T=20,
phi_star=jnp.array([0.5]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
ffold = cv.KFoldCVScheme(T=m0.T, k=5)
eljpd = m0.cv(y=y, scheme=ffold)
assert -45 < eljpd < -25 # expect about -35
eljpd_l = m0.cv_laplace(y=y, scheme=ffold)
assert -45 < eljpd < -25 # expect about -35
# tolerate rel log difference < 1%
assert jnp.abs((eljpd_l - eljpd) / eljpd) < 1e-2
class TestMCMCPosterior(unittest.TestCase):
def test_mcmc_posterior(self):
m0 = arx.ARX(
T=100,
phi_star=jnp.array([0.5]),
sigsq_star=1.0,
beta_star=jnp.array([1.0, 0.5, 0.5]),
q=3,
prng_key=jax.random.PRNGKey(123),
) # type: ignore
y = m0.simulate()
key = jax.random.PRNGKey(123)
post = m0.fd_nuts_post(y, key, ndraws=200, nwarmup=200, nchains=1)
self.assertIsInstance(post, arx.MCMCPosterior)
if __name__ == "__main__":
unittest.main()
| 9,391 | 32.070423 | 82 | py |
arx | arx-master/arx/cv_test.py | import unittest
import cv
from chex import assert_equal, assert_shape, assert_tree_all_close
from jax import numpy as jnp
from tree import assert_same_structure
class TestCVSchemes(unittest.TestCase):
def test_loo(self):
loo = cv.LOOCVScheme(120)
assert_equal(loo.n_folds(), 120)
tstm = jnp.concatenate((jnp.array([False, True]), jnp.repeat(False, 118)))
assert_tree_all_close(loo.test_mask(1), tstm)
assert_tree_all_close(loo.train_mask(1), jnp.logical_not(tstm))
Stest1 = loo.S_test(1)
I = jnp.eye(120)
assert_same_structure(Stest1, I[tstm, :])
assert_tree_all_close(Stest1, I[tstm, :])
Strain1 = loo.S_train(1)
assert_same_structure(Strain1, I[jnp.logical_not(tstm), :])
assert_tree_all_close(Strain1, I[jnp.logical_not(tstm), :])
def test_kfold(self):
fivefold = cv.KFoldCVScheme(120, 5) # 24 cells each
assert_equal(fivefold.n_folds(), 5)
tstm = jnp.concatenate((jnp.repeat(False, 24), jnp.repeat(True, 96)))
assert_tree_all_close(fivefold.train_mask(0), tstm)
assert_tree_all_close(fivefold.test_mask(0), jnp.logical_not(tstm))
assert_shape(fivefold.S_test(0), (24, 120))
assert_shape(fivefold.S_train(0), (96, 120))
assert_shape(fivefold.S_test(1), (24, 120))
assert_shape(fivefold.S_train(1), (96, 120))
def test_hvblock(self):
hvblock = cv.HVBlockCVScheme(120, h=4, v=3)
assert_equal(hvblock.n_folds(), 120)
# test 20th fold (i=19)
tstm = jnp.concatenate(
[
jnp.repeat(False, 12 + 4),
jnp.repeat(True, 1 + 2 * 3),
jnp.repeat(False, 120 - 12 - 4 - 1 - 2 * 3),
]
)
tram = jnp.concatenate(
[
jnp.repeat(True, 12),
jnp.repeat(False, 2 * 4 + 2 * 3 + 1),
jnp.repeat(True, 120 - 12 - 2 * 4 - 2 * 3 - 1),
]
)
assert_tree_all_close(hvblock.test_mask(19), tstm)
assert_tree_all_close(hvblock.train_mask(19), tram)
| 2,115 | 37.472727 | 82 | py |
arx | arx-master/arx/cli.py | #!.venv/bin/python3
from jax.config import config
config.update("jax_enable_x64", True)
import glob
import os
import pandas as pd
import click
import arx.arx_experiments as arxex
import arx.sarx_experiments as sarxex
RESULTS = 'results'
def ensure_results_dir():
if not os.path.exists(RESULTS):
os.mkdir(RESULTS)
@click.group()
def run_experiment() -> None:
"""Run CV experiments
This script is the entry point for all experiments in the paper.
You'll probably need to run setup.sh (or similar) to make it work.
"""
@click.command(name='generate-z')
@click.option('--max_len', default=5000, type=int, help='Number of rows')
@click.option('--max_q', default=5, type=int, help='Number of columns')
@click.option('--seed', default=0, type=int, help='Random seed (default 0)')
def generate_z(max_len: int, max_q, seed: int) -> None:
"""Generate Z for use across experiments."""
sarxex.save_Z(max_len, max_q, seed)
@click.command(name="full-bayes")
@click.argument("experiment_no", type=int)
@click.argument("variant", type=click.Choice(['easy', 'hard']))
@click.argument("alternative", type=click.Choice(['LOO', '10-fold']))
@click.option("--t", type=int, default=100, help="Data length (default 100)")
@click.option("--n", type=int, default=10, help="Number of simulated posteriors (default 10)")
@click.option(
"--mc-reps",
type=int,
default=1000,
help="Number of MC reps for elpd (default 1000)",
)
@click.option("--seed", type=int, default=0, help="Random seed (default 0)")
def full(experiment_no: int, variant: str, alternative: str, t: int, n: int, mc_reps: int, seed: int) -> None:
"""Compute draws for full-Bayes experiment.
This experiment draws n samples from the true model, computes theoretical and CV
estimates for the joint and pointwise elpds. Estimates are saved as a file named
results/{experiment_name}-t={t}-n={n}-mc={mc_reps}-seed={seed}.csv.
For a given random seed and length, datasets are stable across invocations. This means
different experiments can be guaranteed to use the same simulated datasets.
To run this experiment, invoke this command ~50 times with different seeds in different
threads. Then combine results using the full-combine command.
"""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-alt={alternative}-T={t}-n={n}-mc={mc_reps}-seed={seed}.csv"
arxex.full_bayes(experiment_no, variant, filename, t, alternative, n, mc_reps, seed)
@click.command(name="full-kfold")
@click.argument("experiment_no", type=int)
@click.argument("variant", type=click.Choice(['easy', 'hard']))
@click.option("--k", type=int, default=10, help="Number of folds (default 10)")
@click.option("--t", type=int, default=100, help="Data length (default 100)")
@click.option("--n", type=int, default=10, help="Number of simulated posteriors (default 10)")
@click.option("--mcmc_draws", type=int, default=1000, help="MCMC draws per chain (default 1000)")
@click.option("--mcmc_chains", type=int, default=4, help="MCMC chains (default 4)")
@click.option("--mcmc_warmup", type=int, default=1000, help="MCMC warmup (default 1000)")
@click.option(
"--mc-reps",
type=int,
default=1000,
help="Number of MC reps for elpd (default 1000)",
)
@click.option("--seed", type=int, default=0, help="Random seed (default 0)")
def full_kfold(experiment_no: int, variant: str, k: int, t: int, n: int, mc_reps: int, mcmc_draws:int, mcmc_chains:int, mcmc_warmup:int, seed: int) -> None:
"""Compute draws for k-fold full-Bayes experiment.
This experiment draws n samples from the true model, computes theoretical and CV
estimates for the joint and pointwise elpds. Estimates are saved as a file named
results/{experiment_name}-t={t}-n={n}-{k}fold-mc={mc_reps}-seed={seed}.csv.
For a given random seed and length, datasets are stable across invocations. This means
different experiments can be guaranteed to use the same simulated datasets.
To run this experiment, invoke this command ~50 times with different seeds in different
threads. Then combine results using the full-combine command.
"""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-{k}fold-T={t}-n={n}-mc={mc_reps}-seed={seed}.csv"
arxex.full_kfold(
experiment_no=experiment_no,
variant=variant,
filename=filename,
T=t,
k=k,
n_posts=n,
mc_reps=mc_reps,
mcmc_draws=mcmc_draws,
mcmc_chains=mcmc_chains,
mcmc_warmup=mcmc_warmup,
seed=seed)
@click.command(name="full-combine")
@click.argument("experiment_no", type=int)
@click.argument("variant", type=click.Choice(['easy', 'hard']))
def combine_individual(experiment_no: int, variant: str) -> None:
"""Combine full-Bayes result files."""
outfile = f"{RESULTS}/{experiment_no}-{variant}-full-bayes.csv"
infiles = glob.glob(f"{RESULTS}/{experiment_no}-{variant}-*-seed=*.csv")
df = pd.concat([pd.read_csv(f) for f in infiles])
df.to_csv(outfile, index=False)
@click.command(name='by-length')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def by_length(experiment_no: int, variant: str, seed: int = 0) -> None:
"""Simplified model selection by data length."""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-by-length.csv"
sarxex.by_data_length(filename=filename, ex_no=experiment_no, variant=variant, seed=seed)
@click.command(name='length-search')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
@click.option('--threshold', type=float, default=0.01, help='Threshold for length search (default 0.01)')
def length_search(experiment_no: int, variant: str, threshold: float, seed: int) -> None:
"""Simplified model selection by data length."""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-length_search.csv"
sarxex.length_search(filename=filename, ex_no=experiment_no, variant=variant, threshold_alpha=threshold, seed=seed)
@click.command(name='by-halo')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option('--lfo', is_flag=True, default=False, help='Use LFO (default False)')
@click.option('--t', type=int, default=100, help='Data length (default 100)')
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def by_halo(experiment_no: int, variant: str, lfo: bool, t: int, seed: int) -> None:
"""Simplified model selection by halo."""
ensure_results_dir()
suffix = '-lfo' if lfo else ''
filename = f"{RESULTS}/{experiment_no}-{variant}-by-halo{suffix}.csv"
sarxex.by_halo(
filename=filename, ex_no=experiment_no, variant=variant, use_lfo=lfo, seed=seed, T=t)
@click.command(name='by-dimension')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option('--lfo', is_flag=True, default=False, help='Use LFO (default False)')
@click.option('--t', type=int, default=100, help='Data length (default 100)')
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def by_dimension(experiment_no: int, variant: str, lfo: bool, t: int, seed: int) -> None:
"""Simplified model selection by dimension and alpha."""
ensure_results_dir()
suffix = '-lfo' if lfo else ''
filename = f"{RESULTS}/{experiment_no}-{variant}-by-dimension{suffix}.csv"
sarxex.by_dimension(
filename=filename, ex_no=experiment_no, variant=variant, use_lfo=lfo, T=t, seed=seed)
@click.command(name='by-alpha')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option('--t', type=int, default=100, help='Data length (default 100)')
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def by_alpha(experiment_no: int, variant: str, t: int, seed: int) -> None:
"""Simplified model selection by alpha."""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-by-alpha.csv"
sarxex.by_alpha(filename=filename, ex_no=experiment_no, variant=variant, T=t, seed=seed)
@click.command(name='by-included-effect')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option('--nreps', type=int, default=5_000, help='Number of repetitions (default 5_000)')
@click.option('--t', type=int, default=100, help='Data length (default 100)')
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def by_included_effect(experiment_no: int, variant: str, t: int, nreps: int, seed: int) -> None:
"""Simplified model selection by included effect."""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-by-included-effect.csv"
sarxex.by_included_effect(filename=filename, ex_no=experiment_no, variant=variant, T=t, seed=seed)
@click.command(name='by-excluded-effect')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option('--nreps', type=int, default=5_000, help='Number of repetitions (default 5_000)')
@click.option('--t', type=int, default=100, help='Data length (default 100)')
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def by_excluded_effect(experiment_no: int, variant: str, t: int, nreps: int, seed: int) -> None:
"""Simplified model selection by excluded effect."""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-by-excluded-effect.csv"
sarxex.by_excluded_effect(filename=filename, ex_no=experiment_no, variant=variant, T=t, seed=seed)
@click.command(name='loss')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option('--nreps', type=int, default=5_000, help='Number of repetitions (default 5_000)')
@click.option('--t', type=int, default=100, help='Data length (default 100)')
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def loss(experiment_no: int, variant: str, t: int, nreps: int, seed: int) -> None:
"""Loss for simplified model selection by alpha."""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-loss.csv"
sarxex.loss(filename=filename, ex_no=experiment_no, variant=variant, T=t, nreps=nreps, seed=seed)
@click.command(name='pointwise-comparison')
@click.argument('experiment_no', type=int)
@click.argument('variant', type=click.Choice(['easy', 'hard']))
@click.option('--t', type=int, default=100, help='Data length (default 100)')
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def pointwise_comparison(experiment_no: int, variant: str, t: int, seed: int) -> None:
"""Joint/pointwise loss comparison by alpha."""
ensure_results_dir()
filename = f"{RESULTS}/{experiment_no}-{variant}-pointwise-joint.csv"
sarxex.pointwise_comparison(filename=filename, ex_no=experiment_no, variant=variant, t=t, seed=seed)
@click.command(name='supplementary')
@click.option('--t', type=int, default=100, help='Data length (default 100)')
@click.option("--seed", type=int, default=0, help='Random seed (default 0)')
def supplementary(t: int, seed: int) -> None:
"""Joint/pointwise loss comparison by alpha."""
ensure_results_dir()
filename = f"{RESULTS}/supplementary.csv"
sarxex.supplementary(filename=filename, t=t, seed=seed)
run_experiment.add_command(generate_z)
run_experiment.add_command(full)
run_experiment.add_command(full_kfold)
run_experiment.add_command(combine_individual)
run_experiment.add_command(by_length)
run_experiment.add_command(by_halo)
run_experiment.add_command(by_dimension)
run_experiment.add_command(by_alpha)
run_experiment.add_command(loss)
run_experiment.add_command(by_included_effect)
run_experiment.add_command(by_excluded_effect)
run_experiment.add_command(length_search)
run_experiment.add_command(pointwise_comparison)
run_experiment.add_command(supplementary)
if __name__ == "__main__":
run_experiment()
| 12,401 | 44.933333 | 156 | py |
arx | arx-master/arx/arx_experiments.py | from typing import List
import click
import jax
import pandas as pd
import arx.experiments as ex
from arx import cv
def full_bayes(
experiment_no: int,
experiment_variant: str,
filename: str,
T: int = 100,
alternative: str = '10-fold',
n_posts=10,
mc_reps=500,
n_warmup=400,
n_chains=4,
seed=0,
) -> None:
"""Compute and save individual draws for an experiment.
Args:
experiment_no: The number of the experiment to run.
experiment_variant: The variant of the experiment to run ("hard"/"easy").
filename: File to save results to
T: Data length (number of simulated time periods).
alternative: Alternative model (either "10-fold" or "LOO")
n_posts: The number of individual datasets to simulate (ie number of posteriors).
n_warmup: Number of warmup iterations for MCMC
n_chains: Number of MCMC chains to run
mc_reps: Monte Carlo repetitions for estimating true elpd.
seed: The random seed to use.
This experiment draws n samples from the true model, computes theoretical and CV
estimates for the joint and pointwise elpds. Estimates are saved in FILENAME.
For a given random seed and length, datasets are stable across invocations. This means
different experiments can be guaranteed to use the same simulated datasets.
"""
assert alternative in ["10-fold", "LOO"]
model_key, data_key, sim_key = jax.random.split(jax.random.PRNGKey(seed), 3)
experiment = ex.make_full_experiment(experiment_no, experiment_variant)
click.echo(
f"Running experiment {experiment_no} {experiment_variant} with T={T} and seed={seed}"
)
draw_keys = jax.random.split(data_key, n_posts)
sim_keys = jax.random.split(sim_key, n_posts)
results = []
def save():
df = pd.DataFrame(results)
df.to_csv(filename, index=False)
# Loop over y draws
for i, draw_key in enumerate(draw_keys):
for alpha in ex.ALPHA_SM:
click.echo(f"Starting draw i={i} ({i+1}/{n_posts}) for alpha={alpha}")
instance = experiment.make_full_instance(
alpha=alpha, prng_key=model_key, model_params=dict(T=T)
)
y = instance.dgp.simulate(draw_key)
mA_post = instance.mA.fd_nuts_post(
y,
prng_key=sim_keys[i],
ndraws=mc_reps,
nchains=n_chains,
nwarmup=n_warmup,
)
mB_post = instance.mB.fd_nuts_post(
y,
prng_key=sim_keys[i],
ndraws=mc_reps,
nchains=n_chains,
nwarmup=n_warmup,
)
mA = mA_post.estimate_elpd(instance.dgp, mA_post.arviz(), nreps=mc_reps)
mB = mB_post.estimate_elpd(instance.dgp, mB_post.arviz(), nreps=mc_reps)
tenfold = cv.KFoldCVScheme(T=instance.dgp.T, k=10)
mA_tenfold = instance.mA.cv(tenfold, y)[0]
mB_tenfold = instance.mB.cv(tenfold, y)[0]
if alternative == "LOO":
alt = cv.LOOCVScheme(T=instance.dgp.T)
elif alternative == "10-fold":
alt = cv.PointwiseKFoldCVScheme(T=instance.dgp.T, k=10)
else:
raise Exception(f"Unknown alternative scheme {alternative}")
mA_loo = instance.mA.cv(alt, y)[0]
mB_loo = instance.mB.cv(alt, y)[0]
res = dict(
index=i,
alpha=alpha,
mA_elppd=mA["mean_elppd"],
mB_elppd=mB["mean_elppd"],
mA_eljpd=mA["mean_eljpd"],
mB_eljpd=mB["mean_eljpd"],
mA_tenfold=mA_tenfold,
mB_tenfold=mB_tenfold,
mA_loo=mA_loo,
mB_loo=mB_loo,
T=T,
n=n_posts,
mc_reps=mc_reps,
seed=seed,
)
# add model selection statistics
for s in ["elppd", "eljpd", "tenfold", "loo"]:
res[f"sel_{s}"] = res[f"mA_{s}"] - res[f"mB_{s}"]
results.append(res)
save() # checkpoint
click.echo(f"Saved results to {filename}")
def full_kfold(
experiment_no: int,
variant: str,
filename: str,
T: int = 100,
k: int = 10,
n_posts=10,
mc_reps=500,
mcmc_draws:int=1000,
mcmc_chains:int=4,
mcmc_warmup:int=500,
seed=0,
) -> None:
"""Full Bayes k-fold experiment
Args:
experiment_no: The number of the experiment to run.
experiment_variant: The variant of the experiment to run ("hard"/"easy").
filename: File to save results to
T: Data length (number of simulated time periods).
k: Number of folds
n_posts: The number of individual datasets to simulate (ie number of posteriors).
n_warmup: Number of warmup iterations for MCMC
n_chains: Number of MCMC chains to run
mc_reps: Monte Carlo repetitions for estimating true elpd.
seed: The random seed to use.
This experiment draws n samples from the true model, computes theoretical and CV
estimates for the joint and pointwise elpds. Estimates are saved in FILENAME.
For a given random seed and length, datasets are stable across invocations. This means
different experiments can be guaranteed to use the same simulated datasets.
"""
model_key, data_key, sim_key, sampling_key = jax.random.split(jax.random.PRNGKey(seed), 4)
experiment = ex.make_full_experiment(experiment_no, variant)
click.echo(
f"Running experiment {experiment_no} {variant} with T={T} and seed={seed}"
)
draw_keys = jax.random.split(data_key, n_posts)
sim_keys = jax.random.split(sim_key, n_posts)
results = []
def save():
df = pd.DataFrame(results)
df.to_csv(filename, index=False)
# Loop over y draws
for i, draw_key in enumerate(draw_keys):
for alpha in ex.ALPHA_SM:
click.echo(f"Starting draw i={i} ({i+1}/{n_posts}) for alpha={alpha}")
instance = experiment.make_full_instance(
alpha=alpha, prng_key=model_key, model_params=dict(T=T)
)
y = instance.dgp.simulate(draw_key)
mA_post = instance.mA.fd_nuts_post(
y,
prng_key=sim_keys[i],
ndraws=mcmc_draws,
nchains=mcmc_chains,
nwarmup=mcmc_warmup,
)
mB_post = instance.mB.fd_nuts_post(
y,
prng_key=sim_keys[i],
ndraws=mcmc_draws,
nchains=mcmc_chains,
nwarmup=mcmc_warmup,
)
mA = mA_post.estimate_elpd(instance.dgp, mA_post.arviz(), nreps=mc_reps)
mB = mB_post.estimate_elpd(instance.dgp, mB_post.arviz(), nreps=mc_reps)
kfold = cv.KFoldCVScheme(T=instance.dgp.T, k=k)
mA_joint = instance.mA.cv(kfold, y)[0]
mB_joint = instance.mB.cv(kfold, y)[0]
alt = cv.PointwiseKFoldCVScheme(T=instance.dgp.T, k=k)
mA_pw = instance.mA.cv(alt, y)[0]
mB_pw = instance.mB.cv(alt, y)[0]
# # now do with mcmc as cross-check
# FIXME: removing MCMC results for now because they don't make sense and need to be debugged
# mA_mcmc = instance.mA.cv_nuts(scheme=kfold, y=y, prng_key=sampling_key, ndraws=mc_reps, nchains=n_chains, nwarmup=n_warmup)
# mB_mcmc = instance.mB.cv_nuts(scheme=kfold, y=y, prng_key=sampling_key, ndraws=mc_reps, nchains=n_chains, nwarmup=n_warmup)
res = dict(
index=i,
alpha=alpha,
mA_elppd=mA["mean_elppd"],
mB_elppd=mB["mean_elppd"],
mA_eljpd=mA["mean_eljpd"],
mB_eljpd=mB["mean_eljpd"],
sel_elppd=mA["mean_elppd"] - mB["mean_elppd"],
sel_eljpd=mA["mean_eljpd"] - mB["mean_eljpd"],
mA_joint=mA_joint,
mB_joint=mB_joint,
sel_joint=mA_joint - mB_joint,
mA_pw=mA_pw,
mB_pw=mB_pw,
sel_pw=mA_pw - mB_pw,
# mA_mcmc_joint=mA_mcmc['joint'].elpdhat,
# mB_mcmc_joint=mB_mcmc['joint'].elpdhat,
# sel_joint_mcmc=mA_mcmc['joint'].elpdhat - mB_mcmc['joint'].elpdhat,
# mA_mcmc_pw=mA_mcmc['pw'].elpdhat,
# mB_mcmc_pw=mB_mcmc['pw'].elpdhat,
# sel_pw_mcmc=mA_mcmc['pw'].elpdhat - mB_mcmc['pw'].elpdhat,
T=T,
n=n_posts,
mc_reps=mc_reps,
k=k,
seed=seed,
)
results.append(res)
save() # checkpoint
click.echo(f"Saved results to {filename}")
| 9,112 | 39.323009 | 137 | py |
arx | arx-master/arx/arx.py | """Full ARX(p,q) model, using quadrature for inference.
This limited first version can only do inference for p=1,
but can simulate from any ARX(p,q) dgp.
"""
f"This script needs python 3.x"
from jax.config import config
from arx.cv import CVScheme
config.update("jax_enable_x64", True)
from collections import namedtuple
from typing import Callable, Tuple, Dict
import arviz as az
import blackjax
import jax
import jax.numpy as jnp
from chex import Array, PRNGKey, assert_rank, assert_shape, dataclass
from jax.experimental import sparse
from jax.numpy import exp, log
from jax.numpy.linalg import det, slogdet, solve
from jax.scipy.linalg import solve_triangular, inv
from jax.scipy.optimize import minimize
from jax.scipy.special import gammaln, logsumexp
from jax.scipy.stats import beta, multivariate_normal
from scipy.integrate import quad
from scipy.optimize import minimize_scalar
from tensorflow_probability.substrates.jax import bijectors as tfb
from tensorflow_probability.substrates.jax import distributions as tfd
from enum import Enum
class Evaluation(Enum):
POINTWISE = 1
JOINT = 2
Theta = namedtuple("Theta", ["phi", "beta", "sigsq"])
# parameter space transformations for MCMC
sigsq_tfm = tfb.Exp()
phi_tfm = tfb.Sigmoid(low=-1, high=1)
def make_L(phi: Array, T: int):
assert_rank(phi, 1) # vector
L = jnp.eye(T)
for i in range(len(phi)):
L += jnp.diag(jnp.repeat(-phi[i], T - 1 - i), k=-i - 1)
return L
def make_L_ar1(phi: Array, T: int):
assert_rank(phi, 0) # scalar
return jnp.eye(T) + jnp.diag(-phi * jnp.ones(T - 1), k=-1)
def nig_logpdf(x: Array, mu: Array, Sigma: Array, a: float, b: float) -> float:
"""Normal-inverse-gamma log density"""
assert_rank(x, 1)
assert_rank(mu, 1)
assert_rank(Sigma, 2)
assert_shape(Sigma, (len(x), len(x)))
p = len(x)
e = x - mu
return (
gammaln(0.5 * p + a)
- gammaln(a)
+ a * log(b)
- 0.5 * p * log(2 * jnp.pi)
- 0.5 * slogdet(Sigma)[1]
- (0.5 * p + a) * log(b + 0.5 * jnp.dot(e, solve(Sigma, e)))
)
# https://blackjax-devs.github.io/blackjax/examples/change_of_variable_hmc.html#arviz-plots
def arviz_trace_from_states(position, info, burn_in=0):
"""Create Arviz trace from states
Args:
position: position member of blackjax states
info: multichain info object
"""
if isinstance(position, jnp.DeviceArray): # if states.position is array of samples
position = dict(samples=position)
else:
try:
position = position._asdict()
except AttributeError:
pass
samples = {}
for param in position.keys():
ndims = len(position[param].shape)
if ndims >= 2:
samples[param] = jnp.swapaxes(position[param], 0, 1)[
:, burn_in:
] # swap n_samples and n_chains
divergence = jnp.swapaxes(info.is_divergent[burn_in:], 0, 1)
if ndims == 1:
divergence = info.is_divergent
samples[param] = position[param]
trace_posterior = az.convert_to_inference_data(samples)
trace_sample_stats = az.convert_to_inference_data(
{"diverging": divergence}, group="sample_stats"
)
trace = az.concat(trace_posterior, trace_sample_stats)
return trace
CVPosteriorSet = namedtuple("CVPosteriorSet", ["elpdhat", "contribs", "posts"])
class ARX:
"""Full ARX(p,q) model, using quadrature for inference."""
def __init__(
self,
T: int,
phi_star: Array,
sigsq_star: float,
beta_star: Array,
mu_beta0: Array = None,
sigma_beta0: Array = None,
a_phi0: float = 1.0,
b_phi0: float = 1.0,
a_sigsq0: float = 1.0,
b_sigsq0: float = 1.0,
Z: Array = None,
):
self.T = T
self.phi_star = phi_star
self.sigsq_star = sigsq_star
self.beta_star = beta_star
self.q = Z.shape[1]
self.mu_beta0 = mu_beta0
if self.mu_beta0 is None:
self.mu_beta0 = jnp.zeros(self.q)
self.sigma_beta0 = sigma_beta0
if self.sigma_beta0 is None:
self.sigma_beta0 = jnp.eye(self.q)
self.a_phi0 = a_phi0
self.b_phi0 = b_phi0
self.a_sigsq0 = a_sigsq0
self.b_sigsq0 = b_sigsq0
self.Z = Z
self.sigma_beta0_inv = jnp.linalg.inv(self.sigma_beta0)
self.p = len(self.phi_star)
assert_rank(self.phi_star, 1)
assert_rank(self.beta_star, 1)
assert_rank(self.Z, 2)
assert_shape(self.Z, (self.T, len(self.beta_star)))
def simulate(self, key: PRNGKey = None) -> Array:
L = make_L(self.phi_star, self.T)
mstar = solve_triangular(L, self.Z @ self.beta_star, lower=True)
eps = jax.random.normal(key, shape=(self.T,))
return mstar + jnp.sqrt(self.sigsq_star) * solve_triangular(L, eps, lower=True)
def misspecify(self, **args) -> "ARX":
# let's not futz with T because we don't want to adjust the shape of Z
assert "T" not in args, "Can't change T in misspecify()"
args["T"] = self.T
for param in [
"phi_star",
"sigsq_star",
"beta_star",
"Z",
"q",
"mu_beta0",
"sigma_beta0",
"a_phi0",
"b_phi0",
"a_sigsq0",
"b_sigsq0",
]:
if param not in args:
args[param] = getattr(self, param)
if "q" in args:
assert args["q"] <= self.q, "Can only misspecify to a lower q"
args["Z"] = self.Z[:, : args["q"]]
args["beta_star"] = self.beta_star[
: args["q"],
] # won't actually be used
args["sigma_beta0"] = self.sigma_beta0[: args["q"], : args["q"]]
args["mu_beta0"] = self.mu_beta0[: args["q"]]
del args["q"]
if "p" in args:
args["phi_star"] = args["phi_star"][
: args["p"],
]
del args["p"]
return ARX(**args) # type: ignore
def optimal_params(self, dgp: "ARX") -> Tuple[Array, Tuple[Array, Array, Array]]:
"""Compute optimal params for a misspecified model.
This is the KLD minimizing parameters with respect to the DGP.
Returns (min kld, (phi, beta, sigsq))
"""
def D(x):
phi = x[: self.p]
beta = x[self.p : (self.p + self.q)]
sigsq = x[-1]
Lk = make_L(phi, self.T)
Lstar = make_L(dgp.phi_star, self.T)
Lstar_inv = jnp.linalg.inv(Lstar)
A = Lk @ Lstar_inv
m = self.Z @ beta - A @ dgp.Z @ dgp.beta_star
return 0.5 * (
dgp.sigsq_star / sigsq * jnp.trace(A @ A.T)
- self.T
+ self.T * (jnp.log(sigsq) - jnp.log(dgp.sigsq_star))
+ m.T @ m / sigsq
)
# starting point (x0)
x0 = jnp.concatenate([jnp.zeros(self.p), jnp.ones(self.q), jnp.array([1.0])])
from jax.scipy.optimize import minimize
f = lambda theta: D(theta)
theta_min = minimize(f, x0, method="BFGS")
phi = theta_min.x[: dgp.p]
beta = theta_min.x[dgp.p : (dgp.p + dgp.q)]
sigsq = theta_min.x[-1]
return (theta_min.fun, (phi, beta, sigsq))
def phi_prior_logpdf(self, phi) -> float:
return beta.logpdf(x=0.5 * (phi + 1.0), a=self.a_phi0, b=self.b_phi0)
def beta_prior_logpdf(self, beta, sigsq):
return multivariate_normal.logpdf(
beta, mean=self.mu_beta0, cov=sigsq * self.sigma_beta0
)
def sigsq_prior_logpdf(self, sigsq):
return (
self.a_sigsq0 * log(self.b_sigsq0)
- gammaln(self.a_sigsq0)
- (self.a_sigsq0 + 1) * log(sigsq)
- self.b_sigsq0 / sigsq
)
def llhood(self, y, phi, beta, sigsq) -> float:
"""Full-data likelihood"""
L = make_L(phi, self.T)
mu = L @ y - self.Z @ beta
return -0.5 * self.T * log(2 * jnp.pi * sigsq) - 0.5 * jnp.sum(mu**2) / sigsq
def dgp_llhood(self, y: Array) -> float:
"""Return the log likelihood using stored parameters.
Args:
y: data array
"""
return self.llhood(y, self.phi_star, self.beta_star, self.sigsq_star)
def log_p_y_phi(self, phi: float, y: Array) -> float:
"""Computes log p(phi, y)
Args:
phi: univariate AR(1) autoregressive coefficient
y: data vector
"""
L = make_L_ar1(phi, self.T)
Ly = L @ y
c1 = Ly.T @ Ly + self.mu_beta0.T @ self.sigma_beta0_inv @ self.mu_beta0
Sigma_beta_inv = self.Z.T @ self.Z + self.sigma_beta0_inv
c3 = self.sigma_beta0_inv @ self.mu_beta0 + self.Z.T @ L @ y
log_c4 = (
self.phi_prior_logpdf(phi)
+ self.a_sigsq0 * log(self.b_sigsq0)
- 0.5 * (self.T) * log(2 * jnp.pi)
- 0.5 * log(det(self.sigma_beta0))
- gammaln(self.a_phi0)
)
nu = 0.5 * self.T + self.a_sigsq0
log_dens = (
log_c4
- 0.5 * log(det(Sigma_beta_inv)) # note _inv
+ gammaln(nu)
- nu * log(self.b_sigsq0 + 0.5 * (c1 - c3.T @ solve(Sigma_beta_inv, c3)))
)
return log_dens
def p_y_phi(self, phi: float, y: Array, ln_coef: float = 0) -> float:
"""Computes p(phi, y)*exp(ln_coef)
Args:
phi: univariate AR(1) autoregressive coefficient
y: data vector
ln_coef: log of coefficient to scale density
The coefficient is there to deal with roundoff error. See paper draft
for the formula (without coefficient).
"""
return exp(self.log_p_y_phi(phi, y) + ln_coef)
def log_p_y(self, y: Array) -> float:
"""Compute log evidence p(y) by adaptive quadrature.
Args:
y: data vector
This function uses adaptive quadrature from QUADPACK via scipy starting
with a Laplace estimate of log p(y).
"""
assert_shape(y, (self.T,))
# estimate log evidence Z using laplace's method
phi_ols = self.ols(y)[
0:1,
]
f = jax.jit(lambda phi: -self.log_p_y_phi(phi[0], y))
mode = minimize(f, x0=phi_ols, method="BFGS")
assert -1 < mode.x < 1, "mode of p(y, phi) out of bounds"
hessian = jax.hessian(f)(mode.x)
ln_Z_laplace = (
0.5 * jnp.log(2 * jnp.pi)
- 0.5 * jnp.log(jnp.linalg.det(hessian))
- mode.fun
)
# integrate to improve log evidence estimate, now in levels not logs
integral = quad(self.p_y_phi, a=-1.0, b=1.0, args=(y, -ln_Z_laplace))[0]
assert not integral < 0, "Panic: negative integral"
# use accurate log for value close to 1?
return log(integral) + ln_Z_laplace
def ols(self, y):
"""Estimate phi and beta using OLS"""
X = jnp.hstack(
[
jnp.expand_dims(y[0:-1], 1),
self.Z[
1:,
],
]
)
return solve(X.T @ X, X.T @ y[1:])
def post_dens(self, y: Array) -> Tuple[Callable, float]:
"""Construct multivariate posterior density function given y.
Args:
y: data vector
This is a higher-order function that returns a Callable
and the log evidence.
"""
log_p_y = self.log_p_y(y)
def post(phi, beta, sigsq):
log_joint = (
self.beta_prior_logpdf(beta=beta, sigsq=sigsq)
+ self.phi_prior_logpdf(phi=phi)
+ self.sigsq_prior_logpdf(sigsq=sigsq)
+ self.llhood(y, phi, beta, sigsq)
- log_p_y
)
return exp(log_joint)
return post, log_p_y
def post(self, y: Array, log_p_y_guess=None) -> "CVPosterior":
"""Construct posterior object given y.
Args:
y: data vector
"""
return CVPosterior(
self,
y=y,
S_test=jnp.eye(self.T),
S_train=jnp.eye(self.T),
log_p_y_guess=log_p_y_guess,
)
def fd_post(self, y: Array) -> "FullDataPosterior":
"""Full data posterior, given y
The FullDataPosterior is a spcial case of the CVPosterior that uses
the full dataset and requires fewer matrix inversions when computing
log likelihoods.
"""
post = FullDataPosterior(self, y)
return post
def fd_nuts_post(
self, y: Array, prng_key, ndraws=2000, nchains=4, nwarmup=1000
) -> "FullDataMCMCPosterior":
"""Construct posterior object given y using NUTS.
Args:
y: data vector
prng_key: random number generator key
ndraws: number of nuts draws after warmup, per chain
nchains: number of independent chains
nwarmup: number of window adaption iterations to run
"""
post = FullDataMCMCPosterior(self, y=y)
post.nuts(ndraws=ndraws, nchains=nchains, nwarmup=nwarmup, prng_key=prng_key)
return post
def cv(self, scheme: CVScheme, y: Array) -> CVPosteriorSet:
"""Compute cross-validation elpd.
Args:
scheme: cross-validation scheme
y: data vector
Note: we maintain a running moving average of the elpd estimate to use as normalizing
guesses for the next fold. This is a bit of a hack, but it seems to work well.
"""
assert_shape(y, (self.T,))
elpd_contribs, cv_posts = [], []
full_post = self.post(y)
log_p_y = full_post.log_p_y
log_p_y_tilde_g = log_p_y
for i in range(scheme.n_folds()):
fold_post = CVPosterior(
self, y, S_test=scheme.S_test(i), S_train=scheme.S_train(i), log_p_y_guess=log_p_y
)
log_p_y = 0.25 * log_p_y + 0.75 * fold_post.log_p_y
elpd_contribs.append(
fold_post.log_p_y_tilde(y, log_p_y_tilde_guess=log_p_y_tilde_g)
)
log_p_y_tilde_g = 0.25 * log_p_y_tilde_g + 0.75 * elpd_contribs[-1] # update guess moving average
cv_posts.append(fold_post)
arr_contribs = jnp.array(elpd_contribs)
return CVPosteriorSet(
elpdhat=arr_contribs.sum(),
contribs=arr_contribs,
posts=cv_posts,
)
def cv_nuts(self, scheme: CVScheme, y: Array, prng_key, ndraws=2000, nchains=4, nwarmup=1000) -> Dict[str, CVPosteriorSet]:
"""Compute cross-validation elpd using NUTS.
This method is intended for CV methods with small numbers of folds,
like K-fold CV.
Args:
scheme: cross-validation scheme
y: data vector
"""
assert_shape(y, (self.T,))
elppd_contribs, eljpd_contribs, cv_posts = [], [], []
for i in range(scheme.n_folds()):
fold_post = MCMCCVPosterior(self, y=y, S_train=scheme.S_train(i), S_test=scheme.S_test(i))
fold_post.nuts(prng_key=prng_key, ndraws=ndraws, nchains=nchains, nwarmup=nwarmup)
elppd_contribs.append(fold_post.log_p_y(evaluation=Evaluation.POINTWISE))
eljpd_contribs.append(fold_post.log_p_y(evaluation=Evaluation.JOINT))
cv_posts.append(fold_post)
elppd_contribs_a = jnp.array(elppd_contribs)
pw = CVPosteriorSet(
elpdhat=elppd_contribs_a.sum(),
contribs=elppd_contribs,
posts=cv_posts,
)
eljpd_contribs_a = jnp.array(eljpd_contribs)
j = CVPosteriorSet(
elpdhat=eljpd_contribs_a.sum(),
contribs=eljpd_contribs_a,
posts=cv_posts,
)
return {"pw": pw, "joint": j}
def cv_laplace(self, scheme: CVScheme, y: Array) -> float:
"""Compute cross-validation elpd using laplace approximation.
Args:
scheme: cross-validation scheme
y: data vector
"""
assert_shape(y, (self.T,))
elpd_contribs = []
for i in range(scheme.n_folds()):
fold_post = CVPosterior(self, y, scheme.S_test(i), scheme.S_train(i))
elpd_contribs.append(fold_post.log_p_y_tilde_laplace(y))
return jnp.sum(jnp.array(elpd_contribs))
class FullDataPosterior:
"""ARX Posterior for full data
This is a separate class from CVPosterior because we can avoid inverting L in the
likelihood when S_train is the identity.
"""
def __init__(self, m: ARX, y):
self.m = m
self.T = m.T
self.y = y
self.Sigma_beta = jnp.linalg.inv(self.m.sigma_beta0_inv + self.m.Z.T @ self.m.Z)
def log_y_tilde_phi(self, y_tilde: Array, phi: float, S_test: Array) -> float:
"""Posterior predictive log density for y_tilde, conditional on phi"""
# posterior mean and variance - full data
L = make_L_ar1(phi, self.T)
LinvZ = solve_triangular(L, self.m.Z, lower=True)
Linv = solve_triangular(L, jnp.eye(self.T), lower=True)
StLinv = S_test @ Linv
SW_phiS = StLinv @ StLinv.T
mu_beta = self.Sigma_beta @ (
self.m.Z.T @ L @ self.y + self.m.sigma_beta0_inv @ self.m.mu_beta0
)
# gaussian predictive parameters, marginalized down to elements selected by S_test
mkphi_ff = S_test @ LinvZ @ mu_beta
Vk_ff = SW_phiS + S_test @ LinvZ @ self.Sigma_beta @ LinvZ.T @ S_test.T
cond_lpdf = nig_logpdf(
S_test @ y_tilde, mkphi_ff, Vk_ff, self.m.a_sigsq0, self.m.b_sigsq0
)
return cond_lpdf + self.m.phi_prior_logpdf(phi)
def log_p_y_tilde(self, y_tilde, log_guess):
I_T = jnp.eye(self.T)
def f(phi):
return exp(self.log_y_tilde_phi(y_tilde, phi, I_T) - log_guess)
integral = quad(f, a=-1, b=1)[0]
return log(integral) + log_guess
def log_p_y_tilde_pw(self, y_tilde, log_guess):
"""Compute pointwise predictive density.
Returns total predictive AND array of shape (T,) contributions
log_guess should be on the order of individual contributions
"""
def elpd_contrib(i):
# 1xT selection matrix, so S y_tilde is objective
S_test = jnp.expand_dims(1.0 * (jnp.arange(self.T) == i), axis=0)
def f(phi):
return exp(self.log_y_tilde_phi(y_tilde, phi, S_test) - log_guess)
integral = quad(f, a=-1, b=1)[0]
return log(integral) + log_guess
contribs = jnp.array(list(map(elpd_contrib, jnp.arange(self.T))))
return jnp.sum(contribs), contribs
def elpd_mc_quad(self, dgp, log_p_y_tilde_guess, prng_key, mc_reps=500):
"""Return a Monte Carlo estimate of the elpd using quadrature.
Args:
y: data vector
dgp: model for generating data replicates
mc_reps: number of samples to draw from dgp
This is an "oracle" version of the elpd, in that it uses the true
model to generate data replicates.
"""
key, self.prng_key = jax.random.split(prng_key)
keys = jax.random.split(key, mc_reps)
# can't parallelize via vmap because log_p_y_tilde uses scipy quad
elpd_hats = []
log_guess = log_p_y_tilde_guess
for (i, key) in enumerate(keys):
y_tilde = dgp.simulate(key)
elpd = self.log_p_y_tilde(y_tilde, log_guess=log_guess)
log_guess = 0.25 * log_guess + 0.75 * elpd # update guess
elpd_hats.append(elpd)
# use mean here not logmeanexp because we want the expectation of the
# log predictive density
return {"mean": jnp.mean(jnp.array(elpd_hats)), "elpd_hats": jnp.stack(elpd_hats)}
class FullDataMCMCPosterior:
"""MCMC Posterior for full data
This is a separate class from CVPosterior because we can avoid inverting L in the
likelihood when S_train is the identity.
"""
def __init__(self, m: ARX, y):
self.m = m
self.T = m.T
self.y = y
self.Sigma_beta = jnp.linalg.inv(self.m.sigma_beta0_inv + self.m.Z.T @ self.m.Z)
def log_joint(self, theta: Theta):
"""Log joint p(y, phi, beta, sigsq) for MCMC."""
phi = phi_tfm.forward(theta.phi)
phi_ldj = phi_tfm.forward_log_det_jacobian(theta.phi)
sigsq = sigsq_tfm.forward(theta.sigsq)
sigsq_ldj = sigsq_tfm.forward_log_det_jacobian(theta.sigsq)
beta = theta.beta
L = make_L_ar1(phi, self.T)
e = L @ self.y - self.m.Z @ beta
return (
# transform log det jacobians
+phi_ldj
+ sigsq_ldj
# likelihood
- 0.5 * self.T * jnp.log(sigsq)
- 0.5 * jnp.dot(e, e) / sigsq
# priors
+ self.m.phi_prior_logpdf(phi)
+ self.m.beta_prior_logpdf(beta, sigsq)
+ self.m.sigsq_prior_logpdf(sigsq)
)
def inference_loop(self, rng_key, kernel, initial_states, num_samples, num_chains):
"""MCMC inference loop with multiple chains"""
@jax.jit
def one_step(states, rng_key):
keys = jax.random.split(rng_key, num_chains)
states, infos = jax.vmap(kernel)(keys, states)
return states, (states, infos)
keys = jax.random.split(rng_key, num_samples)
_, (states, infos) = jax.lax.scan(one_step, initial_states, keys)
return (states, infos)
def nuts(self, prng_key: PRNGKey, ndraws=2000, nchains=4, nwarmup=1000):
init_key, warmup_key, sampling_key = jax.random.split(prng_key, 3)
# use stan's window adaption algo to choose step size and mass matrix
warmup = blackjax.window_adaptation(blackjax.nuts, self.log_joint, nwarmup)
def warmed_up_states(seed, param):
state, _, _ = warmup.run(seed, param)
return state
warmup_ipos = self.initial_positions(nchains, init_key)
warmup_keys = jax.random.split(warmup_key, nchains)
initial_states = jax.vmap(warmed_up_states)(warmup_keys, warmup_ipos)
# construct kernel using warmup, which we need to run again
_, kernel, _ = warmup.run(warmup_key, self.init_param_fn(init_key))
states, info = self.inference_loop(
sampling_key, kernel, initial_states, ndraws, nchains
)
# wait until program is done on device
states.position.phi.block_until_ready()
# transform states back to constrained space
position = Theta(
phi=jax.vmap(phi_tfm.forward)(states.position.phi),
sigsq=jax.vmap(sigsq_tfm.forward)(states.position.sigsq),
beta=states.position.beta,
)
self.position = position
self.info = info
return self.arviz()
def initial_positions(self, n_chains, rng_key):
keys = jax.random.split(rng_key, n_chains)
return jax.vmap(self.init_param_fn)(keys)
def init_param_fn(self, key):
"""Initial parameters in unconstrained space."""
k1, k2, k3 = jax.random.split(key, 3)
return Theta(
sigsq=tfd.Normal(0, 1).sample(seed=k1),
beta=tfd.MultivariateNormalDiag(
loc=jnp.zeros(self.m.q), scale_diag=jnp.ones(self.m.q)
).sample(seed=k2),
phi=tfd.Normal(0, 1).sample(seed=k3),
)
def arviz(self):
return arviz_trace_from_states(self.position, self.info)
def estimate_elpd(self, dgp, draws_az, prng_key=None, nreps=500):
"""Estimate the expected log predictive density using MCMC.
Args:
dgp: True DGP
draws_az: Arviz InferenceData object
prng_key: rng state for generating ytilde replicates
nreps: number of ytilde replicates to generate
PRNGKey should not be in the range of keys used for data generation.
"""
y_tilde_keys = jax.random.split(prng_key, nreps)
y_tildes = jax.vmap(dgp.simulate)(y_tilde_keys)
draws = az.extract(draws_az, combined=True, num_samples=nreps)
M = draws.dims["sample"]
phi = jnp.array(draws["phi"])
beta = jnp.array(draws["beta"])
sigsq = jnp.array(draws["sigsq"])
def elpd_for_draw(self, phi, beta, sigsq):
L = make_L_ar1(phi, self.T)
Linv = jnp.linalg.inv(L)
Wphi = Linv @ Linv.T
Zbeta = self.m.Z @ beta
pred_mean = jnp.linalg.solve(L, Zbeta)
def eljpd(y_tilde):
return (
-0.5 * self.m.T * jnp.log(2 * jnp.pi * sigsq)
# log(det(Wphi)) == 0
- 0.5 * jnp.sum((L @ y_tilde - Zbeta) ** 2) / sigsq
)
def elppd_point(y_tilde):
return (
# vectors of length T
-0.5 * jnp.log(2 * jnp.pi * sigsq * jnp.diag(Wphi))
- 0.5 * ((y_tilde - pred_mean) ** 2) / (sigsq * jnp.diag(Wphi))
)
draw_eljpd = jax.vmap(eljpd)(y_tildes)
draw_rep_pw_contribs = jax.vmap(elppd_point)(y_tildes)
return {"eljpd": draw_eljpd, "elppd_point": draw_rep_pw_contribs}
estimates = jax.vmap(elpd_for_draw, in_axes=(None, 0, 1, 0))(
self, phi, beta, sigsq
)
eljpds = logsumexp(estimates["eljpd"], axis=0) - jnp.log(M)
elppd_point_contribs = logsumexp(estimates["elppd_point"], axis=0) - jnp.log(M)
# add T pointwise contributions to get elppds
elppds = jnp.sum(elppd_point_contribs, axis=1)
# average over y_tilde reps to estimate elpd
return {
"mean_eljpd": jnp.mean(eljpds),
"std_eljpd": jnp.std(eljpds),
"mean_elppd": jnp.mean(elppds),
"std_elppd": jnp.std(elppds),
}
class CVPosterior:
"""ARX Posterior for a CV fold
All computations here are specialized versions of the above that deal with
a subset of the data.
"""
def __init__(
self,
m: ARX,
y: Array,
S_test: Array = None,
S_train: Array = None,
log_p_y_guess=None,
):
self.m: ARX = m
self.T = m.T
self.S_test = S_test
self.S_train = S_train
self.y = y
self.n = S_train.shape[0]
self.v = S_test.shape[0]
assert_shape(y, (self.m.T,))
assert_rank(S_test, 2)
assert_rank(S_train, 2)
assert S_test.shape[1] == self.T
assert S_train.shape[1] == self.T
if log_p_y_guess is None:
self.log_p_y = self.log_p_y_laplace()
else:
self.log_p_y = log_p_y_guess
self.log_p_y = self.log_p_y_quad(guess=self.log_p_y)
def log_p_y_quad(self, guess) -> float:
"""Compute log evidence p(y) by adaptive quadrature.
Args:
A guess for the log evidence. Can come from laplace approximation or
something else.
This function uses adaptive quadrature from QUADPACK via scipy starting
with a Laplace estimate of log p(y).
"""
g = jax.jit(lambda phi: jnp.exp(self.log_p_y_phi(phi) - guess))
integral = quad(g, a=-1.0, b=1.0)[0]
assert not integral < 0, "Panic: negative likelihood"
return log(integral) + guess
def log_p_y_laplace(self) -> float:
"""Approximate log evidence p(y) by Laplace approximation."""
f = jax.jit(lambda phi: -self.log_p_y_phi(phi))
mode = minimize_scalar(f, bounds=[-1, 1], method="bounded")
hessian = jax.hessian(f)(mode.x)
return 0.5 * jnp.log(2 * jnp.pi) - 0.5 * jnp.log(hessian) - mode.fun
def log_p_y_phi(self, phi: float) -> float:
"""Computes log p(phi, y)
Args:
phi: univariate AR(1) autoregressive coefficient
"""
L = make_L_ar1(phi, self.T)
Linv = solve_triangular(L, jnp.eye(self.T), lower=True)
StrainLinv = self.S_train @ Linv
Sigma_y_phi = (
StrainLinv
@ (jnp.eye(self.T) + self.m.Z @ self.m.sigma_beta0 @ self.m.Z.T)
@ StrainLinv.T
)
mu_y_phi = StrainLinv @ self.m.Z @ self.m.mu_beta0
log_p_y_given_phi = nig_logpdf(
self.S_train @ self.y,
mu_y_phi,
Sigma_y_phi,
self.m.a_sigsq0,
self.m.b_sigsq0,
)
return log_p_y_given_phi + self.m.phi_prior_logpdf(phi)
# log joint density log p(y_tilde, phi | y)
def log_p_phi_ytilde(self, phi, y_tilde):
L = make_L_ar1(phi, self.T)
Linv = solve_triangular(L, jnp.eye(self.T), lower=True)
LinvZ = solve_triangular(L, self.m.Z, lower=True)
Sy = jnp.hstack([self.S_train @ self.y, self.S_test @ y_tilde])
mu = jnp.vstack([self.S_train, self.S_test]) @ LinvZ @ self.m.mu_beta0
ZSZ = self.m.Z @ self.m.sigma_beta0 @ self.m.Z.T
StrainLinv = self.S_train @ Linv
StestLinv = self.S_test @ Linv
IT = jnp.eye(self.T)
Sigma = jnp.block(
[
[
StrainLinv @ (IT + ZSZ) @ StrainLinv.T,
StrainLinv @ ZSZ @ StestLinv.T,
],
[
StestLinv @ ZSZ @ StrainLinv.T,
StestLinv @ (IT + ZSZ) @ StestLinv.T,
],
]
)
log_p_y_given_phi = nig_logpdf(
Sy,
mu,
Sigma,
self.m.a_sigsq0,
self.m.b_sigsq0,
)
return log_p_y_given_phi + self.m.phi_prior_logpdf(phi) - self.log_p_y
def marg_post_phi(self, phi: float) -> float:
"""Phi marginal"""
return exp(self.log_p_y_phi(phi) - self.log_p_y)
def log_p_y_tilde(self, y_tilde: Array, log_p_y_tilde_guess) -> float:
"""Compute predictive log density log p(y_tilde | y)
Args:
y_tilde: full length test data vector w/ shape (T,)
"""
f = jax.jit(
lambda phi: exp(self.log_p_phi_ytilde(phi, y_tilde) - log_p_y_tilde_guess)
)
pred = quad(f, a=-1, b=1)[0]
return jnp.log(pred) + log_p_y_tilde_guess
def log_p_y_tilde_laplace(self, y_tilde: Array) -> float:
"""Approximate log p(y_tilde | y) by Laplace approximation.
Args:
y_tilde: full length test data vector w/ shape (T,)
"""
f = jax.jit(lambda phi: -self.log_p_phi_ytilde(phi, y_tilde))
mode = minimize_scalar(f, bounds=[-1, 1], method="bounded")
assert -1 < mode.x < 1, f"mode of p(y, phi) ({mode.x}) out of bounds"
hessian = jax.hessian(f)(mode.x)
return 0.5 * jnp.log(2 * jnp.pi) - 0.5 * jnp.log(hessian) - mode.fun
def elpd_mc_quad(self, dgp, log_p_y_tilde_guess, n_samples=500):
"""Return a Monte Carlo estimate of the elpd using quadrature.
Args:
y: data vector
dgp: model for generating data replicates
n_samples: number of samples to draw from dgp
This is an "oracle" version of the elpd, in that it uses the true
model to generate data replicates.
"""
key, self.prng_key = jax.random.split(self.prng_key)
keys = jax.random.split(key, n_samples)
y_tildes = jax.vmap(dgp.simulate)(keys)
# can't parallelize via vmap because log_p_y_tilde uses scipy quad
elpd_hats = list(
map(lambda yt: self.log_p_y_tilde(yt, log_p_y_tilde_guess), y_tildes)
)
return {"mean": jnp.mean(elpd_hats), "elpd_hats": elpd_hats}
def elpd_mc_laplace(self, dgp, prng_key, n_samples=1000):
"""Return a Monte Carlo estimate of the elpd using Laplace approximation.
Args:
y: data vector
dgp: model for generating data replicates
n_samples: number of samples to draw from dgp
This is an "oracle" version of the elpd, in that it uses the true
model to generate data replicates.
"""
keys = jax.random.split(prng_key, n_samples)
y_tildes = jax.vmap(dgp.simulate)(keys)
elpd_hats = jax.vmap(lambda yt: self.log_p_y_tilde_laplace(yt))(y_tildes)
return jnp.mean(elpd_hats)
class MCMCCVPosterior:
"""MCMC variant of CV posterior.
This version uses nuts to estimate the posterior. Note, mcmc must be
run after object creation. This is to facilitate testing etc.
"""
def __init__(self, m, y, S_train, S_test):
self.m = m
self.T = m.T
self.q = m.q
self.y = y
self.S_train = S_train
self.S_test = S_test
self.n = S_train.sum()
def log_joint(self, theta: Theta):
"""Log joint p(y, phi, beta, sigsq) for MCMC.
This version of the log joint is reduced to just the training set
by S_train.
"""
# transform unconstrained theta to constrained parameter space
phi = phi_tfm.forward(theta.phi)
phi_ldj = phi_tfm.forward_log_det_jacobian(theta.phi)
sigsq = sigsq_tfm.forward(theta.sigsq)
sigsq_ldj = sigsq_tfm.forward_log_det_jacobian(theta.sigsq)
beta = theta.beta
L = make_L(jnp.array([phi]), self.T)
Linv = solve_triangular(L, jnp.eye(self.T), lower=True)
Se = self.S_train @ (self.y - Linv @ self.m.Z @ beta)
SWSt = self.S_train @ (Linv @ Linv.T) @ self.S_train.T
return (
# transform log det jacobians
phi_ldj
+ sigsq_ldj
# likelihood
- 0.5 * self.n * jnp.log(2 * jnp.pi)
- 0.5 * self.n * jnp.log(sigsq)
- 0.5 * jnp.linalg.slogdet(SWSt)[1]
- 0.5 * jnp.dot(Se, solve(SWSt, Se)) / sigsq
# priors
+ self.m.phi_prior_logpdf(phi)
+ self.m.beta_prior_logpdf(beta, sigsq)
+ self.m.sigsq_prior_logpdf(sigsq)
)
def inference_loop(self, rng_key, kernel, initial_states, num_samples, num_chains):
"""MCMC inference loop with multiple chains"""
@jax.jit
def one_step(states, rng_key):
keys = jax.random.split(rng_key, num_chains)
states, infos = jax.vmap(kernel)(keys, states)
return states, (states, infos)
keys = jax.random.split(rng_key, num_samples)
_, (states, infos) = jax.lax.scan(one_step, initial_states, keys)
return (states, infos)
def nuts(self, prng_key, ndraws=2000, nchains=4, nwarmup=1000):
init_key, warmup_key, sampling_key = jax.random.split(prng_key, 3)
# use stan's window adaption algo to choose step size and mass matrix
warmup = blackjax.window_adaptation(blackjax.nuts, self.log_joint, nwarmup)
initial_states = jax.vmap(lambda key, param: warmup.run(key, param)[0])(
jax.random.split(warmup_key, nchains),
self.initial_positions(nchains, init_key)
)
# construct kernel using warmup, which we need to run again
_, kernel, _ = warmup.run(warmup_key, self.init_param_fn(init_key))
states, info = self.inference_loop(
sampling_key, kernel, initial_states, ndraws, nchains
)
# wait until program is done on device
states.position.phi.block_until_ready()
# transform states back to constrained space
position = Theta(
phi=jax.vmap(phi_tfm.forward)(states.position.phi),
sigsq=jax.vmap(sigsq_tfm.forward)(states.position.sigsq),
beta=states.position.beta,
)
self.position = position
self.info = info
return self.arviz()
def initial_positions(self, n_chains, rng_key):
keys = jax.random.split(rng_key, n_chains)
return jax.vmap(self.init_param_fn)(keys)
def init_param_fn(self, key):
k1, k2, k3 = jax.random.split(key, 3)
return Theta(
sigsq=tfd.Normal(0, 1).sample(seed=k1),
beta=tfd.MultivariateNormalDiag(
loc=jnp.zeros(self.q), scale_diag=jnp.ones(self.q)
).sample(seed=k2),
phi=tfd.Normal(0, 1).sample(seed=k3),
)
def arviz(self):
return arviz_trace_from_states(self.position, self.info)
def log_p_y(self, evaluation: Evaluation = Evaluation.JOINT):
"""Log predictive density p(y* | y)
Note that self.position has already been transformed back to constrained parameters.
"""
# joint version returns a scalar per fold
def lpred_joint(phi, beta, sigsq):
L = make_L(jnp.array([phi]), self.T)
StestLinv = self.S_test @ inv(L)
m = StestLinv @ self.m.Z @ beta
cov = sigsq * StestLinv @ StestLinv.T
return tfd.MultivariateNormalFullCovariance(loc=m, covariance_matrix=cov).log_prob(self.S_test @ self.y)
# pointwise version needs to return a vector of contributions,
# to be combined with logsumexp coordinatewise
def lpred_pw(phi, beta, sigsq):
L = make_L(jnp.array([phi]), self.T)
StestLinv = self.S_test @ inv(L)
m = StestLinv @ self.m.Z @ beta
sigs = jnp.sqrt(jnp.diag(sigsq * StestLinv @ StestLinv.T))
return tfd.Normal(loc=m, scale=sigs).log_prob(self.S_test @ self.y)
lpred = lpred_joint if evaluation == Evaluation.JOINT else lpred_pw
phis = jnp.reshape(self.position.phi, (-1))
sigsqs = jnp.reshape(self.position.sigsq, (-1))
betas = jnp.reshape(self.position.beta, (-1, self.q))
contribs = jax.vmap(lpred)(phis, betas, sigsqs)
M = phis.shape[0]
unnorm_contrib = logsumexp(contribs, axis=0) - jnp.log(M)
return unnorm_contrib.sum()
| 38,201 | 35.732692 | 127 | py |
arx | arx-master/arx/experiments_test.py | import os
import unittest
import experiments as ex
import jax
import sarx_experiments as sx
import arx
class TestExperimentInstance(unittest.TestCase):
def setUp(self) -> None:
self.ex1 = ex.make_full_experiment(1, "hard", simplified=False)
def test_experiment_instance(self) -> None:
key = jax.random.PRNGKey(0)
inst = self.ex1.make_instance(alpha=0.5, T=110, prng_key=key)
self.assertEqual(inst.dgp.T, 110)
self.assertIsInstance(inst.dgp, arx.ARX)
self.assertIsInstance(inst.mA, arx.ARX)
self.assertIsInstance(inst.mB, arx.ARX)
for m in [inst.dgp, inst.mA, inst.mB]:
self.assertEqual(m.T, 110)
self.assertEqual(inst.dgp.q, 3)
self.assertEqual(inst.mA.q, 2)
self.assertEqual(inst.mB.q, 1)
def test_full_bayes_experiment(self) -> None:
# just a smoke test
TGT = "/tmp/ex1C.csv"
if os.path.isfile(TGT):
os.remove(TGT)
ex.full_bayes(
1,
"easy",
n_posts=2,
T=10,
mc_reps=10,
filename=TGT,
seed=0,
n_warmup=100,
n_chains=2,
)
assert os.path.isfile(TGT)
os.remove(TGT)
class TestSARXExperiments(unittest.TestCase):
def testExcludedEffect(self):
filename = "/tmp/excluded_effect.csv"
if os.path.isfile(filename):
os.remove(filename)
sx.by_excluded_effect(filename=filename, ex_no=1, variant="easy", T=20, seed=0)
assert os.path.isfile(filename)
os.remove(filename)
def testIncludedEffect(self):
filename = "/tmp/included_effect.csv"
if os.path.isfile(filename):
os.remove(filename)
sx.by_included_effect(filename=filename, ex_no=1, variant="easy", T=20, seed=0)
assert os.path.isfile(filename)
os.remove(filename)
def testDataLength(self):
filename = "/tmp/data_length.csv"
if os.path.isfile(filename):
os.remove(filename)
sx.by_data_length(filename=filename, ex_no=1, variant="easy", T=20, seed=0)
assert os.path.isfile(filename)
os.remove(filename)
def testByHalo(self):
filename = "/tmp/by_halo.csv"
if os.path.isfile(filename):
os.remove(filename)
sx.by_halo(filename=filename, ex_no=1, variant="easy", T=20, seed=0)
assert os.path.isfile(filename)
os.remove(filename)
def testByDimension(self):
filename = "/tmp/by_dimension.csv"
if os.path.isfile(filename):
os.remove(filename)
sx.by_dimension(filename=filename, ex_no=1, variant="easy", T=20, seed=0)
assert os.path.isfile(filename)
os.remove(filename)
| 2,784 | 30.647727 | 87 | py |
ADaPTION | ADaPTION-master/tools/extra/summarize.py | #!/usr/bin/env python
"""Net summarization tool.
This tool summarizes the structure of a net in a concise but comprehensive
tabular listing, taking a prototxt file as input.
Use this tool to check at a glance that the computation you've specified is the
computation you expect.
"""
from caffe.proto import caffe_pb2
from google import protobuf
import re
import argparse
# ANSI codes for coloring blobs (used cyclically)
COLORS = ['92', '93', '94', '95', '97', '96', '42', '43;30', '100',
'444', '103;30', '107;30']
DISCONNECTED_COLOR = '41'
def read_net(filename):
net = caffe_pb2.NetParameter()
with open(filename) as f:
protobuf.text_format.Parse(f.read(), net)
return net
def format_param(param):
out = []
if len(param.name) > 0:
out.append(param.name)
if param.lr_mult != 1:
out.append('x{}'.format(param.lr_mult))
if param.decay_mult != 1:
out.append('Dx{}'.format(param.decay_mult))
return ' '.join(out)
def printed_len(s):
return len(re.sub(r'\033\[[\d;]+m', '', s))
def print_table(table, max_width):
"""Print a simple nicely-aligned table.
table must be a list of (equal-length) lists. Columns are space-separated,
and as narrow as possible, but no wider than max_width. Text may overflow
columns; note that unlike string.format, this will not affect subsequent
columns, if possible."""
max_widths = [max_width] * len(table[0])
column_widths = [max(printed_len(row[j]) + 1 for row in table)
for j in range(len(table[0]))]
column_widths = [min(w, max_w) for w, max_w in zip(column_widths, max_widths)]
for row in table:
row_str = ''
right_col = 0
for cell, width in zip(row, column_widths):
right_col += width
row_str += cell + ' '
row_str += ' ' * max(right_col - printed_len(row_str), 0)
print row_str
def summarize_net(net):
disconnected_tops = set()
for lr in net.layer:
disconnected_tops |= set(lr.top)
disconnected_tops -= set(lr.bottom)
table = []
colors = {}
for lr in net.layer:
tops = []
for ind, top in enumerate(lr.top):
color = colors.setdefault(top, COLORS[len(colors) % len(COLORS)])
if top in disconnected_tops:
top = '\033[1;4m' + top
if len(lr.loss_weight) > 0:
top = '{} * {}'.format(lr.loss_weight[ind], top)
tops.append('\033[{}m{}\033[0m'.format(color, top))
top_str = ', '.join(tops)
bottoms = []
for bottom in lr.bottom:
color = colors.get(bottom, DISCONNECTED_COLOR)
bottoms.append('\033[{}m{}\033[0m'.format(color, bottom))
bottom_str = ', '.join(bottoms)
if lr.type == 'Python':
type_str = lr.python_param.module + '.' + lr.python_param.layer
else:
type_str = lr.type
# Summarize conv/pool parameters.
# TODO support rectangular/ND parameters
conv_param = lr.convolution_param
if (lr.type in ['Convolution', 'Deconvolution']
and len(conv_param.kernel_size) == 1):
arg_str = str(conv_param.kernel_size[0])
if len(conv_param.stride) > 0 and conv_param.stride[0] != 1:
arg_str += '/' + str(conv_param.stride[0])
if len(conv_param.pad) > 0 and conv_param.pad[0] != 0:
arg_str += '+' + str(conv_param.pad[0])
arg_str += ' ' + str(conv_param.num_output)
if conv_param.group != 1:
arg_str += '/' + str(conv_param.group)
elif lr.type == 'Pooling':
arg_str = str(lr.pooling_param.kernel_size)
if lr.pooling_param.stride != 1:
arg_str += '/' + str(lr.pooling_param.stride)
if lr.pooling_param.pad != 0:
arg_str += '+' + str(lr.pooling_param.pad)
else:
arg_str = ''
if len(lr.param) > 0:
param_strs = map(format_param, lr.param)
if max(map(len, param_strs)) > 0:
param_str = '({})'.format(', '.join(param_strs))
else:
param_str = ''
else:
param_str = ''
table.append([lr.name, type_str, param_str, bottom_str, '->', top_str,
arg_str])
return table
def main():
parser = argparse.ArgumentParser(description="Print a concise summary of net computation.")
parser.add_argument('filename', help='net prototxt file to summarize')
parser.add_argument('-w', '--max-width', help='maximum field width',
type=int, default=30)
args = parser.parse_args()
net = read_net(args.filename)
table = summarize_net(net)
print_table(table, max_width=args.max_width)
if __name__ == '__main__':
main()
| 4,880 | 33.617021 | 95 | py |
ADaPTION | ADaPTION-master/tools/extra/parse_log.py | #!/usr/bin/env python
"""
Parse training log
Evolved from parse_log.sh
"""
import os
import re
import extract_seconds
import argparse
import csv
from collections import OrderedDict
def parse_log(path_to_log):
"""Parse log file
Returns (train_dict_list, test_dict_list)
train_dict_list and test_dict_list are lists of dicts that define the table
rows
"""
regex_iteration = re.compile('Iteration (\d+)')
regex_train_output = re.compile('Train net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_learning_rate = re.compile('lr = ([-+]?[0-9]*\.?[0-9]+([eE]?[-+]?[0-9]+)?)')
# Pick out lines of interest
iteration = -1
learning_rate = float('NaN')
train_dict_list = []
test_dict_list = []
train_row = None
test_row = None
logfile_year = extract_seconds.get_log_created_year(path_to_log)
with open(path_to_log) as f:
start_time = extract_seconds.get_start_time(f, logfile_year)
for line in f:
iteration_match = regex_iteration.search(line)
if iteration_match:
iteration = float(iteration_match.group(1))
if iteration == -1:
# Only start parsing for other stuff if we've found the first
# iteration
continue
time = extract_seconds.extract_datetime_from_line(line,
logfile_year)
seconds = (time - start_time).total_seconds()
learning_rate_match = regex_learning_rate.search(line)
if learning_rate_match:
learning_rate = float(learning_rate_match.group(1))
train_dict_list, train_row = parse_line_for_net_output(
regex_train_output, train_row, train_dict_list,
line, iteration, seconds, learning_rate
)
test_dict_list, test_row = parse_line_for_net_output(
regex_test_output, test_row, test_dict_list,
line, iteration, seconds, learning_rate
)
fix_initial_nan_learning_rate(train_dict_list)
fix_initial_nan_learning_rate(test_dict_list)
return train_dict_list, test_dict_list
def parse_line_for_net_output(regex_obj, row, row_dict_list,
line, iteration, seconds, learning_rate):
"""Parse a single line for training or test output
Returns a a tuple with (row_dict_list, row)
row: may be either a new row or an augmented version of the current row
row_dict_list: may be either the current row_dict_list or an augmented
version of the current row_dict_list
"""
output_match = regex_obj.search(line)
if output_match:
if not row or row['NumIters'] != iteration:
# Push the last row and start a new one
if row:
# If we're on a new iteration, push the last row
# This will probably only happen for the first row; otherwise
# the full row checking logic below will push and clear full
# rows
row_dict_list.append(row)
row = OrderedDict([
('NumIters', iteration),
('Seconds', seconds),
('LearningRate', learning_rate)
])
# output_num is not used; may be used in the future
# output_num = output_match.group(1)
output_name = output_match.group(2)
output_val = output_match.group(3)
row[output_name] = float(output_val)
if row and len(row_dict_list) >= 1 and len(row) == len(row_dict_list[0]):
# The row is full, based on the fact that it has the same number of
# columns as the first row; append it to the list
row_dict_list.append(row)
row = None
return row_dict_list, row
def fix_initial_nan_learning_rate(dict_list):
"""Correct initial value of learning rate
Learning rate is normally not printed until after the initial test and
training step, which means the initial testing and training rows have
LearningRate = NaN. Fix this by copying over the LearningRate from the
second row, if it exists.
"""
if len(dict_list) > 1:
dict_list[0]['LearningRate'] = dict_list[1]['LearningRate']
def save_csv_files(logfile_path, output_dir, train_dict_list, test_dict_list,
delimiter=',', verbose=False):
"""Save CSV files to output_dir
If the input log file is, e.g., caffe.INFO, the names will be
caffe.INFO.train and caffe.INFO.test
"""
log_basename = os.path.basename(logfile_path)
train_filename = os.path.join(output_dir, log_basename + '.train')
write_csv(train_filename, train_dict_list, delimiter, verbose)
test_filename = os.path.join(output_dir, log_basename + '.test')
write_csv(test_filename, test_dict_list, delimiter, verbose)
def write_csv(output_filename, dict_list, delimiter, verbose=False):
"""Write a CSV file
"""
if not dict_list:
if verbose:
print('Not writing %s; no lines to write' % output_filename)
return
dialect = csv.excel
dialect.delimiter = delimiter
with open(output_filename, 'w') as f:
dict_writer = csv.DictWriter(f, fieldnames=dict_list[0].keys(),
dialect=dialect)
dict_writer.writeheader()
dict_writer.writerows(dict_list)
if verbose:
print 'Wrote %s' % output_filename
def parse_args():
description = ('Parse a Caffe training log into two CSV files '
'containing training and testing information')
parser = argparse.ArgumentParser(description=description)
parser.add_argument('logfile_path',
help='Path to log file')
parser.add_argument('output_dir',
help='Directory in which to place output CSV files')
parser.add_argument('--verbose',
action='store_true',
help='Print some extra info (e.g., output filenames)')
parser.add_argument('--delimiter',
default=',',
help=('Column delimiter in output files '
'(default: \'%(default)s\')'))
args = parser.parse_args()
return args
def main():
args = parse_args()
train_dict_list, test_dict_list = parse_log(args.logfile_path)
save_csv_files(args.logfile_path, args.output_dir, train_dict_list,
test_dict_list, delimiter=args.delimiter)
if __name__ == '__main__':
main()
| 6,688 | 32.613065 | 86 | py |
ADaPTION | ADaPTION-master/examples/web_demo/app.py | import os
import time
import cPickle
import datetime
import logging
import flask
import werkzeug
import optparse
import tornado.wsgi
import tornado.httpserver
import numpy as np
import pandas as pd
from PIL import Image
import cStringIO as StringIO
import urllib
import exifutil
import caffe
REPO_DIRNAME = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../..')
UPLOAD_FOLDER = '/tmp/caffe_demos_uploads'
ALLOWED_IMAGE_EXTENSIONS = set(['png', 'bmp', 'jpg', 'jpe', 'jpeg', 'gif'])
# Obtain the flask app object
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('index.html', has_result=False)
@app.route('/classify_url', methods=['GET'])
def classify_url():
imageurl = flask.request.args.get('imageurl', '')
try:
string_buffer = StringIO.StringIO(
urllib.urlopen(imageurl).read())
image = caffe.io.load_image(string_buffer)
except Exception as err:
# For any exception we encounter in reading the image, we will just
# not continue.
logging.info('URL Image open error: %s', err)
return flask.render_template(
'index.html', has_result=True,
result=(False, 'Cannot open image from URL.')
)
logging.info('Image: %s', imageurl)
result = app.clf.classify_image(image)
return flask.render_template(
'index.html', has_result=True, result=result, imagesrc=imageurl)
@app.route('/classify_upload', methods=['POST'])
def classify_upload():
try:
# We will save the file to disk for possible data collection.
imagefile = flask.request.files['imagefile']
filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
werkzeug.secure_filename(imagefile.filename)
filename = os.path.join(UPLOAD_FOLDER, filename_)
imagefile.save(filename)
logging.info('Saving to %s.', filename)
image = exifutil.open_oriented_im(filename)
except Exception as err:
logging.info('Uploaded image open error: %s', err)
return flask.render_template(
'index.html', has_result=True,
result=(False, 'Cannot open uploaded image.')
)
result = app.clf.classify_image(image)
return flask.render_template(
'index.html', has_result=True, result=result,
imagesrc=embed_image_html(image)
)
def embed_image_html(image):
"""Creates an image embedded in HTML base64 format."""
image_pil = Image.fromarray((255 * image).astype('uint8'))
image_pil = image_pil.resize((256, 256))
string_buf = StringIO.StringIO()
image_pil.save(string_buf, format='png')
data = string_buf.getvalue().encode('base64').replace('\n', '')
return 'data:image/png;base64,' + data
def allowed_file(filename):
return (
'.' in filename and
filename.rsplit('.', 1)[1] in ALLOWED_IMAGE_EXTENSIONS
)
class ImagenetClassifier(object):
default_args = {
'model_def_file': (
'{}/models/bvlc_reference_caffenet/deploy.prototxt'.format(REPO_DIRNAME)),
'pretrained_model_file': (
'{}/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'.format(REPO_DIRNAME)),
'mean_file': (
'{}/python/caffe/imagenet/ilsvrc_2012_mean.npy'.format(REPO_DIRNAME)),
'class_labels_file': (
'{}/data/ilsvrc12/synset_words.txt'.format(REPO_DIRNAME)),
'bet_file': (
'{}/data/ilsvrc12/imagenet.bet.pickle'.format(REPO_DIRNAME)),
}
for key, val in default_args.iteritems():
if not os.path.exists(val):
raise Exception(
"File for {} is missing. Should be at: {}".format(key, val))
default_args['image_dim'] = 256
default_args['raw_scale'] = 255.
def __init__(self, model_def_file, pretrained_model_file, mean_file,
raw_scale, class_labels_file, bet_file, image_dim, gpu_mode):
logging.info('Loading net and associated files...')
if gpu_mode:
caffe.set_mode_gpu()
else:
caffe.set_mode_cpu()
self.net = caffe.Classifier(
model_def_file, pretrained_model_file,
image_dims=(image_dim, image_dim), raw_scale=raw_scale,
mean=np.load(mean_file).mean(1).mean(1), channel_swap=(2, 1, 0)
)
with open(class_labels_file) as f:
labels_df = pd.DataFrame([
{
'synset_id': l.strip().split(' ')[0],
'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0]
}
for l in f.readlines()
])
self.labels = labels_df.sort('synset_id')['name'].values
self.bet = cPickle.load(open(bet_file))
# A bias to prefer children nodes in single-chain paths
# I am setting the value to 0.1 as a quick, simple model.
# We could use better psychological models here...
self.bet['infogain'] -= np.array(self.bet['preferences']) * 0.1
def classify_image(self, image):
try:
starttime = time.time()
scores = self.net.predict([image], oversample=True).flatten()
endtime = time.time()
indices = (-scores).argsort()[:5]
predictions = self.labels[indices]
# In addition to the prediction text, we will also produce
# the length for the progress bar visualization.
meta = [
(p, '%.5f' % scores[i])
for i, p in zip(indices, predictions)
]
logging.info('result: %s', str(meta))
# Compute expected information gain
expected_infogain = np.dot(
self.bet['probmat'], scores[self.bet['idmapping']])
expected_infogain *= self.bet['infogain']
# sort the scores
infogain_sort = expected_infogain.argsort()[::-1]
bet_result = [(self.bet['words'][v], '%.5f' % expected_infogain[v])
for v in infogain_sort[:5]]
logging.info('bet result: %s', str(bet_result))
return (True, meta, bet_result, '%.3f' % (endtime - starttime))
except Exception as err:
logging.info('Classification error: %s', err)
return (False, 'Something went wrong when classifying the '
'image. Maybe try another one?')
def start_tornado(app, port=5000):
http_server = tornado.httpserver.HTTPServer(
tornado.wsgi.WSGIContainer(app))
http_server.listen(port)
print("Tornado server starting on port {}".format(port))
tornado.ioloop.IOLoop.instance().start()
def start_from_terminal(app):
"""
Parse command line options and start the server.
"""
parser = optparse.OptionParser()
parser.add_option(
'-d', '--debug',
help="enable debug mode",
action="store_true", default=False)
parser.add_option(
'-p', '--port',
help="which port to serve content on",
type='int', default=5000)
parser.add_option(
'-g', '--gpu',
help="use gpu mode",
action='store_true', default=False)
opts, args = parser.parse_args()
ImagenetClassifier.default_args.update({'gpu_mode': opts.gpu})
# Initialize classifier + warm start by forward for allocation
app.clf = ImagenetClassifier(**ImagenetClassifier.default_args)
app.clf.net.forward()
if opts.debug:
app.run(debug=True, host='0.0.0.0', port=opts.port)
else:
start_tornado(app, opts.port)
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
start_from_terminal(app)
| 7,793 | 33.184211 | 105 | py |
ADaPTION | ADaPTION-master/examples/pycaffe/caffenet.py | from __future__ import print_function
from caffe import layers as L, params as P, to_proto
from caffe.proto import caffe_pb2
# helper function for common structures
def conv_relu(bottom, ks, nout, stride=1, pad=0, group=1):
conv = L.Convolution(bottom, kernel_size=ks, stride=stride,
num_output=nout, pad=pad, group=group)
return conv, L.ReLU(conv, in_place=True)
def fc_relu(bottom, nout):
fc = L.InnerProduct(bottom, num_output=nout)
return fc, L.ReLU(fc, in_place=True)
def max_pool(bottom, ks, stride=1):
return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride)
def caffenet(lmdb, batch_size=256, include_acc=False):
data, label = L.Data(source=lmdb, backend=P.Data.LMDB, batch_size=batch_size, ntop=2,
transform_param=dict(crop_size=227, mean_value=[104, 117, 123], mirror=True))
# the net itself
conv1, relu1 = conv_relu(data, 11, 96, stride=4)
pool1 = max_pool(relu1, 3, stride=2)
norm1 = L.LRN(pool1, local_size=5, alpha=1e-4, beta=0.75)
conv2, relu2 = conv_relu(norm1, 5, 256, pad=2, group=2)
pool2 = max_pool(relu2, 3, stride=2)
norm2 = L.LRN(pool2, local_size=5, alpha=1e-4, beta=0.75)
conv3, relu3 = conv_relu(norm2, 3, 384, pad=1)
conv4, relu4 = conv_relu(relu3, 3, 384, pad=1, group=2)
conv5, relu5 = conv_relu(relu4, 3, 256, pad=1, group=2)
pool5 = max_pool(relu5, 3, stride=2)
fc6, relu6 = fc_relu(pool5, 4096)
drop6 = L.Dropout(relu6, in_place=True)
fc7, relu7 = fc_relu(drop6, 4096)
drop7 = L.Dropout(relu7, in_place=True)
fc8 = L.InnerProduct(drop7, num_output=1000)
loss = L.SoftmaxWithLoss(fc8, label)
if include_acc:
acc = L.Accuracy(fc8, label)
return to_proto(loss, acc)
else:
return to_proto(loss)
def make_net():
with open('train.prototxt', 'w') as f:
print(caffenet('/path/to/caffe-train-lmdb'), file=f)
with open('test.prototxt', 'w') as f:
print(caffenet('/path/to/caffe-val-lmdb', batch_size=50, include_acc=True), file=f)
if __name__ == '__main__':
make_net()
| 2,112 | 36.732143 | 91 | py |
ADaPTION | ADaPTION-master/examples/pycaffe/tools.py | import numpy as np
class SimpleTransformer:
"""
SimpleTransformer is a simple class for preprocessing and deprocessing
images for caffe.
"""
def __init__(self, mean=[128, 128, 128]):
self.mean = np.array(mean, dtype=np.float32)
self.scale = 1.0
def set_mean(self, mean):
"""
Set the mean to subtract for centering the data.
"""
self.mean = mean
def set_scale(self, scale):
"""
Set the data scaling.
"""
self.scale = scale
def preprocess(self, im):
"""
preprocess() emulate the pre-processing occuring in the vgg16 caffe
prototxt.
"""
im = np.float32(im)
im = im[:, :, ::-1] # change to BGR
im -= self.mean
im *= self.scale
im = im.transpose((2, 0, 1))
return im
def deprocess(self, im):
"""
inverse of preprocess()
"""
im = im.transpose(1, 2, 0)
im /= self.scale
im += self.mean
im = im[:, :, ::-1] # change to RGB
return np.uint8(im)
class CaffeSolver:
"""
Caffesolver is a class for creating a solver.prototxt file. It sets default
values and can export a solver parameter file.
Note that all parameters are stored as strings. Strings variables are
stored as strings in strings.
"""
def __init__(self, testnet_prototxt_path="testnet.prototxt",
trainnet_prototxt_path="trainnet.prototxt", debug=False):
self.sp = {}
# critical:
self.sp['base_lr'] = '0.001'
self.sp['momentum'] = '0.9'
# speed:
self.sp['test_iter'] = '100'
self.sp['test_interval'] = '250'
# looks:
self.sp['display'] = '25'
self.sp['snapshot'] = '2500'
self.sp['snapshot_prefix'] = '"snapshot"' # string withing a string!
# learning rate policy
self.sp['lr_policy'] = '"fixed"'
# important, but rare:
self.sp['gamma'] = '0.1'
self.sp['weight_decay'] = '0.0005'
self.sp['train_net'] = '"' + trainnet_prototxt_path + '"'
self.sp['test_net'] = '"' + testnet_prototxt_path + '"'
# pretty much never change these.
self.sp['max_iter'] = '100000'
self.sp['test_initialization'] = 'false'
self.sp['average_loss'] = '25' # this has to do with the display.
self.sp['iter_size'] = '1' # this is for accumulating gradients
if (debug):
self.sp['max_iter'] = '12'
self.sp['test_iter'] = '1'
self.sp['test_interval'] = '4'
self.sp['display'] = '1'
def add_from_file(self, filepath):
"""
Reads a caffe solver prototxt file and updates the Caffesolver
instance parameters.
"""
with open(filepath, 'r') as f:
for line in f:
if line[0] == '#':
continue
splitLine = line.split(':')
self.sp[splitLine[0].strip()] = splitLine[1].strip()
def write(self, filepath):
"""
Export solver parameters to INPUT "filepath". Sorted alphabetically.
"""
f = open(filepath, 'w')
for key, value in sorted(self.sp.items()):
if not(type(value) is str):
raise TypeError('All solver parameters must be strings')
f.write('%s: %s\n' % (key, value))
| 3,457 | 27.344262 | 79 | py |
ADaPTION | ADaPTION-master/examples/pycaffe/layers/pascal_multilabel_datalayers.py | # imports
import json
import time
import pickle
import scipy.misc
import skimage.io
import caffe
import numpy as np
import os.path as osp
from xml.dom import minidom
from random import shuffle
from threading import Thread
from PIL import Image
from tools import SimpleTransformer
class PascalMultilabelDataLayerSync(caffe.Layer):
"""
This is a simple synchronous datalayer for training a multilabel model on
PASCAL.
"""
def setup(self, bottom, top):
self.top_names = ['data', 'label']
# === Read input parameters ===
# params is a python dictionary with layer parameters.
params = eval(self.param_str)
# Check the parameters for validity.
check_params(params)
# store input as class variables
self.batch_size = params['batch_size']
# Create a batch loader to load the images.
self.batch_loader = BatchLoader(params, None)
# === reshape tops ===
# since we use a fixed input image size, we can shape the data layer
# once. Else, we'd have to do it in the reshape call.
top[0].reshape(
self.batch_size, 3, params['im_shape'][0], params['im_shape'][1])
# Note the 20 channels (because PASCAL has 20 classes.)
top[1].reshape(self.batch_size, 20)
print_info("PascalMultilabelDataLayerSync", params)
def forward(self, bottom, top):
"""
Load data.
"""
for itt in range(self.batch_size):
# Use the batch loader to load the next image.
im, multilabel = self.batch_loader.load_next_image()
# Add directly to the caffe data layer
top[0].data[itt, ...] = im
top[1].data[itt, ...] = multilabel
def reshape(self, bottom, top):
"""
There is no need to reshape the data, since the input is of fixed size
(rows and columns)
"""
pass
def backward(self, top, propagate_down, bottom):
"""
These layers does not back propagate
"""
pass
class BatchLoader(object):
"""
This class abstracts away the loading of images.
Images can either be loaded singly, or in a batch. The latter is used for
the asyncronous data layer to preload batches while other processing is
performed.
"""
def __init__(self, params, result):
self.result = result
self.batch_size = params['batch_size']
self.pascal_root = params['pascal_root']
self.im_shape = params['im_shape']
# get list of image indexes.
list_file = params['split'] + '.txt'
self.indexlist = [line.rstrip('\n') for line in open(
osp.join(self.pascal_root, 'ImageSets/Main', list_file))]
self._cur = 0 # current image
# this class does some simple data-manipulations
self.transformer = SimpleTransformer()
print "BatchLoader initialized with {} images".format(
len(self.indexlist))
def load_next_image(self):
"""
Load the next image in a batch.
"""
# Did we finish an epoch?
if self._cur == len(self.indexlist):
self._cur = 0
shuffle(self.indexlist)
# Load an image
index = self.indexlist[self._cur] # Get the image index
image_file_name = index + '.jpg'
im = np.asarray(Image.open(
osp.join(self.pascal_root, 'JPEGImages', image_file_name)))
im = scipy.misc.imresize(im, self.im_shape) # resize
# do a simple horizontal flip as data augmentation
flip = np.random.choice(2)*2-1
im = im[:, ::flip, :]
# Load and prepare ground truth
multilabel = np.zeros(20).astype(np.float32)
anns = load_pascal_annotation(index, self.pascal_root)
for label in anns['gt_classes']:
# in the multilabel problem we don't care how MANY instances
# there are of each class. Only if they are present.
# The "-1" is b/c we are not interested in the background
# class.
multilabel[label - 1] = 1
self._cur += 1
return self.transformer.preprocess(im), multilabel
def load_pascal_annotation(index, pascal_root):
"""
This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083).
Thanks Ross!
"""
classes = ('__background__', # always index 0
'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'diningtable', 'dog', 'horse',
'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'tvmonitor')
class_to_ind = dict(zip(classes, xrange(21)))
filename = osp.join(pascal_root, 'Annotations', index + '.xml')
# print 'Loading: {}'.format(filename)
def get_data_from_tag(node, tag):
return node.getElementsByTagName(tag)[0].childNodes[0].data
with open(filename) as f:
data = minidom.parseString(f.read())
objs = data.getElementsByTagName('object')
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, 21), dtype=np.float32)
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
# Make pixel indexes 0-based
x1 = float(get_data_from_tag(obj, 'xmin')) - 1
y1 = float(get_data_from_tag(obj, 'ymin')) - 1
x2 = float(get_data_from_tag(obj, 'xmax')) - 1
y2 = float(get_data_from_tag(obj, 'ymax')) - 1
cls = class_to_ind[
str(get_data_from_tag(obj, "name")).lower().strip()]
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
overlaps = scipy.sparse.csr_matrix(overlaps)
return {'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'flipped': False,
'index': index}
def check_params(params):
"""
A utility function to check the parameters for the data layers.
"""
assert 'split' in params.keys(
), 'Params must include split (train, val, or test).'
required = ['batch_size', 'pascal_root', 'im_shape']
for r in required:
assert r in params.keys(), 'Params must include {}'.format(r)
def print_info(name, params):
"""
Output some info regarding the class
"""
print "{} initialized for split: {}, with bs: {}, im_shape: {}.".format(
name,
params['split'],
params['batch_size'],
params['im_shape'])
| 6,846 | 30.552995 | 78 | py |
ADaPTION | ADaPTION-master/examples/pycaffe/layers/pyloss.py | import caffe
import numpy as np
class EuclideanLossLayer(caffe.Layer):
"""
Compute the Euclidean Loss in the same manner as the C++ EuclideanLossLayer
to demonstrate the class interface for developing layers in Python.
"""
def setup(self, bottom, top):
# check input pair
if len(bottom) != 2:
raise Exception("Need two inputs to compute distance.")
def reshape(self, bottom, top):
# check input dimensions match
if bottom[0].count != bottom[1].count:
raise Exception("Inputs must have the same dimension.")
# difference is shape of inputs
self.diff = np.zeros_like(bottom[0].data, dtype=np.float32)
# loss output is scalar
top[0].reshape(1)
def forward(self, bottom, top):
self.diff[...] = bottom[0].data - bottom[1].data
top[0].data[...] = np.sum(self.diff**2) / bottom[0].num / 2.
def backward(self, top, propagate_down, bottom):
for i in range(2):
if not propagate_down[i]:
continue
if i == 0:
sign = 1
else:
sign = -1
bottom[i].diff[...] = sign * self.diff / bottom[i].num
| 1,223 | 31.210526 | 79 | py |
ADaPTION | ADaPTION-master/examples/low_precision/imagenet/visualization/Visualization_weights.py | import caffe
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
plt.rcParams['font.size'] = 20
# plt.rcParams['xtick.labelzie'] = 18
def make_2d(data):
return np.reshape(data, (data.shape[0], -1))
caffe.set_mode_gpu()
caffe.set_device(0)
caffe_root = '/home/moritz/Repositories/caffe_lp/'
model_root = 'examples/low_precision/imagenet/models/'
snapshot_root = '/media/moritz/Data/ILSVRC2015/Snapshots/'
# prototxt_file = caffe_root + model_root + 'VGG16_deploy_vis.prototxt'
# prototxt_file = caffe_root + model_root + 'LP_VGG16_0_7_vis.prototxt'
# prototxt_file = caffe_root + model_root + 'LP_VGG16_1_6_vis.prototxt'
# prototxt_file = caffe_root + model_root + 'LP_VGG16_2_5_vis.prototxt'
# prototxt_file = caffe_root + model_root + 'LP_VGG16_0_15_vis.prototxt'
# prototxt_file = caffe_root + model_root + 'LP_VGG16_1_14_vis.prototxt'
# prototxt_file = caffe_root + model_root + 'LP_VGG16_2_13_vis.prototxt'
# prototxt_file = caffe_root + model_root + 'LP_VGG16_3_12_vis.prototxt'
prototxt_file = caffe_root + model_root + 'LP_VGG16_5_10_vis.prototxt'
# weights_file = '/home/moritz/Downloads/VGG16_tmp/' + 'LP_VGG16.caffemodel.h5'
# weights_file = '/home/moritz/Downloads/VGG16_tmp/' + 'HP_VGG16.caffemodel'
weights_file = '/home/moritz/Downloads/VGG16_tmp/' + 'converted_hp_weights.caffemodel'
net = caffe.Net(prototxt_file, weights_file, caffe.TEST)
print('Doing forward pass...')
net.forward()
print('Done.')
# %matplotlib inline
print("All params in the net: {}".format(net.params.keys()))
print("All blobs in the net: {}".format(net.blobs.keys()))
# Extract the data
data = net.blobs['data'].data
labels = net.blobs['label'].data
print('Input data shape: {}'.format(data.shape))
# Build a translation dictionary for the labels that converts label to text
trans_dict = {0.: 'Left', 1.: 'Center', 2.: 'Right', 3.: 'Not Visible'}
# Pick out four images to process
show_data = [0, 2, 3, 1]
# plt.figure(1, figsize=(8, 8))
# for iter_num, d_idx in enumerate(show_data):
# plt.subplot(2, 2, iter_num + 1)
# plt.imshow(data[d_idx, 0, :, :], interpolation='nearest', cmap='gray')
# # plt.title(trans_dict[labels[d_idx]])
# plt.colorbar()
# plt.draw()
print 'Start plotting the weights'
binwidth = 0.001
bd = 5
ad = 10
ymax = 100
x_min = -0.5
x_max = 0.5
nb_bins = 100
if 'LP' in prototxt_file:
hp = False
l_idx1 = 'conv_lp_1'
l_idx2 = 'conv_lp_3'
l_idx3 = 'conv_lp_6'
l_idx4 = 'conv_lp_8'
l_idx5 = 'conv_lp_11'
l_idx6 = 'conv_lp_13'
l_idx7 = 'conv_lp_15'
l_idx8 = 'conv_lp_18'
l_idx9 = 'conv_lp_20'
l_idx10 = 'conv_lp_22'
l_idx11 = 'conv_lp_25'
l_idx12 = 'conv_lp_27'
l_idx13 = 'conv_lp_29'
l_idx14 = 'fc_lp_32'
l_idx15 = 'fc_lp_34'
l_idx16 = 'fc_lp_36'
else:
hp = True
l_idx1 = 'conv1_1'
l_idx2 = 'conv1_2'
l_idx3 = 'conv2_1'
l_idx4 = 'conv2_2'
l_idx5 = 'conv3_1'
l_idx6 = 'conv3_2'
l_idx7 = 'conv3_3'
l_idx8 = 'conv4_1'
l_idx9 = 'conv4_2'
l_idx10 = 'conv4_3'
l_idx11 = 'conv5_1'
l_idx12 = 'conv5_2'
l_idx13 = 'conv5_3'
l_idx14 = 'fc6'
l_idx15 = 'fc7'
l_idx16 = 'fc8'
print hp
# hp = True
if hp:
# plt.figure(2, figsize=(16, 8))
# plt.subplot(2, 4, 1)
# plt.title('High precision Weight Matrix {}'.format(l_idx1))
# plt.imshow(make_2d(net.params[l_idx1][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 2)
# plt.title('High precision Weight Matrix {}'.format(l_idx2))
# plt.imshow(make_2d(net.params[l_idx2][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 3)
# plt.title('High precision Weight Matrix {}'.format(l_idx3))
# plt.imshow(make_2d(net.params[l_idx3][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 4)
# plt.title('High precision Weight Matrix {}'.format(l_idx4))
# plt.imshow(make_2d(net.params[l_idx4][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 5)
# plt.title('High precision Weight Matrix {}'.format(l_idx1))
# show_data = net.params[l_idx1][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 6)
# plt.title('High precision Weight Matrix {}'.format(l_idx2))
# show_data = net.params[l_idx2][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 7)
# plt.title('High precision Weight Matrix {}'.format(l_idx3))
# show_data = net.params[l_idx3][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 8)
# plt.title('High precision Weight Matrix {}'.format(l_idx4))
# show_data = net.params[l_idx4][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.show()
# plt.figure(3, figsize=(16, 8))
# plt.subplot(2, 4, 1)
# plt.title('High precision Weight Matrix {}'.format(l_idx5))
# plt.imshow(make_2d(net.params[l_idx5][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 2)
# plt.title('High precision Weight Matrix {}'.format(l_idx6))
# plt.imshow(make_2d(net.params[l_idx6][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 3)
# plt.title('High precision Weight Matrix {}'.format(l_idx7))
# plt.imshow(make_2d(net.params[l_idx7][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 4)
# plt.title('High precision Weight Matrix {}'.format(l_idx8))
# plt.imshow(make_2d(net.params[l_idx8][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 5)
# plt.title('High precision Weight Matrix {}'.format(l_idx5))
# show_data = net.params[l_idx5][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 6)
# plt.title('High precision Weight Matrix {}'.format(l_idx6))
# show_data = net.params[l_idx6][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 7)
# plt.title('High precision Weight Matrix {}'.format(l_idx7))
# show_data = net.params[l_idx7][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 8)
# plt.title('High precision Weight Matrix {}'.format(l_idx8))
# show_data = net.params[l_idx8][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.tight_layout()
# plt.show()
# plt.figure(4, figsize=(16, 8))
# plt.subplot(2, 4, 1)
# plt.title('High precision Weight Matrix {}'.format(l_idx9))
# plt.imshow(make_2d(net.params[l_idx9][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 2)
# plt.title('High precision Weight Matrix {}'.format(l_idx10))
# plt.imshow(make_2d(net.params[l_idx10][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 3)
# plt.title('High precision Weight Matrix {}'.format(l_idx11))
# plt.imshow(make_2d(net.params[l_idx11][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 4)
# plt.title('High precision Weight Matrix {}'.format(l_idx12))
# plt.imshow(make_2d(net.params[l_idx12][0].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 5)
# plt.title('High precision Weight Matrix {}'.format(l_idx9))
# show_data = net.params[l_idx9][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 6)
# plt.title('High precision Weight Matrix {}'.format(l_idx10))
# show_data = net.params[l_idx10][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 7)
# plt.title('High precision Weight Matrix {}'.format(l_idx11))
# show_data = net.params[l_idx11][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 8)
# plt.title('High precision Weight Matrix {}'.format(l_idx12))
# show_data = net.params[l_idx12][0].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.show()
plt.figure(5, figsize=(16, 8))
plt.subplot(2, 4, 1)
plt.title('{}'.format(l_idx13))
plt.imshow(make_2d(net.params[l_idx13][0].data), interpolation='nearest', aspect='auto')
plt.colorbar()
plt.draw()
plt.subplot(2, 4, 2)
plt.title('{}'.format(l_idx14))
plt.imshow(make_2d(net.params[l_idx14][0].data), interpolation='nearest', aspect='auto')
plt.colorbar()
plt.draw()
plt.subplot(2, 4, 3)
plt.title('{}'.format(l_idx15))
plt.imshow(make_2d(net.params[l_idx15][0].data), interpolation='nearest', aspect='auto')
plt.colorbar()
plt.draw()
plt.subplot(2, 4, 4)
plt.title('{}'.format(l_idx16))
plt.imshow(make_2d(net.params[l_idx16][0].data), interpolation='nearest', aspect='auto')
plt.colorbar()
plt.draw()
plt.subplot(2, 4, 5)
plt.title('{}'.format(l_idx13))
show_data = net.params[l_idx13][0].data.flatten()
# plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
plt.hist(show_data, nb_bins)
# plt.ylim([0, ymax])
plt.draw()
plt.subplot(2, 4, 6)
plt.title('{}'.format(l_idx14))
show_data = net.params[l_idx14][0].data.flatten()
# plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
plt.hist(show_data, nb_bins)
# plt.ylim([0, ymax])
plt.draw()
plt.subplot(2, 4, 7)
plt.title('{}'.format(l_idx15))
show_data = net.params[l_idx15][0].data.flatten()
# plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
plt.hist(show_data, nb_bins)
# plt.ylim([0, ymax])
plt.draw()
plt.subplot(2, 4, 8)
plt.title('{}'.format(l_idx16))
show_data = net.params[l_idx16][0].data.flatten()
# plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
plt.hist(show_data, nb_bins)
# plt.ylim([0, ymax])
plt.draw()
plt.tight_layout()
plt.show()
else:
# 'conv_lp_1', 'conv_lp_3', 'conv_lp_6', 'conv_lp_8', 'conv_lp_11', 'conv_lp_13', 'conv_lp_15',
# 'conv_lp_18', 'conv_lp_20', 'conv_lp_22', 'conv_lp_25', 'conv_lp_27', 'conv_lp_29', 'fc_lp_32',
# 'fc_lp_34', 'fc_lp_36']
# All blobs in the net: ['data', 'label', 'label_data_1_split_0', 'label_data_1_split_1',
# 'conv_lp_1', 'act_lp_2', 'conv_lp_3', 'act_lp_4', 'pool_5', 'conv_lp_6', 'act_lp_7',
# 'conv_lp_8', 'act_lp_9', 'pool_10', 'conv_lp_11', 'act_lp_12', 'conv_lp_13', 'act_lp_14',
# 'conv_lp_15', 'act_lp_16', 'pool_17', 'conv_lp_18', 'act_lp_19', 'conv_lp_20', 'act_lp_21',
# 'conv_lp_22', 'act_lp_23', 'pool_24', 'conv_lp_25', 'act_lp_26', 'conv_lp_27', 'act_lp_28',
# 'conv_lp_29', 'act_lp_30', 'pool_31', 'fc_lp_32', 'act_lp_33', 'fc_lp_34', 'act_lp_35',
# 'fc_lp_36', 'fc_lp_36_fc_lp_36_0_split_0', 'fc_lp_36_fc_lp_36_0_split_1', 'accuracy', 'loss'
# plt.figure(2, figsize=(16, 8))
# plt.subplot(2, 4, 1)
# plt.title('Rounded Weight Matrix {}'.format(l_idx1))
# plt.imshow(make_2d(net.params[l_idx1][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 2)
# plt.title('Rounded Weight Matrix {}'.format(l_idx2))
# plt.imshow(make_2d(net.params[l_idx2][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 3)
# plt.title('Rounded Weight Matrix {}'.format(l_idx3))
# plt.imshow(make_2d(net.params[l_idx3][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 4)
# plt.title('Rounded Weight Matrix {}'.format(l_idx4))
# plt.imshow(make_2d(net.params[l_idx4][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 5)
# plt.title('rounded weight matrix {}'.format(l_idx1))
# show_data = net.params[l_idx1][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 6)
# plt.title('rounded weight matrix {}'.format(l_idx2))
# show_data = net.params[l_idx2][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 7)
# plt.title('rounded weight matrix {}'.format(l_idx3))
# show_data = net.params[l_idx3][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 8)
# plt.title('rounded weight matrix {}'.format(l_idx4))
# show_data = net.params[l_idx4][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.show()
# plt.figure(3, figsize=(16, 8))
# plt.subplot(2, 4, 1)
# plt.title('Rounded Weight Matrix {}'.format(l_idx5))
# plt.imshow(make_2d(net.params[l_idx5][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 2)
# plt.title('Rounded Weight Matrix {}'.format(l_idx6))
# plt.imshow(make_2d(net.params[l_idx6][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 3)
# plt.title('Rounded Weight Matrix {}'.format(l_idx7))
# plt.imshow(make_2d(net.params[l_idx7][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 4)
# plt.title('Rounded Weight Matrix {}'.format(l_idx8))
# plt.imshow(make_2d(net.params[l_idx8][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 5)
# plt.title('rounded weight matrix {}'.format(l_idx5))
# show_data = net.params[l_idx5][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 6)
# plt.title('rounded weight matrix {}'.format(l_idx6))
# show_data = net.params[l_idx6][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 7)
# plt.title('rounded weight matrix {}'.format(l_idx7))
# show_data = net.params[l_idx7][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 8)
# plt.title('rounded weight matrix {}'.format(l_idx8))
# show_data = net.params[l_idx8][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.show()
# plt.figure(4, figsize=(16, 8))
# plt.subplot(2, 4, 1)
# plt.title('Rounded Weight Matrix {}'.format(l_idx9))
# plt.imshow(make_2d(net.params[l_idx9][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 2)
# plt.title('Rounded Weight Matrix {}'.format(l_idx10))
# plt.imshow(make_2d(net.params[l_idx10][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 3)
# plt.title('Rounded Weight Matrix {}'.format(l_idx11))
# plt.imshow(make_2d(net.params[l_idx11][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 4)
# plt.title('Rounded Weight Matrix {}'.format(l_idx12))
# plt.imshow(make_2d(net.params[l_idx12][1].data), interpolation='nearest', aspect='auto')
# plt.colorbar()
# plt.draw()
# plt.subplot(2, 4, 5)
# plt.title('rounded weight matrix {}'.format(l_idx9))
# show_data = net.params[l_idx9][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 6)
# plt.title('rounded weight matrix {}'.format(l_idx10))
# show_data = net.params[l_idx10][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 7)
# plt.title('rounded weight matrix {}'.format(l_idx11))
# show_data = net.params[l_idx11][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.subplot(2, 4, 8)
# plt.title('rounded weight matrix {}'.format(l_idx12))
# show_data = net.params[l_idx12][1].data.flatten()
# # plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
# plt.hist(show_data, nb_bins)
# # plt.ylim([0, ymax])
# plt.draw()
# plt.show()
plt.figure(5, figsize=(16, 8))
plt.subplot(2, 4, 1)
plt.title('{}'.format(l_idx13))
plt.imshow(make_2d(net.params[l_idx13][1].data), interpolation='nearest', aspect='auto')
plt.colorbar()
plt.draw()
plt.subplot(2, 4, 2)
plt.title('{}'.format(l_idx14))
plt.imshow(make_2d(net.params[l_idx14][1].data), interpolation='nearest', aspect='auto')
plt.colorbar()
plt.draw()
plt.subplot(2, 4, 3)
plt.title('{}'.format(l_idx15))
plt.imshow(make_2d(net.params[l_idx15][1].data), interpolation='nearest', aspect='auto')
plt.colorbar()
plt.draw()
plt.subplot(2, 4, 4)
plt.title('{}'.format(l_idx16))
plt.imshow(make_2d(net.params[l_idx16][1].data), interpolation='nearest', aspect='auto')
plt.colorbar()
plt.draw()
plt.subplot(2, 4, 5)
plt.title('{}'.format(l_idx13))
show_data = net.params[l_idx13][1].data.flatten()
# plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
plt.hist(show_data, nb_bins)
# plt.ylim([0, ymax])
plt.draw()
plt.subplot(2, 4, 6)
plt.title('{}'.format(l_idx14))
show_data = net.params[l_idx14][1].data.flatten()
# plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
plt.hist(show_data, nb_bins)
# plt.ylim([0, ymax])
plt.draw()
plt.subplot(2, 4, 7)
plt.title('{}'.format(l_idx15))
show_data = net.params[l_idx15][1].data.flatten()
# plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
plt.hist(show_data, nb_bins)
# plt.ylim([0, ymax])
plt.draw()
plt.subplot(2, 4, 8)
plt.title('{}'.format(l_idx16))
show_data = net.params[l_idx16][1].data.flatten()
# plt.hist(show_data, bins=np.arange(x_min, x_max, binwidth))
plt.hist(show_data, nb_bins)
# plt.ylim([0, ymax])
plt.draw()
plt.tight_layout()
plt.show()
# plt.figure(8)
# plt.hist(show_data, 20)
# plt.title('Rounded weight distribution 1000 Class Classifier')
# plt.draw()
# plt.show() | 19,380 | 31.463987 | 98 | py |
ADaPTION | ADaPTION-master/examples/finetune_flickr_style/assemble_data.py | #!/usr/bin/env python
"""
Form a subset of the Flickr Style data, download images to dirname, and write
Caffe ImagesDataLayer training file.
"""
import os
import urllib
import hashlib
import argparse
import numpy as np
import pandas as pd
from skimage import io
import multiprocessing
# Flickr returns a special image if the request is unavailable.
MISSING_IMAGE_SHA1 = '6a92790b1c2a301c6e7ddef645dca1f53ea97ac2'
example_dirname = os.path.abspath(os.path.dirname(__file__))
caffe_dirname = os.path.abspath(os.path.join(example_dirname, '../..'))
training_dirname = os.path.join(caffe_dirname, 'data/flickr_style')
def download_image(args_tuple):
"For use with multiprocessing map. Returns filename on fail."
try:
url, filename = args_tuple
if not os.path.exists(filename):
urllib.urlretrieve(url, filename)
with open(filename) as f:
assert hashlib.sha1(f.read()).hexdigest() != MISSING_IMAGE_SHA1
test_read_image = io.imread(filename)
return True
except KeyboardInterrupt:
raise Exception() # multiprocessing doesn't catch keyboard exceptions
except:
return False
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Download a subset of Flickr Style to a directory')
parser.add_argument(
'-s', '--seed', type=int, default=0,
help="random seed")
parser.add_argument(
'-i', '--images', type=int, default=-1,
help="number of images to use (-1 for all [default])",
)
parser.add_argument(
'-w', '--workers', type=int, default=-1,
help="num workers used to download images. -x uses (all - x) cores [-1 default]."
)
parser.add_argument(
'-l', '--labels', type=int, default=0,
help="if set to a positive value, only sample images from the first number of labels."
)
args = parser.parse_args()
np.random.seed(args.seed)
# Read data, shuffle order, and subsample.
csv_filename = os.path.join(example_dirname, 'flickr_style.csv.gz')
df = pd.read_csv(csv_filename, index_col=0, compression='gzip')
df = df.iloc[np.random.permutation(df.shape[0])]
if args.labels > 0:
df = df.loc[df['label'] < args.labels]
if args.images > 0 and args.images < df.shape[0]:
df = df.iloc[:args.images]
# Make directory for images and get local filenames.
if training_dirname is None:
training_dirname = os.path.join(caffe_dirname, 'data/flickr_style')
images_dirname = os.path.join(training_dirname, 'images')
if not os.path.exists(images_dirname):
os.makedirs(images_dirname)
df['image_filename'] = [
os.path.join(images_dirname, _.split('/')[-1]) for _ in df['image_url']
]
# Download images.
num_workers = args.workers
if num_workers <= 0:
num_workers = multiprocessing.cpu_count() + num_workers
print('Downloading {} images with {} workers...'.format(
df.shape[0], num_workers))
pool = multiprocessing.Pool(processes=num_workers)
map_args = zip(df['image_url'], df['image_filename'])
results = pool.map(download_image, map_args)
# Only keep rows with valid images, and write out training file lists.
df = df[results]
for split in ['train', 'test']:
split_df = df[df['_split'] == split]
filename = os.path.join(training_dirname, '{}.txt'.format(split))
split_df[['image_filename', 'label']].to_csv(
filename, sep=' ', header=None, index=None)
print('Writing train/val for {} successfully downloaded images.'.format(
df.shape[0]))
| 3,636 | 35.737374 | 94 | py |
ADaPTION | ADaPTION-master/src/caffe/test/test_data/generate_sample_data.py | """
Generate data used in the HDF5DataLayer and GradientBasedSolver tests.
"""
import os
import numpy as np
import h5py
script_dir = os.path.dirname(os.path.abspath(__file__))
# Generate HDF5DataLayer sample_data.h5
num_cols = 8
num_rows = 10
height = 6
width = 5
total_size = num_cols * num_rows * height * width
data = np.arange(total_size)
data = data.reshape(num_rows, num_cols, height, width)
data = data.astype('float32')
# We had a bug where data was copied into label, but the tests weren't
# catching it, so let's make label 1-indexed.
label = 1 + np.arange(num_rows)[:, np.newaxis]
label = label.astype('float32')
# We add an extra label2 dataset to test HDF5 layer's ability
# to handle arbitrary number of output ("top") Blobs.
label2 = label + 1
print data
print label
with h5py.File(script_dir + '/sample_data.h5', 'w') as f:
f['data'] = data
f['label'] = label
f['label2'] = label2
with h5py.File(script_dir + '/sample_data_2_gzip.h5', 'w') as f:
f.create_dataset(
'data', data=data + total_size,
compression='gzip', compression_opts=1
)
f.create_dataset(
'label', data=label,
compression='gzip', compression_opts=1,
dtype='uint8',
)
f.create_dataset(
'label2', data=label2,
compression='gzip', compression_opts=1,
dtype='uint8',
)
with open(script_dir + '/sample_data_list.txt', 'w') as f:
f.write('src/caffe/test/test_data/sample_data.h5\n')
f.write('src/caffe/test/test_data/sample_data_2_gzip.h5\n')
# Generate GradientBasedSolver solver_data.h5
num_cols = 3
num_rows = 8
height = 10
width = 10
data = np.random.randn(num_rows, num_cols, height, width)
data = data.reshape(num_rows, num_cols, height, width)
data = data.astype('float32')
targets = np.random.randn(num_rows, 1)
targets = targets.astype('float32')
print data
print targets
with h5py.File(script_dir + '/solver_data.h5', 'w') as f:
f['data'] = data
f['targets'] = targets
with open(script_dir + '/solver_data_list.txt', 'w') as f:
f.write('src/caffe/test/test_data/solver_data.h5\n')
| 2,104 | 24.670732 | 70 | py |
ADaPTION | ADaPTION-master/python/draw_net.py | #!/usr/bin/env python
"""
Draw a graph of the net architecture.
"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from google.protobuf import text_format
import caffe
import caffe.draw
from caffe.proto import caffe_pb2
def parse_args():
"""Parse input arguments
"""
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('input_net_proto_file',
help='Input network prototxt file')
parser.add_argument('output_image_file',
help='Output image file')
parser.add_argument('--rankdir',
help=('One of TB (top-bottom, i.e., vertical), '
'RL (right-left, i.e., horizontal), or another '
'valid dot option; see '
'http://www.graphviz.org/doc/info/'
'attrs.html#k:rankdir'),
default='LR')
parser.add_argument('--phase',
help=('Which network phase to draw: can be TRAIN, '
'TEST, or ALL. If ALL, then all layers are drawn '
'regardless of phase.'),
default="ALL")
args = parser.parse_args()
return args
def main():
args = parse_args()
net = caffe_pb2.NetParameter()
text_format.Merge(open(args.input_net_proto_file).read(), net)
print('Drawing net to %s' % args.output_image_file)
phase=None;
if args.phase == "TRAIN":
phase = caffe.TRAIN
elif args.phase == "TEST":
phase = caffe.TEST
elif args.phase != "ALL":
raise ValueError("Unknown phase: " + args.phase)
caffe.draw.draw_net_to_file(net, args.output_image_file, args.rankdir,
phase)
if __name__ == '__main__':
main()
| 1,934 | 31.79661 | 81 | py |
ADaPTION | ADaPTION-master/python/detect.py | #!/usr/bin/env python
"""
detector.py is an out-of-the-box windowed detector
callable from the command line.
By default it configures and runs the Caffe reference ImageNet model.
Note that this model was trained for image classification and not detection,
and finetuning for detection can be expected to improve results.
The selective_search_ijcv_with_python code required for the selective search
proposal mode is available at
https://github.com/sergeyk/selective_search_ijcv_with_python
TODO:
- batch up image filenames as well: don't want to load all of them into memory
- come up with a batching scheme that preserved order / keeps a unique ID
"""
import numpy as np
import pandas as pd
import os
import argparse
import time
import caffe
CROP_MODES = ['list', 'selective_search']
COORD_COLS = ['ymin', 'xmin', 'ymax', 'xmax']
def main(argv):
pycaffe_dir = os.path.dirname(__file__)
parser = argparse.ArgumentParser()
# Required arguments: input and output.
parser.add_argument(
"input_file",
help="Input txt/csv filename. If .txt, must be list of filenames.\
If .csv, must be comma-separated file with header\
'filename, xmin, ymin, xmax, ymax'"
)
parser.add_argument(
"output_file",
help="Output h5/csv filename. Format depends on extension."
)
# Optional arguments.
parser.add_argument(
"--model_def",
default=os.path.join(pycaffe_dir,
"../models/bvlc_reference_caffenet/deploy.prototxt"),
help="Model definition file."
)
parser.add_argument(
"--pretrained_model",
default=os.path.join(pycaffe_dir,
"../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel"),
help="Trained model weights file."
)
parser.add_argument(
"--crop_mode",
default="selective_search",
choices=CROP_MODES,
help="How to generate windows for detection."
)
parser.add_argument(
"--gpu",
action='store_true',
help="Switch for gpu computation."
)
parser.add_argument(
"--mean_file",
default=os.path.join(pycaffe_dir,
'caffe/imagenet/ilsvrc_2012_mean.npy'),
help="Data set image mean of H x W x K dimensions (numpy array). " +
"Set to '' for no mean subtraction."
)
parser.add_argument(
"--input_scale",
type=float,
help="Multiply input features by this scale to finish preprocessing."
)
parser.add_argument(
"--raw_scale",
type=float,
default=255.0,
help="Multiply raw input by this scale before preprocessing."
)
parser.add_argument(
"--channel_swap",
default='2,1,0',
help="Order to permute input channels. The default converts " +
"RGB -> BGR since BGR is the Caffe default by way of OpenCV."
)
parser.add_argument(
"--context_pad",
type=int,
default='16',
help="Amount of surrounding context to collect in input window."
)
args = parser.parse_args()
mean, channel_swap = None, None
if args.mean_file:
mean = np.load(args.mean_file)
if mean.shape[1:] != (1, 1):
mean = mean.mean(1).mean(1)
if args.channel_swap:
channel_swap = [int(s) for s in args.channel_swap.split(',')]
if args.gpu:
caffe.set_mode_gpu()
print("GPU mode")
else:
caffe.set_mode_cpu()
print("CPU mode")
# Make detector.
detector = caffe.Detector(args.model_def, args.pretrained_model, mean=mean,
input_scale=args.input_scale, raw_scale=args.raw_scale,
channel_swap=channel_swap,
context_pad=args.context_pad)
# Load input.
t = time.time()
print("Loading input...")
if args.input_file.lower().endswith('txt'):
with open(args.input_file) as f:
inputs = [_.strip() for _ in f.readlines()]
elif args.input_file.lower().endswith('csv'):
inputs = pd.read_csv(args.input_file, sep=',', dtype={'filename': str})
inputs.set_index('filename', inplace=True)
else:
raise Exception("Unknown input file type: not in txt or csv.")
# Detect.
if args.crop_mode == 'list':
# Unpack sequence of (image filename, windows).
images_windows = [
(ix, inputs.iloc[np.where(inputs.index == ix)][COORD_COLS].values)
for ix in inputs.index.unique()
]
detections = detector.detect_windows(images_windows)
else:
detections = detector.detect_selective_search(inputs)
print("Processed {} windows in {:.3f} s.".format(len(detections),
time.time() - t))
# Collect into dataframe with labeled fields.
df = pd.DataFrame(detections)
df.set_index('filename', inplace=True)
df[COORD_COLS] = pd.DataFrame(
data=np.vstack(df['window']), index=df.index, columns=COORD_COLS)
del(df['window'])
# Save results.
t = time.time()
if args.output_file.lower().endswith('csv'):
# csv
# Enumerate the class probabilities.
class_cols = ['class{}'.format(x) for x in range(NUM_OUTPUT)]
df[class_cols] = pd.DataFrame(
data=np.vstack(df['feat']), index=df.index, columns=class_cols)
df.to_csv(args.output_file, cols=COORD_COLS + class_cols)
else:
# h5
df.to_hdf(args.output_file, 'df', mode='w')
print("Saved to {} in {:.3f} s.".format(args.output_file,
time.time() - t))
if __name__ == "__main__":
import sys
main(sys.argv)
| 5,734 | 31.95977 | 88 | py |
ADaPTION | ADaPTION-master/python/classify.py | #!/usr/bin/env python
"""
classify.py is an out-of-the-box image classifer callable from the command line.
By default it configures and runs the Caffe reference ImageNet model.
"""
import numpy as np
import os
import sys
import argparse
import glob
import time
import caffe
def main(argv):
pycaffe_dir = os.path.dirname(__file__)
parser = argparse.ArgumentParser()
# Required arguments: input and output files.
parser.add_argument(
"input_file",
help="Input image, directory, or npy."
)
parser.add_argument(
"output_file",
help="Output npy filename."
)
# Optional arguments.
parser.add_argument(
"--model_def",
default=os.path.join(pycaffe_dir,
"../models/bvlc_reference_caffenet/deploy.prototxt"),
help="Model definition file."
)
parser.add_argument(
"--pretrained_model",
default=os.path.join(pycaffe_dir,
"../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel"),
help="Trained model weights file."
)
parser.add_argument(
"--gpu",
action='store_true',
help="Switch for gpu computation."
)
parser.add_argument(
"--center_only",
action='store_true',
help="Switch for prediction from center crop alone instead of " +
"averaging predictions across crops (default)."
)
parser.add_argument(
"--images_dim",
default='256,256',
help="Canonical 'height,width' dimensions of input images."
)
parser.add_argument(
"--mean_file",
default=os.path.join(pycaffe_dir,
'caffe/imagenet/ilsvrc_2012_mean.npy'),
help="Data set image mean of [Channels x Height x Width] dimensions " +
"(numpy array). Set to '' for no mean subtraction."
)
parser.add_argument(
"--input_scale",
type=float,
help="Multiply input features by this scale to finish preprocessing."
)
parser.add_argument(
"--raw_scale",
type=float,
default=255.0,
help="Multiply raw input by this scale before preprocessing."
)
parser.add_argument(
"--channel_swap",
default='2,1,0',
help="Order to permute input channels. The default converts " +
"RGB -> BGR since BGR is the Caffe default by way of OpenCV."
)
parser.add_argument(
"--ext",
default='jpg',
help="Image file extension to take as input when a directory " +
"is given as the input file."
)
args = parser.parse_args()
image_dims = [int(s) for s in args.images_dim.split(',')]
mean, channel_swap = None, None
if args.mean_file:
mean = np.load(args.mean_file)
if args.channel_swap:
channel_swap = [int(s) for s in args.channel_swap.split(',')]
if args.gpu:
caffe.set_mode_gpu()
print("GPU mode")
else:
caffe.set_mode_cpu()
print("CPU mode")
# Make classifier.
classifier = caffe.Classifier(args.model_def, args.pretrained_model,
image_dims=image_dims, mean=mean,
input_scale=args.input_scale, raw_scale=args.raw_scale,
channel_swap=channel_swap)
# Load numpy array (.npy), directory glob (*.jpg), or image file.
args.input_file = os.path.expanduser(args.input_file)
if args.input_file.endswith('npy'):
print("Loading file: %s" % args.input_file)
inputs = np.load(args.input_file)
elif os.path.isdir(args.input_file):
print("Loading folder: %s" % args.input_file)
inputs =[caffe.io.load_image(im_f)
for im_f in glob.glob(args.input_file + '/*.' + args.ext)]
else:
print("Loading file: %s" % args.input_file)
inputs = [caffe.io.load_image(args.input_file)]
print("Classifying %d inputs." % len(inputs))
# Classify.
start = time.time()
predictions = classifier.predict(inputs, not args.center_only)
print("Done in %.2f s." % (time.time() - start))
# Save
print("Saving results into %s" % args.output_file)
np.save(args.output_file, predictions)
if __name__ == '__main__':
main(sys.argv)
| 4,262 | 29.669065 | 88 | py |
ADaPTION | ADaPTION-master/python/caffe/net_spec.py | """Python net specification.
This module provides a way to write nets directly in Python, using a natural,
functional style. See examples/pycaffe/caffenet.py for an example.
Currently this works as a thin wrapper around the Python protobuf interface,
with layers and parameters automatically generated for the "layers" and
"params" pseudo-modules, which are actually objects using __getattr__ magic
to generate protobuf messages.
Note that when using to_proto or Top.to_proto, names of intermediate blobs will
be automatically generated. To explicitly specify blob names, use the NetSpec
class -- assign to its attributes directly to name layers, and call
NetSpec.to_proto to serialize all assigned layers.
This interface is expected to continue to evolve as Caffe gains new capabilities
for specifying nets. In particular, the automatically generated layer names
are not guaranteed to be forward-compatible.
"""
from collections import OrderedDict, Counter
from .proto import caffe_pb2
from google import protobuf
import six
def param_name_dict():
"""Find out the correspondence between layer names and parameter names."""
layer = caffe_pb2.LayerParameter()
# get all parameter names (typically underscore case) and corresponding
# type names (typically camel case), which contain the layer names
# (note that not all parameters correspond to layers, but we'll ignore that)
param_names = [f.name for f in layer.DESCRIPTOR.fields if f.name.endswith('_param')]
param_type_names = [type(getattr(layer, s)).__name__ for s in param_names]
# strip the final '_param' or 'Parameter'
param_names = [s[:-len('_param')] for s in param_names]
param_type_names = [s[:-len('Parameter')] for s in param_type_names]
return dict(zip(param_type_names, param_names))
def to_proto(*tops):
"""Generate a NetParameter that contains all layers needed to compute
all arguments."""
layers = OrderedDict()
autonames = Counter()
for top in tops:
top.fn._to_proto(layers, {}, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net
def assign_proto(proto, name, val):
"""Assign a Python object to a protobuf message, based on the Python
type (in recursive fashion). Lists become repeated fields/messages, dicts
become messages, and other types are assigned directly. For convenience,
repeated fields whose values are not lists are converted to single-element
lists; e.g., `my_repeated_int_field=3` is converted to
`my_repeated_int_field=[3]`."""
is_repeated_field = hasattr(getattr(proto, name), 'extend')
if is_repeated_field and not isinstance(val, list):
val = [val]
if isinstance(val, list):
if isinstance(val[0], dict):
for item in val:
proto_item = getattr(proto, name).add()
for k, v in six.iteritems(item):
assign_proto(proto_item, k, v)
else:
getattr(proto, name).extend(val)
elif isinstance(val, dict):
for k, v in six.iteritems(val):
assign_proto(getattr(proto, name), k, v)
else:
setattr(proto, name, val)
class Top(object):
"""A Top specifies a single output blob (which could be one of several
produced by a layer.)"""
def __init__(self, fn, n):
self.fn = fn
self.n = n
def to_proto(self):
"""Generate a NetParameter that contains all layers needed to compute
this top."""
return to_proto(self)
def _to_proto(self, layers, names, autonames):
return self.fn._to_proto(layers, names, autonames)
class Function(object):
"""A Function specifies a layer, its parameters, and its inputs (which
are Tops from other layers)."""
def __init__(self, type_name, inputs, params):
self.type_name = type_name
self.inputs = inputs
self.params = params
self.ntop = self.params.get('ntop', 1)
# use del to make sure kwargs are not double-processed as layer params
if 'ntop' in self.params:
del self.params['ntop']
self.in_place = self.params.get('in_place', False)
if 'in_place' in self.params:
del self.params['in_place']
self.tops = tuple(Top(self, n) for n in range(self.ntop))
def _get_name(self, names, autonames):
if self not in names and self.ntop > 0:
names[self] = self._get_top_name(self.tops[0], names, autonames)
elif self not in names:
autonames[self.type_name] += 1
names[self] = self.type_name + str(autonames[self.type_name])
return names[self]
def _get_top_name(self, top, names, autonames):
if top not in names:
autonames[top.fn.type_name] += 1
names[top] = top.fn.type_name + str(autonames[top.fn.type_name])
return names[top]
def _to_proto(self, layers, names, autonames):
if self in layers:
return
bottom_names = []
for inp in self.inputs:
inp._to_proto(layers, names, autonames)
bottom_names.append(layers[inp.fn].top[inp.n])
layer = caffe_pb2.LayerParameter()
layer.type = self.type_name
layer.bottom.extend(bottom_names)
if self.in_place:
layer.top.extend(layer.bottom)
else:
for top in self.tops:
layer.top.append(self._get_top_name(top, names, autonames))
layer.name = self._get_name(names, autonames)
for k, v in six.iteritems(self.params):
# special case to handle generic *params
if k.endswith('param'):
assign_proto(layer, k, v)
else:
try:
assign_proto(getattr(layer,
_param_names[self.type_name] + '_param'), k, v)
except (AttributeError, KeyError):
assign_proto(layer, k, v)
layers[self] = layer
class NetSpec(object):
"""A NetSpec contains a set of Tops (assigned directly as attributes).
Calling NetSpec.to_proto generates a NetParameter containing all of the
layers needed to produce all of the assigned Tops, using the assigned
names."""
def __init__(self):
super(NetSpec, self).__setattr__('tops', OrderedDict())
def __setattr__(self, name, value):
self.tops[name] = value
def __getattr__(self, name):
return self.tops[name]
def __setitem__(self, key, value):
self.__setattr__(key, value)
def __getitem__(self, item):
return self.__getattr__(item)
def to_proto(self):
names = {v: k for k, v in six.iteritems(self.tops)}
autonames = Counter()
layers = OrderedDict()
for name, top in six.iteritems(self.tops):
top._to_proto(layers, names, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net
class Layers(object):
"""A Layers object is a pseudo-module which generates functions that specify
layers; e.g., Layers().Convolution(bottom, kernel_size=3) will produce a Top
specifying a 3x3 convolution applied to bottom."""
def __getattr__(self, name):
def layer_fn(*args, **kwargs):
fn = Function(name, args, kwargs)
if fn.ntop == 0:
return fn
elif fn.ntop == 1:
return fn.tops[0]
else:
return fn.tops
return layer_fn
class Parameters(object):
"""A Parameters object is a pseudo-module which generates constants used
in layer parameters; e.g., Parameters().Pooling.MAX is the value used
to specify max pooling."""
def __getattr__(self, name):
class Param:
def __getattr__(self, param_name):
return getattr(getattr(caffe_pb2, name + 'Parameter'), param_name)
return Param()
_param_names = param_name_dict()
layers = Layers()
params = Parameters()
| 8,048 | 34.45815 | 88 | py |
ADaPTION | ADaPTION-master/python/caffe/classifier.py | #!/usr/bin/env python
"""
Classifier is an image classifier specialization of Net.
"""
import numpy as np
import caffe
class Classifier(caffe.Net):
"""
Classifier extends Net for image class prediction
by scaling, center cropping, or oversampling.
Parameters
----------
image_dims : dimensions to scale input for cropping/sampling.
Default is to scale to net input size for whole-image crop.
mean, input_scale, raw_scale, channel_swap: params for
preprocessing options.
"""
def __init__(self, model_file, pretrained_file, image_dims=None,
mean=None, input_scale=None, raw_scale=None,
channel_swap=None):
caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST)
# configure pre-processing
in_ = self.inputs[0]
self.transformer = caffe.io.Transformer(
{in_: self.blobs[in_].data.shape})
self.transformer.set_transpose(in_, (2, 0, 1))
if mean is not None:
self.transformer.set_mean(in_, mean)
if input_scale is not None:
self.transformer.set_input_scale(in_, input_scale)
if raw_scale is not None:
self.transformer.set_raw_scale(in_, raw_scale)
if channel_swap is not None:
self.transformer.set_channel_swap(in_, channel_swap)
self.crop_dims = np.array(self.blobs[in_].data.shape[2:])
if not image_dims:
image_dims = self.crop_dims
self.image_dims = image_dims
def predict(self, inputs, oversample=True):
"""
Predict classification probabilities of inputs.
Parameters
----------
inputs : iterable of (H x W x K) input ndarrays.
oversample : boolean
average predictions across center, corners, and mirrors
when True (default). Center-only prediction when False.
Returns
-------
predictions: (N x C) ndarray of class probabilities for N images and C
classes.
"""
# Scale to standardize input dimensions.
input_ = np.zeros((len(inputs),
self.image_dims[0],
self.image_dims[1],
inputs[0].shape[2]),
dtype=np.float32)
for ix, in_ in enumerate(inputs):
input_[ix] = caffe.io.resize_image(in_, self.image_dims)
if oversample:
# Generate center, corner, and mirrored crops.
input_ = caffe.io.oversample(input_, self.crop_dims)
else:
# Take center crop.
center = np.array(self.image_dims) / 2.0
crop = np.tile(center, (1, 2))[0] + np.concatenate([
-self.crop_dims / 2.0,
self.crop_dims / 2.0
])
crop = crop.astype(int)
input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :]
# Classify
caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]],
dtype=np.float32)
for ix, in_ in enumerate(input_):
caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_)
out = self.forward_all(**{self.inputs[0]: caffe_in})
predictions = out[self.outputs[0]]
# For oversampling, average predictions across crops.
if oversample:
predictions = predictions.reshape((len(predictions) / 10, 10, -1))
predictions = predictions.mean(1)
return predictions
| 3,537 | 34.737374 | 78 | py |
ADaPTION | ADaPTION-master/python/caffe/coord_map.py | """
Determine spatial relationships between layers to relate their coordinates.
Coordinates are mapped from input-to-output (forward), but can
be mapped output-to-input (backward) by the inverse mapping too.
This helps crop and align feature maps among other uses.
"""
from __future__ import division
import numpy as np
from caffe import layers as L
PASS_THROUGH_LAYERS = ['AbsVal', 'BatchNorm', 'Bias', 'BNLL', 'Dropout',
'Eltwise', 'ELU', 'Log', 'LRN', 'Exp', 'MVN', 'Power',
'ReLU', 'PReLU', 'Scale', 'Sigmoid', 'Split', 'TanH',
'Threshold']
def conv_params(fn):
"""
Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation.
Implementation detail: Convolution, Deconvolution, and Im2col layers
define these in the convolution_param message, while Pooling has its
own fields in pooling_param. This method deals with these details to
extract canonical parameters.
"""
params = fn.params.get('convolution_param', fn.params)
axis = params.get('axis', 1)
ks = np.array(params['kernel_size'], ndmin=1)
dilation = np.array(params.get('dilation', 1), ndmin=1)
assert len({'pad_h', 'pad_w', 'kernel_h', 'kernel_w', 'stride_h',
'stride_w'} & set(fn.params)) == 0, \
'cropping does not support legacy _h/_w params'
return (axis, np.array(params.get('stride', 1), ndmin=1),
(ks - 1) * dilation + 1,
np.array(params.get('pad', 0), ndmin=1))
def crop_params(fn):
"""
Extract the crop layer parameters with defaults.
"""
params = fn.params.get('crop_param', fn.params)
axis = params.get('axis', 2) # default to spatial crop for N, C, H, W
offset = np.array(params.get('offset', 0), ndmin=1)
return (axis, offset)
class UndefinedMapException(Exception):
"""
Exception raised for layers that do not have a defined coordinate mapping.
"""
pass
def coord_map(fn):
"""
Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords.
"""
if fn.type_name in ['Convolution', 'Pooling', 'Im2col']:
axis, stride, ks, pad = conv_params(fn)
return axis, 1 / stride, (pad - (ks - 1) / 2) / stride
elif fn.type_name == 'Deconvolution':
axis, stride, ks, pad = conv_params(fn)
return axis, stride, (ks - 1) / 2 - pad
elif fn.type_name in PASS_THROUGH_LAYERS:
return None, 1, 0
elif fn.type_name == 'Crop':
axis, offset = crop_params(fn)
axis -= 1 # -1 for last non-coordinate dim.
return axis, 1, - offset
else:
raise UndefinedMapException
class AxisMismatchException(Exception):
"""
Exception raised for mappings with incompatible axes.
"""
pass
def compose(base_map, next_map):
"""
Compose a base coord map with scale a1, shift b1 with a further coord map
with scale a2, shift b2. The scales multiply and the further shift, b2,
is scaled by base coord scale a1.
"""
ax1, a1, b1 = base_map
ax2, a2, b2 = next_map
if ax1 is None:
ax = ax2
elif ax2 is None or ax1 == ax2:
ax = ax1
else:
raise AxisMismatchException
return ax, a1 * a2, a1 * b2 + b1
def inverse(coord_map):
"""
Invert a coord map by de-scaling and un-shifting;
this gives the backward mapping for the gradient.
"""
ax, a, b = coord_map
return ax, 1 / a, -b / a
def coord_map_from_to(top_from, top_to):
"""
Determine the coordinate mapping betweeen a top (from) and a top (to).
Walk the graph to find a common ancestor while composing the coord maps for
from and to until they meet. As a last step the from map is inverted.
"""
# We need to find a common ancestor of top_from and top_to.
# We'll assume that all ancestors are equivalent here (otherwise the graph
# is an inconsistent state (which we could improve this to check for)).
# For now use a brute-force algorithm.
def collect_bottoms(top):
"""
Collect the bottoms to walk for the coordinate mapping.
The general rule is that all the bottoms of a layer can be mapped, as
most layers have the same coordinate mapping for each bottom.
Crop layer is a notable exception. Only the first/cropped bottom is
mappable; the second/dimensions bottom is excluded from the walk.
"""
bottoms = top.fn.inputs
if top.fn.type_name == 'Crop':
bottoms = bottoms[:1]
return bottoms
# walk back from top_from, keeping the coord map as we go
from_maps = {top_from: (None, 1, 0)}
frontier = {top_from}
while frontier:
top = frontier.pop()
try:
bottoms = collect_bottoms(top)
for bottom in bottoms:
from_maps[bottom] = compose(from_maps[top], coord_map(top.fn))
frontier.add(bottom)
except UndefinedMapException:
pass
# now walk back from top_to until we hit a common blob
to_maps = {top_to: (None, 1, 0)}
frontier = {top_to}
while frontier:
top = frontier.pop()
if top in from_maps:
return compose(to_maps[top], inverse(from_maps[top]))
try:
bottoms = collect_bottoms(top)
for bottom in bottoms:
to_maps[bottom] = compose(to_maps[top], coord_map(top.fn))
frontier.add(bottom)
except UndefinedMapException:
continue
# if we got here, we did not find a blob in common
raise RuntimeError('Could not compute map between tops; are they '
'connected by spatial layers?')
def crop(top_from, top_to):
"""
Define a Crop layer to crop a top (from) to another top (to) by
determining the coordinate mapping between the two and net spec'ing
the axis and shift parameters of the crop.
"""
ax, a, b = coord_map_from_to(top_from, top_to)
assert (a == 1).all(), 'scale mismatch on crop (a = {})'.format(a)
assert (b <= 0).all(), 'cannot crop negative offset (b = {})'.format(b)
assert (np.round(b) == b).all(), 'cannot crop noninteger offset ' \
'(b = {})'.format(b)
return L.Crop(top_from, top_to,
crop_param=dict(axis=ax + 1, # +1 for first cropping dim.
offset=list(-np.round(b).astype(int))))
| 6,721 | 35.139785 | 79 | py |
ADaPTION | ADaPTION-master/python/caffe/detector.py | #!/usr/bin/env python
"""
Do windowed detection by classifying a number of images/crops at once,
optionally using the selective search window proposal method.
This implementation follows ideas in
Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra Malik.
Rich feature hierarchies for accurate object detection and semantic
segmentation.
http://arxiv.org/abs/1311.2524
The selective_search_ijcv_with_python code required for the selective search
proposal mode is available at
https://github.com/sergeyk/selective_search_ijcv_with_python
"""
import numpy as np
import os
import caffe
class Detector(caffe.Net):
"""
Detector extends Net for windowed detection by a list of crops or
selective search proposals.
Parameters
----------
mean, input_scale, raw_scale, channel_swap : params for preprocessing
options.
context_pad : amount of surrounding context to take s.t. a `context_pad`
sized border of pixels in the network input image is context, as in
R-CNN feature extraction.
"""
def __init__(self, model_file, pretrained_file, mean=None,
input_scale=None, raw_scale=None, channel_swap=None,
context_pad=None):
caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST)
# configure pre-processing
in_ = self.inputs[0]
self.transformer = caffe.io.Transformer(
{in_: self.blobs[in_].data.shape})
self.transformer.set_transpose(in_, (2, 0, 1))
if mean is not None:
self.transformer.set_mean(in_, mean)
if input_scale is not None:
self.transformer.set_input_scale(in_, input_scale)
if raw_scale is not None:
self.transformer.set_raw_scale(in_, raw_scale)
if channel_swap is not None:
self.transformer.set_channel_swap(in_, channel_swap)
self.configure_crop(context_pad)
def detect_windows(self, images_windows):
"""
Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts.
"""
# Extract windows.
window_inputs = []
for image_fname, windows in images_windows:
image = caffe.io.load_image(image_fname).astype(np.float32)
for window in windows:
window_inputs.append(self.crop(image, window))
# Run through the net (warping windows to input dimensions).
in_ = self.inputs[0]
caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2])
+ self.blobs[in_].data.shape[2:],
dtype=np.float32)
for ix, window_in in enumerate(window_inputs):
caffe_in[ix] = self.transformer.preprocess(in_, window_in)
out = self.forward_all(**{in_: caffe_in})
predictions = out[self.outputs[0]]
# Package predictions with images and windows.
detections = []
ix = 0
for image_fname, windows in images_windows:
for window in windows:
detections.append({
'window': window,
'prediction': predictions[ix],
'filename': image_fname
})
ix += 1
return detections
def detect_selective_search(self, image_fnames):
"""
Do windowed detection over Selective Search proposals by extracting
the crop and warping to the input dimensions of the net.
Parameters
----------
image_fnames: list
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts.
"""
import selective_search_ijcv_with_python as selective_search
# Make absolute paths so MATLAB can find the files.
image_fnames = [os.path.abspath(f) for f in image_fnames]
windows_list = selective_search.get_windows(
image_fnames,
cmd='selective_search_rcnn'
)
# Run windowed detection on the selective search list.
return self.detect_windows(zip(image_fnames, windows_list))
def crop(self, im, window):
"""
Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration.
Parameters
----------
im: H x W x K image ndarray to crop.
window: bounding box coordinates as ymin, xmin, ymax, xmax.
Returns
-------
crop: cropped window.
"""
# Crop window from the image.
crop = im[window[0]:window[2], window[1]:window[3]]
if self.context_pad:
box = window.copy()
crop_size = self.blobs[self.inputs[0]].width # assumes square
scale = crop_size / (1. * crop_size - self.context_pad * 2)
# Crop a box + surrounding context.
half_h = (box[2] - box[0] + 1) / 2.
half_w = (box[3] - box[1] + 1) / 2.
center = (box[0] + half_h, box[1] + half_w)
scaled_dims = scale * np.array((-half_h, -half_w, half_h, half_w))
box = np.round(np.tile(center, 2) + scaled_dims)
full_h = box[2] - box[0] + 1
full_w = box[3] - box[1] + 1
scale_h = crop_size / full_h
scale_w = crop_size / full_w
pad_y = round(max(0, -box[0]) * scale_h) # amount out-of-bounds
pad_x = round(max(0, -box[1]) * scale_w)
# Clip box to image dimensions.
im_h, im_w = im.shape[:2]
box = np.clip(box, 0., [im_h, im_w, im_h, im_w])
clip_h = box[2] - box[0] + 1
clip_w = box[3] - box[1] + 1
assert(clip_h > 0 and clip_w > 0)
crop_h = round(clip_h * scale_h)
crop_w = round(clip_w * scale_w)
if pad_y + crop_h > crop_size:
crop_h = crop_size - pad_y
if pad_x + crop_w > crop_size:
crop_w = crop_size - pad_x
# collect with context padding and place in input
# with mean padding
context_crop = im[box[0]:box[2], box[1]:box[3]]
context_crop = caffe.io.resize_image(context_crop, (crop_h, crop_w))
crop = np.ones(self.crop_dims, dtype=np.float32) * self.crop_mean
crop[pad_y:(pad_y + crop_h), pad_x:(pad_x + crop_w)] = context_crop
return crop
def configure_crop(self, context_pad):
"""
Configure crop dimensions and amount of context for cropping.
If context is included, make the special input mean for context padding.
Parameters
----------
context_pad : amount of context for cropping.
"""
# crop dimensions
in_ = self.inputs[0]
tpose = self.transformer.transpose[in_]
inv_tpose = [tpose[t] for t in tpose]
self.crop_dims = np.array(self.blobs[in_].data.shape[1:])[inv_tpose]
#.transpose(inv_tpose)
# context padding
self.context_pad = context_pad
if self.context_pad:
in_ = self.inputs[0]
transpose = self.transformer.transpose.get(in_)
channel_order = self.transformer.channel_swap.get(in_)
raw_scale = self.transformer.raw_scale.get(in_)
# Padding context crops needs the mean in unprocessed input space.
mean = self.transformer.mean.get(in_)
if mean is not None:
inv_transpose = [transpose[t] for t in transpose]
crop_mean = mean.copy().transpose(inv_transpose)
if channel_order is not None:
channel_order_inverse = [channel_order.index(i)
for i in range(crop_mean.shape[2])]
crop_mean = crop_mean[:, :, channel_order_inverse]
if raw_scale is not None:
crop_mean /= raw_scale
self.crop_mean = crop_mean
else:
self.crop_mean = np.zeros(self.crop_dims, dtype=np.float32)
| 8,541 | 38.364055 | 80 | py |
ADaPTION | ADaPTION-master/python/caffe/__init__.py | from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver
from ._caffe import set_mode_cpu, set_mode_gpu, set_device, Layer, get_solver, layer_type_list, set_random_seed
from ._caffe import __version__
from .proto.caffe_pb2 import TRAIN, TEST
from .classifier import Classifier
from .detector import Detector
from . import io
from .net_spec import layers, params, NetSpec, to_proto
| 434 | 47.333333 | 111 | py |
ADaPTION | ADaPTION-master/python/caffe/pycaffe.py | """
Wrap the internal caffe C++ module (_caffe.so) with a clean, Pythonic
interface.
"""
from collections import OrderedDict
try:
from itertools import izip_longest
except:
from itertools import zip_longest as izip_longest
import numpy as np
from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, \
RMSPropSolver, AdaDeltaSolver, AdamSolver
import caffe.io
import six
# We directly update methods from Net here (rather than using composition or
# inheritance) so that nets created by caffe (e.g., by SGDSolver) will
# automatically have the improved interface.
@property
def _Net_blobs(self):
"""
An OrderedDict (bottom to top, i.e., input to output) of network
blobs indexed by name
"""
if not hasattr(self, '_blobs_dict'):
self._blobs_dict = OrderedDict(zip(self._blob_names, self._blobs))
return self._blobs_dict
@property
def _Net_blob_loss_weights(self):
"""
An OrderedDict (bottom to top, i.e., input to output) of network
blob loss weights indexed by name
"""
if not hasattr(self, '_blobs_loss_weights_dict'):
self._blob_loss_weights_dict = OrderedDict(zip(self._blob_names,
self._blob_loss_weights))
return self._blob_loss_weights_dict
@property
def _Net_params(self):
"""
An OrderedDict (bottom to top, i.e., input to output) of network
parameters indexed by name; each is a list of multiple blobs (e.g.,
weights and biases)
"""
if not hasattr(self, '_params_dict'):
self._params_dict = OrderedDict([(name, lr.blobs)
for name, lr in zip(
self._layer_names, self.layers)
if len(lr.blobs) > 0])
return self._params_dict
@property
def _Net_inputs(self):
if not hasattr(self, '_input_list'):
keys = list(self.blobs.keys())
self._input_list = [keys[i] for i in self._inputs]
return self._input_list
@property
def _Net_outputs(self):
if not hasattr(self, '_output_list'):
keys = list(self.blobs.keys())
self._output_list = [keys[i] for i in self._outputs]
return self._output_list
def _Net_forward(self, blobs=None, start=None, end=None, **kwargs):
"""
Forward pass: prepare inputs and run the net forward.
Parameters
----------
blobs : list of blobs to return in addition to output blobs.
kwargs : Keys are input blob names and values are blob ndarrays.
For formatting inputs for Caffe, see Net.preprocess().
If None, input is taken from data layers.
start : optional name of layer at which to begin the forward pass
end : optional name of layer at which to finish the forward pass
(inclusive)
Returns
-------
outs : {blob name: blob ndarray} dict.
"""
if blobs is None:
blobs = []
if start is not None:
start_ind = list(self._layer_names).index(start)
else:
start_ind = 0
if end is not None:
end_ind = list(self._layer_names).index(end)
outputs = set([end] + blobs)
else:
end_ind = len(self.layers) - 1
outputs = set(self.outputs + blobs)
if kwargs:
if set(kwargs.keys()) != set(self.inputs):
raise Exception('Input blob arguments do not match net inputs.')
# Set input according to defined shapes and make arrays single and
# C-contiguous as Caffe expects.
for in_, blob in six.iteritems(kwargs):
if blob.shape[0] != self.blobs[in_].shape[0]:
raise Exception('Input is not batch sized')
self.blobs[in_].data[...] = blob
self._forward(start_ind, end_ind)
# Unpack blobs to extract
return {out: self.blobs[out].data for out in outputs}
def _Net_backward(self, diffs=None, start=None, end=None, **kwargs):
"""
Backward pass: prepare diffs and run the net backward.
Parameters
----------
diffs : list of diffs to return in addition to bottom diffs.
kwargs : Keys are output blob names and values are diff ndarrays.
If None, top diffs are taken from forward loss.
start : optional name of layer at which to begin the backward pass
end : optional name of layer at which to finish the backward pass
(inclusive)
Returns
-------
outs: {blob name: diff ndarray} dict.
"""
if diffs is None:
diffs = []
if start is not None:
start_ind = list(self._layer_names).index(start)
else:
start_ind = len(self.layers) - 1
if end is not None:
end_ind = list(self._layer_names).index(end)
outputs = set([end] + diffs)
else:
end_ind = 0
outputs = set(self.inputs + diffs)
if kwargs:
if set(kwargs.keys()) != set(self.outputs):
raise Exception('Top diff arguments do not match net outputs.')
# Set top diffs according to defined shapes and make arrays single and
# C-contiguous as Caffe expects.
for top, diff in six.iteritems(kwargs):
if diff.shape[0] != self.blobs[top].shape[0]:
raise Exception('Diff is not batch sized')
self.blobs[top].diff[...] = diff
self._backward(start_ind, end_ind)
# Unpack diffs to extract
return {out: self.blobs[out].diff for out in outputs}
def _Net_forward_all(self, blobs=None, **kwargs):
"""
Run net forward in batches.
Parameters
----------
blobs : list of blobs to extract as in forward()
kwargs : Keys are input blob names and values are blob ndarrays.
Refer to forward().
Returns
-------
all_outs : {blob name: list of blobs} dict.
"""
# Collect outputs from batches
all_outs = {out: [] for out in set(self.outputs + (blobs or []))}
for batch in self._batch(kwargs):
outs = self.forward(blobs=blobs, **batch)
for out, out_blob in six.iteritems(outs):
all_outs[out].extend(out_blob.copy())
# Package in ndarray.
for out in all_outs:
all_outs[out] = np.asarray(all_outs[out])
# Discard padding.
pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs)))
if pad:
for out in all_outs:
all_outs[out] = all_outs[out][:-pad]
return all_outs
def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs):
"""
Run net forward + backward in batches.
Parameters
----------
blobs: list of blobs to extract as in forward()
diffs: list of diffs to extract as in backward()
kwargs: Keys are input (for forward) and output (for backward) blob names
and values are ndarrays. Refer to forward() and backward().
Prefilled variants are called for lack of input or output blobs.
Returns
-------
all_blobs: {blob name: blob ndarray} dict.
all_diffs: {blob name: diff ndarray} dict.
"""
# Batch blobs and diffs.
all_outs = {out: [] for out in set(self.outputs + (blobs or []))}
all_diffs = {diff: [] for diff in set(self.inputs + (diffs or []))}
forward_batches = self._batch({in_: kwargs[in_]
for in_ in self.inputs if in_ in kwargs})
backward_batches = self._batch({out: kwargs[out]
for out in self.outputs if out in kwargs})
# Collect outputs from batches (and heed lack of forward/backward batches).
for fb, bb in izip_longest(forward_batches, backward_batches, fillvalue={}):
batch_blobs = self.forward(blobs=blobs, **fb)
batch_diffs = self.backward(diffs=diffs, **bb)
for out, out_blobs in six.iteritems(batch_blobs):
all_outs[out].extend(out_blobs.copy())
for diff, out_diffs in six.iteritems(batch_diffs):
all_diffs[diff].extend(out_diffs.copy())
# Package in ndarray.
for out, diff in zip(all_outs, all_diffs):
all_outs[out] = np.asarray(all_outs[out])
all_diffs[diff] = np.asarray(all_diffs[diff])
# Discard padding at the end and package in ndarray.
pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs)))
if pad:
for out, diff in zip(all_outs, all_diffs):
all_outs[out] = all_outs[out][:-pad]
all_diffs[diff] = all_diffs[diff][:-pad]
return all_outs, all_diffs
def _Net_set_input_arrays(self, data, labels):
"""
Set input arrays of the in-memory MemoryDataLayer.
(Note: this is only for networks declared with the memory data layer.)
"""
if labels.ndim == 1:
labels = np.ascontiguousarray(labels[:, np.newaxis, np.newaxis,
np.newaxis])
return self._set_input_arrays(data, labels)
def _Net_batch(self, blobs):
"""
Batch blob lists according to net's batch size.
Parameters
----------
blobs: Keys blob names and values are lists of blobs (of any length).
Naturally, all the lists should have the same length.
Yields
------
batch: {blob name: list of blobs} dict for a single batch.
"""
num = len(six.next(six.itervalues(blobs)))
batch_size = six.next(six.itervalues(self.blobs)).shape[0]
remainder = num % batch_size
num_batches = num // batch_size
# Yield full batches.
for b in range(num_batches):
i = b * batch_size
yield {name: blobs[name][i:i + batch_size] for name in blobs}
# Yield last padded batch, if any.
if remainder > 0:
padded_batch = {}
for name in blobs:
padding = np.zeros((batch_size - remainder,)
+ blobs[name].shape[1:])
padded_batch[name] = np.concatenate([blobs[name][-remainder:],
padding])
yield padded_batch
def _Net_get_id_name(func, field):
"""
Generic property that maps func to the layer names into an OrderedDict.
Used for top_names and bottom_names.
Parameters
----------
func: function id -> [id]
field: implementation field name (cache)
Returns
------
A one-parameter function that can be set as a property.
"""
@property
def get_id_name(self):
if not hasattr(self, field):
id_to_name = list(self.blobs)
res = OrderedDict([(self._layer_names[i],
[id_to_name[j] for j in func(self, i)])
for i in range(len(self.layers))])
setattr(self, field, res)
return getattr(self, field)
return get_id_name
# Attach methods to Net.
Net.blobs = _Net_blobs
Net.blob_loss_weights = _Net_blob_loss_weights
Net.params = _Net_params
Net.forward = _Net_forward
Net.backward = _Net_backward
Net.forward_all = _Net_forward_all
Net.forward_backward_all = _Net_forward_backward_all
Net.set_input_arrays = _Net_set_input_arrays
Net._batch = _Net_batch
Net.inputs = _Net_inputs
Net.outputs = _Net_outputs
Net.top_names = _Net_get_id_name(Net._top_ids, "_top_names")
Net.bottom_names = _Net_get_id_name(Net._bottom_ids, "_bottom_names")
| 11,243 | 32.564179 | 89 | py |
ADaPTION | ADaPTION-master/python/caffe/draw.py | """
Caffe network visualization: draw the NetParameter protobuffer.
.. note::
This requires pydot>=1.0.2, which is not included in requirements.txt since
it requires graphviz and other prerequisites outside the scope of the
Caffe.
"""
from caffe.proto import caffe_pb2
"""
pydot is not supported under python 3 and pydot2 doesn't work properly.
pydotplus works nicely (pip install pydotplus)
"""
try:
# Try to load pydotplus
import pydotplus as pydot
except ImportError:
import pydot
# Internal layer and blob styles.
LAYER_STYLE_DEFAULT = {'shape': 'record',
'fillcolor': '#6495ED',
'style': 'filled'}
NEURON_LAYER_STYLE = {'shape': 'record',
'fillcolor': '#90EE90',
'style': 'filled'}
BLOB_STYLE = {'shape': 'octagon',
'fillcolor': '#E0E0E0',
'style': 'filled'}
def get_pooling_types_dict():
"""Get dictionary mapping pooling type number to type name
"""
desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR
d = {}
for k, v in desc.values_by_name.items():
d[v.number] = k
return d
def get_edge_label(layer):
"""Define edge label based on layer type.
"""
if layer.type == 'Data':
edge_label = 'Batch ' + str(layer.data_param.batch_size)
elif layer.type == 'Convolution' or layer.type == 'Deconvolution':
edge_label = str(layer.convolution_param.num_output)
elif layer.type == 'InnerProduct':
edge_label = str(layer.inner_product_param.num_output)
else:
edge_label = '""'
return edge_label
def get_layer_label(layer, rankdir):
"""Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer
"""
if rankdir in ('TB', 'BT'):
# If graph orientation is vertical, horizontal space is free and
# vertical space is not; separate words with spaces
separator = ' '
else:
# If graph orientation is horizontal, vertical space is free and
# horizontal space is not; separate words with newlines
separator = '\\n'
if layer.type == 'Convolution' or layer.type == 'Deconvolution':
# Outer double quotes needed or else colon characters don't parse
# properly
node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
layer.type,
separator,
layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size._values) else 1,
separator,
layer.convolution_param.stride[0] if len(layer.convolution_param.stride._values) else 1,
separator,
layer.convolution_param.pad[0] if len(layer.convolution_param.pad._values) else 0)
elif layer.type == 'Pooling':
pooling_types_dict = get_pooling_types_dict()
node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
pooling_types_dict[layer.pooling_param.pool],
layer.type,
separator,
layer.pooling_param.kernel_size,
separator,
layer.pooling_param.stride,
separator,
layer.pooling_param.pad)
else:
node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type)
return node_label
def choose_color_by_layertype(layertype):
"""Define colors for nodes based on the layer type.
"""
color = '#6495ED' # Default
if layertype == 'Convolution' or layertype == 'Deconvolution':
color = '#FF5050'
elif layertype == 'Pooling':
color = '#FF9900'
elif layertype == 'InnerProduct':
color = '#CC33FF'
return color
def get_pydot_graph(caffe_net, rankdir, label_edges=True, phase=None):
"""Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_net : object
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
label_edges : boolean, optional
Label the edges (default is True).
phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional
Include layers from this network phase. If None, include all layers.
(the default is None)
Returns
-------
pydot graph object
"""
pydot_graph = pydot.Dot(caffe_net.name if caffe_net.name else 'Net',
graph_type='digraph',
rankdir=rankdir)
pydot_nodes = {}
pydot_edges = []
for layer in caffe_net.layer:
if phase is not None:
included = False
if len(layer.include) == 0:
included = True
if len(layer.include) > 0 and len(layer.exclude) > 0:
raise ValueError('layer ' + layer.name + ' has both include '
'and exclude specified.')
for layer_phase in layer.include:
included = included or layer_phase.phase == phase
for layer_phase in layer.exclude:
included = included and not layer_phase.phase == phase
if not included:
continue
node_label = get_layer_label(layer, rankdir)
node_name = "%s_%s" % (layer.name, layer.type)
if (len(layer.bottom) == 1 and len(layer.top) == 1 and
layer.bottom[0] == layer.top[0]):
# We have an in-place neuron layer.
pydot_nodes[node_name] = pydot.Node(node_label,
**NEURON_LAYER_STYLE)
else:
layer_style = LAYER_STYLE_DEFAULT
layer_style['fillcolor'] = choose_color_by_layertype(layer.type)
pydot_nodes[node_name] = pydot.Node(node_label, **layer_style)
for bottom_blob in layer.bottom:
pydot_nodes[bottom_blob + '_blob'] = pydot.Node('%s' % bottom_blob,
**BLOB_STYLE)
edge_label = '""'
pydot_edges.append({'src': bottom_blob + '_blob',
'dst': node_name,
'label': edge_label})
for top_blob in layer.top:
pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob))
if label_edges:
edge_label = get_edge_label(layer)
else:
edge_label = '""'
pydot_edges.append({'src': node_name,
'dst': top_blob + '_blob',
'label': edge_label})
# Now, add the nodes and edges to the graph.
for node in pydot_nodes.values():
pydot_graph.add_node(node)
for edge in pydot_edges:
pydot_graph.add_edge(
pydot.Edge(pydot_nodes[edge['src']],
pydot_nodes[edge['dst']],
label=edge['label']))
return pydot_graph
def draw_net(caffe_net, rankdir, ext='png', phase=None):
"""Draws a caffe net and returns the image string encoded using the given
extension.
Parameters
----------
caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer.
ext : string, optional
The image extension (the default is 'png').
phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional
Include layers from this network phase. If None, include all layers.
(the default is None)
Returns
-------
string :
Postscript representation of the graph.
"""
return get_pydot_graph(caffe_net, rankdir, phase=phase).create(format=ext)
def draw_net_to_file(caffe_net, filename, rankdir='LR', phase=None):
"""Draws a caffe net, and saves it to file using the format given as the
file extension. Use '.raw' to output raw text that you can manually feed
to graphviz to draw graphs.
Parameters
----------
caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer.
filename : string
The path to a file where the networks visualization will be stored.
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional
Include layers from this network phase. If None, include all layers.
(the default is None)
"""
ext = filename[filename.rfind('.')+1:]
with open(filename, 'wb') as fid:
fid.write(draw_net(caffe_net, rankdir, ext, phase))
| 8,813 | 34.97551 | 120 | py |
ADaPTION | ADaPTION-master/python/caffe/io.py | import numpy as np
import skimage.io
from scipy.ndimage import zoom
from skimage.transform import resize
try:
# Python3 will most likely not be able to load protobuf
from caffe.proto import caffe_pb2
except:
import sys
if sys.version_info >= (3, 0):
print("Failed to include caffe_pb2, things might go wrong!")
else:
raise
## proto / datum / ndarray conversion
def blobproto_to_array(blob, return_diff=False):
"""
Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff.
"""
# Read the data into an array
if return_diff:
data = np.array(blob.diff)
else:
data = np.array(blob.data)
# Reshape the array
if blob.HasField('num') or blob.HasField('channels') or blob.HasField('height') or blob.HasField('width'):
# Use legacy 4D shape
return data.reshape(blob.num, blob.channels, blob.height, blob.width)
else:
return data.reshape(blob.shape.dim)
def array_to_blobproto(arr, diff=None):
"""Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check.
"""
blob = caffe_pb2.BlobProto()
blob.shape.dim.extend(arr.shape)
blob.data.extend(arr.astype(float).flat)
if diff is not None:
blob.diff.extend(diff.astype(float).flat)
return blob
def arraylist_to_blobprotovector_str(arraylist):
"""Converts a list of arrays to a serialized blobprotovec, which could be
then passed to a network for processing.
"""
vec = caffe_pb2.BlobProtoVector()
vec.blobs.extend([array_to_blobproto(arr) for arr in arraylist])
return vec.SerializeToString()
def blobprotovector_str_to_arraylist(str):
"""Converts a serialized blobprotovec to a list of arrays.
"""
vec = caffe_pb2.BlobProtoVector()
vec.ParseFromString(str)
return [blobproto_to_array(blob) for blob in vec.blobs]
def array_to_datum(arr, label=None):
"""Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format.
"""
if arr.ndim != 3:
raise ValueError('Incorrect array shape.')
datum = caffe_pb2.Datum()
datum.channels, datum.height, datum.width = arr.shape
if arr.dtype == np.uint8:
datum.data = arr.tostring()
else:
datum.float_data.extend(arr.flat)
if label is not None:
datum.label = label
return datum
def datum_to_array(datum):
"""Converts a datum to an array. Note that the label is not returned,
as one can easily get it by calling datum.label.
"""
if len(datum.data):
return np.fromstring(datum.data, dtype=np.uint8).reshape(
datum.channels, datum.height, datum.width)
else:
return np.array(datum.float_data).astype(float).reshape(
datum.channels, datum.height, datum.width)
## Pre-processing
class Transformer:
"""
Transform input for feeding into a Net.
Note: this is mostly for illustrative purposes and it is likely better
to define your own input preprocessing routine for your needs.
Parameters
----------
net : a Net for which the input should be prepared
"""
def __init__(self, inputs):
self.inputs = inputs
self.transpose = {}
self.channel_swap = {}
self.raw_scale = {}
self.mean = {}
self.input_scale = {}
def __check_input(self, in_):
if in_ not in self.inputs:
raise Exception('{} is not one of the net inputs: {}'.format(
in_, self.inputs))
def preprocess(self, in_, data):
"""
Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net
"""
self.__check_input(in_)
caffe_in = data.astype(np.float32, copy=False)
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
in_dims = self.inputs[in_][2:]
if caffe_in.shape[:2] != in_dims:
caffe_in = resize_image(caffe_in, in_dims)
if transpose is not None:
caffe_in = caffe_in.transpose(transpose)
if channel_swap is not None:
caffe_in = caffe_in[channel_swap, :, :]
if raw_scale is not None:
caffe_in *= raw_scale
if mean is not None:
caffe_in -= mean
if input_scale is not None:
caffe_in *= input_scale
return caffe_in
def deprocess(self, in_, data):
"""
Invert Caffe formatting; see preprocess().
"""
self.__check_input(in_)
decaf_in = data.copy().squeeze()
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
if input_scale is not None:
decaf_in /= input_scale
if mean is not None:
decaf_in += mean
if raw_scale is not None:
decaf_in /= raw_scale
if channel_swap is not None:
decaf_in = decaf_in[np.argsort(channel_swap), :, :]
if transpose is not None:
decaf_in = decaf_in.transpose(np.argsort(transpose))
return decaf_in
def set_transpose(self, in_, order):
"""
Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model.
Parameters
----------
in_ : which input to assign this channel order
order : the order to transpose the dimensions
"""
self.__check_input(in_)
if len(order) != len(self.inputs[in_]) - 1:
raise Exception('Transpose order needs to have the same number of '
'dimensions as the input.')
self.transpose[in_] = order
def set_channel_swap(self, in_, order):
"""
Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model.
N.B. this assumes the channels are the first dimension AFTER transpose.
Parameters
----------
in_ : which input to assign this channel order
order : the order to take the channels.
(2,1,0) maps RGB to BGR for example.
"""
self.__check_input(in_)
if len(order) != self.inputs[in_][1]:
raise Exception('Channel swap needs to have the same number of '
'dimensions as the input channels.')
self.channel_swap[in_] = order
def set_raw_scale(self, in_, scale):
"""
Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.raw_scale[in_] = scale
def set_mean(self, in_, mean):
"""
Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable)
"""
self.__check_input(in_)
ms = mean.shape
if mean.ndim == 1:
# broadcast channels
if ms[0] != self.inputs[in_][1]:
raise ValueError('Mean channels incompatible with input.')
mean = mean[:, np.newaxis, np.newaxis]
else:
# elementwise mean
if len(ms) == 2:
ms = (1,) + ms
if len(ms) != 3:
raise ValueError('Mean shape invalid')
if ms != self.inputs[in_][1:]:
raise ValueError('Mean shape incompatible with input shape.')
self.mean[in_] = mean
def set_input_scale(self, in_, scale):
"""
Set the scale of preprocessed inputs s.t. the blob = blob * scale.
N.B. input_scale is done AFTER mean subtraction and other preprocessing
while raw_scale is done BEFORE.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.input_scale[in_] = scale
## Image IO
def load_image(filename, color=True):
"""
Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale.
"""
img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
if img.ndim == 2:
img = img[:, :, np.newaxis]
if color:
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img
def resize_image(im, new_dims, interp_order=1):
"""
Resize an image array with interpolation.
Parameters
----------
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
interp_order : interpolation order, default is linear.
Returns
-------
im : resized ndarray with shape (new_dims[0], new_dims[1], K)
"""
if im.shape[-1] == 1 or im.shape[-1] == 3:
im_min, im_max = im.min(), im.max()
if im_max > im_min:
# skimage is fast but only understands {1,3} channel images
# in [0, 1].
im_std = (im - im_min) / (im_max - im_min)
resized_std = resize(im_std, new_dims, order=interp_order)
resized_im = resized_std * (im_max - im_min) + im_min
else:
# the image is a constant -- avoid divide by 0
ret = np.empty((new_dims[0], new_dims[1], im.shape[-1]),
dtype=np.float32)
ret.fill(im_min)
return ret
else:
# ndimage interpolates anything but more slowly.
scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2]))
resized_im = zoom(im, scale + (1,), order=interp_order)
return resized_im.astype(np.float32)
def oversample(images, crop_dims):
"""
Crop images into the four corners, center, and their mirrored versions.
Parameters
----------
image : iterable of (H x W x K) ndarrays
crop_dims : (height, width) tuple for the crops.
Returns
-------
crops : (10*N x H x W x K) ndarray of crops for number of inputs N.
"""
# Dimensions and center.
im_shape = np.array(images[0].shape)
crop_dims = np.array(crop_dims)
im_center = im_shape[:2] / 2.0
# Make crop coordinates
h_indices = (0, im_shape[0] - crop_dims[0])
w_indices = (0, im_shape[1] - crop_dims[1])
crops_ix = np.empty((5, 4), dtype=int)
curr = 0
for i in h_indices:
for j in w_indices:
crops_ix[curr] = (i, j, i + crop_dims[0], j + crop_dims[1])
curr += 1
crops_ix[4] = np.tile(im_center, (1, 2)) + np.concatenate([
-crop_dims / 2.0,
crop_dims / 2.0
])
crops_ix = np.tile(crops_ix, (2, 1))
# Extract crops
crops = np.empty((10 * len(images), crop_dims[0], crop_dims[1],
im_shape[-1]), dtype=np.float32)
ix = 0
for im in images:
for crop in crops_ix:
crops[ix] = im[crop[0]:crop[2], crop[1]:crop[3], :]
ix += 1
crops[ix-5:ix] = crops[ix-5:ix, :, ::-1, :] # flip for mirrors
return crops
| 12,729 | 32.151042 | 110 | py |
ADaPTION | ADaPTION-master/python/caffe/nullhop/caffe2nullhop.py | '''
TODO: remove pixels from the network file
TODO: support different fixed point representations other than q7.8
TODO: check kernels arrangement
TODO: Currently only for LP version of convolutional layers. Extend also to normal convolution?
To be used only with low precision (LP) version of caffe (caffe_lp/ ), because of the way pooling and ReLU are detected from layers after LPConvolution;
in LP version there is an additional LPActivation layer that caps the activations to max or min representable in the wanted fixed point representation.
'''
'''
PARAMETERS TO MODIFY
'''
modelName = 'roshambo' # set the model name; this is used to find the relative caffe files. Directory has to be specified below
enableCompressedInputImage = False # set true if input image from camera is compressed
debug = False
inputPath = '/home/enrico/Desktop/NullHop/roshambo/params_extraction_/'
outputPath = inputPath
prototxtName = 'NullHop'
caffemodelName = 'NullHop'
'''
'''
'''
The following is the class used to create the network file
'''
#wrapper around layer params. Currently does no special processing or error checking
class layerParam:
allParams = []
@staticmethod
def clearLayerParams():
layerParam.allParams = []
def __init__(self, width=None, height=None, nChIn=None, nChOut=128, kernel_size=3, pooling=True, relu=True, enableCompression=True, padding=0):
#params = {}
self.width = width
self.height = height
self.kernel_size = kernel_size
self.nChIn = nChIn
self.nChOut = nChOut
self.pooling = pooling
self.relu = relu
self.enableCompression = enableCompression
self.padding = padding
i=0
if(len(layerParam.allParams)!=0): # calculate output parameters of the layer based on previous layer. True for all layers except input
prevParam = layerParam.allParams[-1]
divisor = 2 if prevParam.pooling else 1
self.width = (prevParam.width - prevParam.kernel_size + 1 + prevParam.padding*2)/divisor
self.height = (prevParam.height - prevParam.kernel_size + 1 + prevParam.padding*2)/divisor
self.nChIn = prevParam.nChOut
print 'net.blobs[conv_lp_{}].channels: {}'.format(i, net.blobs['conv_lp_1'].channels)
i+=1
if not(self.width):
raise Exception("insufficienct information to get layer width")
if not(self.height):
raise Exception("insufficienct information to get layer height")
if not(self.nChIn):
raise Exception("insufficienct information to get layer input channel number")
print 'width : %d , height : %d , nChIn : %d' % (self.width,self.height,self.nChIn) ###### TODO: include in debug
if not(self.nChIn):
if(len(allParams)==0):
raise Exception("insufficient input feature map information")
prevParam = allParams[-1]
self.nChIn = prevParam.nChOut
self.kernels = np.random.randint(low=-64,high=64,size = (self.nChOut,self.nChIn,kernel_size,kernel_size))
self.biases = np.random.randint(low=-64,high = 64,size = self.nChOut)
layerParam.allParams.append(self)
class network:
def __init__(self,image=None):
self.image = image
def dumpParamList(self,file,p):
file.write(' %d #compression_enabled\n' % (p.enableCompression))
file.write(' %d #kernel_size \n' % (p.kernel_size))
file.write(' %d #num input channels \n' % (p.nChIn))
file.write(' %d #num_input_column \n' % (p.width))
file.write(' %d #num_input_rows \n' % (p.height))
file.write(' %d #num_output_channels \n' % (p.nChOut))
file.write(' %d #pooling_enabled \n' % (p.pooling))
file.write(' %d #relu_enabled \n' % (p.relu))
file.write(' %d #padding \n' % (p.padding))
def dumpArray(self,file,marker,A):
file.write(marker + '\n')
file.write('\n'.join([str(x) for x in A.flatten()]) + '\n')
def dumpNetworkFile(self,path="network"):
file = open(path,'w')
if len(layerParam.allParams) == 0:
raise Exception("empty layer parameters list")
firstLayerParams = layerParam.allParams[0]
if self.image.size != 0:
if(self.image.size != firstLayerParams.nChIn * firstLayerParams.height * firstLayerParams.width):
raise Exception("image size does not match first layer parameters")
else:
self.image = np.random.randint(low=0,high = 32,size = (firstLayerParams.nChIn,firstLayerParams.height,firstLayerParams.width))
file.write(str(len(layerParam.allParams)) + ' # num layers \n')
for (i,p) in enumerate(layerParam.allParams):
self.dumpParamList(file,p)
self.dumpArray(file,"#KERNELS#",p.kernels)
self.dumpArray(file,"#BIASES#",p.biases)
if(i==0):
self.dumpArray(file,"#PIXELS#",self.image)
'''
'''
'''
Set model_def to your caffe model and model_weights to your caffe parameters.
This loads the model and stores the original weights and biases and creates a hash 'convLayers' that maps a layer name to the layer object
'''
import sys
sys.path.append('/home/enrico/caffe_lp/python')
import caffe
import numpy as np
from google.protobuf import text_format
caffe.set_mode_cpu()
model_def = inputPath + prototxtName + '.prototxt'
model_weights = inputPath + caffemodelName + '.caffemodel'
net = caffe.Net(model_def, # defines the structure of the model
model_weights, # contains the trained weights
caffe.TEST) # use test mode (e.g., don't perform dropout)
convLayers = [y for (x,y) in zip(list(net._layer_names),list(net.layers)) if 'conv' in x]
origWeights = [x.blobs[1].data for x in convLayers] # get the low precision version of parameters
origBiases = [x.blobs[3].data for x in convLayers] #
output = net.forward()
model_protobuf = caffe.proto.caffe_pb2.NetParameter()
text_format.Merge(open(model_def).read(), model_protobuf)
model = {'model': (net, model_protobuf)}
'''
img_scale is how you scale your input image pixels. If you scale an image, you will have to scale the biases using the same factor so that the output
of the network is also scaled with this factor and the classification result is unchanged
'''
# TODO: check img_scale factor
#img_scale = 1
#for i in range(net.blobs['data'].data.shape[0]): #Fill the mini-batch
# image = caffe.io.load_image(imgPaths[10+i]) #You will have to replace this with code that loads your image
# net.blobs['data'].data[i,...] = image/img_scale #Fill the input to the network with the scaled image
#for i,x in enumerate(convLayers):
# x.blobs[1].data[...] = origBiases[i]/img_scale #Scale the biases in the network
#Run the network
caffe_model = model['model'][0]
caffe_layers = model['model'][1].layer # caffe_layers doesn't take into account input data layer
allWeights = [x.blobs[1].data for x in convLayers]
allBiases = [x.blobs[3].data for x in convLayers]
convBlobs = [y.data for (x,y) in net.blobs.items() if 'conv' in x] #The feature maps of the convolutional layers
# This prints the ranges of the weights,biases, and activations in all the layers. Use this information to select an appropriate img_scale number
# so that the maximum activation and maximum bias is 256 (Assuming 8 bit integer part in our fixed point representation)
for (x,y,z) in zip(allWeights,allBiases,convBlobs):
print (x.max(),x.min(),y.max(),y.min(),z.max(),z.min())
'''
HERE NETWORK GETS CONSTRUCTED, EXTRACTING INFORMATION FROM .prototxt FILE
# width, height,nChIn : dimensions of input image. Are extracted from 'data' for 1st layer;
# for other layers are calculated from previous layer parameters.
# enableCompression : if NullHop expects input data to be compressed (sparsity maps and pixels) or in normal format (all the pixels).
# default is : (self, width=None, height=None, nChIn=None, nChOut=128, kernel_size=3, pooling=True, relu=True, enableCompression=True, padding=0)
'''
imageW = net.blobs['data'].width
imageH = net.blobs['data'].height
imageCh = net.blobs['data'].channels
if debug == True:
print '--------------------------------------------'
print 'imageW', imageW
print 'imageH', imageH
print 'imageCh', imageCh
print '--------------------------------------------'
conv_idx = 0 # Initialize conv layer number, used to differentiate 1st conv layer: needs explicit imageW, imageH, imageCh;
# Also, enableCompression is set according to initial setting, to decide if input image from sensor is also compressed
# TODO: when find a Conv layer: loop over successive layers until find another conv or FC; if in between there's relu and/or pooling layers,
# activate the respective flags, otherwise default will be 0.
for (layer_num, layer) in enumerate(caffe_layers):
if layer.type == 'LPConvolution':
print 'layer_num', layer_num
pad = caffe_layers[layer_num].pooling_param.pad
print 'padding', pad
# detects if relu is active for the current the convolutional layer
reluVal = 0
next_layer = net.layers[layer_num + 3] # TODO: remove hardcoded value. Offset due to additional act layer for LP training
if next_layer.type == 'ReLU':
reluVal = 1
print 'ReLU', reluVal
# detects if pooling is active for the current the convolutional layer
poolVal=0
second_next_layer = net.layers[layer_num + 4] # net.layers[3].type is another ReLU layer. # TODO: remove hardcoded value
if second_next_layer.type == 'Pooling':
poolVal = 1
print 'pooling', poolVal
if conv_idx == 0: # for first layer only: set image dimension and compression in input image
p=layerParam(width=imageW, height=imageH, nChIn=imageCh, nChOut=caffe_layers[layer_num].convolution_param.num_output, kernel_size=caffe_layers[layer_num].convolution_param.kernel_size[0], relu=reluVal, pooling=poolVal, enableCompression=enableCompressedInputImage, padding=pad)
else: # compression always enabled for layers beyond 1st
p=layerParam(nChOut=caffe_layers[layer_num].convolution_param.num_output, kernel_size=caffe_layers[layer_num].convolution_param.kernel_size[0],relu=reluVal, pooling=poolVal, padding=pad)
conv_idx +=1
if debug == True:
print 'layer_num: {}'.format(layer_num)
#print 'layer: {}'.format(layer)
print 'layer.type: {}'.format(layer.type)
print '----------------------'
'''
Shift parameters to be in NullHop format and generate network file
'''
# TODO: add support for different bit precisions
#Load your scaled weights and biases. You need to scale by 256, i.e. left shift of 8 bits, since we have 8 bits fractional part.
for l,w,b in zip(layerParam.allParams,allWeights,allBiases):
assert(l.kernels.shape == w.shape)
assert(l.biases.shape == b.shape)
l.kernels = np.asarray(w*256,'int32')
l.biases = np.asarray(b*256,'int32')
# Create the network object, load it with the image, then dump to file. The image is scaled by 256, 8 bits fractional part.
nw = network()
#nw.image = net.blobs['data'].data[0]*256
nw.image = np.random.randint(256, size=(64, 64))
nw.dumpNetworkFile(outputPath + 'network_'+ modelName + '.cnn')
| 11,262 | 38.658451 | 290 | py |
ADaPTION | ADaPTION-master/python/caffe/imagenet/cnn_to_NullHop.py | #!/usr/bin/env python
"""
Authors: federico.corradi@inilabs.com, diederikmoeys@live.com
Converts caffe networks into jAER xml format
this script requires command line arguments:
model file -> network.prototxt
weights file -> caffenet.model
OR
if you pass a directory it will look for these files
Example usage:
python python/cnn_to_xml.py caffe_network_directory/ (it looks for .caffemodel and .prototxt)
"""
import numpy as np
import re
import click
from matplotlib import pylab as plt
import numpy as np
import os
import sys
import argparse
import glob
import time
import pandas as pd
from PIL import Image
import scipy
import caffe
import re
from caffe.proto import caffe_pb2
from google.protobuf import text_format
import pydot
import base64
import struct
def get_pooling_types_dict():
"""Get dictionary mapping pooling type number to type name
"""
desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR
d = {}
for k, v in desc.values_by_name.items():
d[v.number] = k
return d
def get_edge_label(layer):
"""Define edge label based on layer type.
"""
if layer.type == 'Data':
edge_label = 'Batch ' + str(layer.data_param.batch_size)
elif layer.type == 'Convolution' or layer.type == 'Deconvolution':
edge_label = str(layer.convolution_param.num_output)
elif layer.type == 'InnerProduct':
edge_label = str(layer.inner_product_param.num_output)
else:
edge_label = '""'
return edge_label
def get_layer_label(layer, rankdir):
"""Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer
"""
if rankdir in ('TB', 'BT'):
# If graph orientation is vertical, horizontal space is free and
# vertical space is not; separate words with spaces
separator = ' '
else:
# If graph orientation is horizontal, vertical space is free and
# horizontal space is not; separate words with newlines
separator = '\\n'
if layer.type == 'Convolution' or layer.type == 'Deconvolution':
# Outer double quotes needed or else colon characters don't parse
# properly
param = layer.convolution_param
node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
layer.type,
separator,
layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size._values) else 1,
separator,
layer.convolution_param.stride[0] if len(layer.convolution_param.stride._values) else 1,
separator,
layer.convolution_param.pad[0] if len(layer.convolution_param.pad._values) else 0)
elif layer.type == 'Pooling':
pooling_types_dict = get_pooling_types_dict()
node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
pooling_types_dict[layer.pooling_param.pool],
layer.type,
separator,
layer.pooling_param.kernel_size,
separator,
layer.pooling_param.stride,
separator,
layer.pooling_param.pad)
else:
node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type)
return node_label
def get_pydot_graph(caffe_net, rankdir, label_edges=True):
"""Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_net : object
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
label_edges : boolean, optional
Label the edges (default is True).
Returns
-------
pydot graph object
"""
pydot_graph = pydot.Dot(caffe_net.name,
graph_type='digraph',
rankdir=rankdir)
pydot_nodes = {}
pydot_edges = []
for layer in caffe_net.layer:
node_label = get_layer_label(layer, rankdir)
node_name = "%s_%s" % (layer.name, layer.type)
if (len(layer.bottom) == 1 and len(layer.top) == 1 and
layer.bottom[0] == layer.top[0]):
# We have an in-place neuron layer.
pydot_nodes[node_name] = pydot.Node(node_label,
**NEURON_LAYER_STYLE)
else:
layer_style = LAYER_STYLE_DEFAULT
layer_style['fillcolor'] = choose_color_by_layertype(layer.type)
pydot_nodes[node_name] = pydot.Node(node_label, **layer_style)
for bottom_blob in layer.bottom:
pydot_nodes[bottom_blob + '_blob'] = pydot.Node('%s' % bottom_blob,
**BLOB_STYLE)
edge_label = '""'
pydot_edges.append({'src': bottom_blob + '_blob',
'dst': node_name,
'label': edge_label})
for top_blob in layer.top:
pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob))
if label_edges:
edge_label = get_edge_label(layer)
else:
edge_label = '""'
pydot_edges.append({'src': node_name,
'dst': top_blob + '_blob',
'label': edge_label})
# Now, add the nodes and edges to the graph.
for node in pydot_nodes.values():
pydot_graph.add_node(node)
for edge in pydot_edges:
pydot_graph.add_edge(
pydot.Edge(pydot_nodes[edge['src']],
pydot_nodes[edge['dst']],
label=edge['label']))
return pydot_graph
@click.command()
@click.argument('dirs', nargs=-1, type=click.Path(exists=True, resolve_path=True))
def main(dirs):
solvers = []
classifiers = []
nets = []
net_files = []
weight_files = []
ip_present = False
for i, log_dir in enumerate(dirs):
print("working on >"+log_dir+"<"+str(i)+">")
#find networks
tmp_files = []
for file in os.listdir(log_dir):
if file.endswith("solver.prototxt"):
#print("solver file >" +file)
solver = caffe_pb2.SolverParameter()
prototxt_solver = log_dir +"/"+file
#print("opening >" +prototxt_solver)
f = open(prototxt_solver, 'r')
text_format.Merge(str(f.read()), solver)
solvers.append(solver)
if file.endswith(".prototxt") and not file.endswith("solver.prototxt") and not file.endswith("train_test.prototxt"):
#print("net file >" +file)
net = caffe_pb2.NetParameter()
prototxt_net = log_dir +"/"+file
f = open(prototxt_net, 'r')
text_format.Merge(f.read(), net)
net_files.append(prototxt_net)
nets.append(net)
if file.endswith(".caffemodel"):
#print("weight file >" +file)
weight_net = log_dir +"/"+file
tmp_files.append(weight_net)
weight_files.append(tmp_files)
# prototxt_net.prototxt, solver (net solver object)
#find last weight snapshot for this net
iter_num = -1
iter_index = 0
for this_f in weight_files[0]:
whole_path = str(this_f)
cutted = whole_path.split(".caffemodel")
#find num iterations
#this assumes that before caffemodel we have filename accordingly to
# _iternum.caffemodel
#for this_c in cutted:
#splitted = this_c.split("_")
#try:
#this_iter = int(splitted[-1])
#if(int(this_iter) == solver.max_iter):
# iter_num = iter_index
#except ValueError:
# continue
#iter_index += 1
print(prototxt_net)
try:
print(weight_files[0][iter_num])
except IndexError:
print("\n#################################")
print("##### Failed to locate weight file, please check your inputs.")
print("#################################\n")
this_classifier = caffe.Classifier(prototxt_net,weight_files[0][iter_num])
classifiers.append(this_classifier)
nets_num = len(nets)
rankdir = "LR"
#loop over all net in folder
for this_net in range(nets_num):
this_classifier = classifiers[this_net] #grub one net
nodes_label = []
nodes_name = []
#header
net_string = ''
# net_string += '<Network>\n'
# net_string += '<name>'+nets[this_net].name+'</name>\n'
# net_string += '<type>caffe_net</type>\n'
# net_string += '<notes>Built using cnn_to_xml.py Authors: federico.corradi@inilabs.com, diederikmoeys@live.com</notes>\n'
# net_string += '<nLayers>'+str(len(nets[this_net].layer))+'</nLayers>\n'
conv_layer_num = 0
for layer in nets[this_net].layer:
if( layer.type == 'Convolution'):
conv_layer_num += 1
net_string += str(conv_layer_num)+' # num layers \n'
# net_string += '<dob>'+str(time.strftime("%d/%m/%Y %H:%M:%S"))+'</dob>\n'
#input data layer
bs, dim, x, y = nets[this_net].input_dim
#net_string += '\t<Layer>\n'
#net_string += '\t\t<index>0</index>\n'
#net_string += '\t\t<type>i</type>\n'
#net_string += '\t\t<dimx>'+str(x)+'</dimx>\n'
#net_string += '\t\t<dimy>'+str(y)+'</dimy>\n'
#net_string += '\t\t<nUnits>'+str(x*y*dim)+'</nUnits>\n'
#net_string += '\t</Layer>\n'
inputmaps = 1
#initialize indices
count_lay = 1
count_lay_two = count_lay+1
count_xml_layer = 0
counter_ip_out = 1
layers_string = ''
n_layer = len(nets[this_net].layer)
#determines which one is the last output layer
for layer in nets[this_net].layer:
if(layer.type == 'InnerProduct'):
output_layer_num = counter_ip_out
counter_ip_out += 1
for layer in nets[this_net].layer:
# if( layer.type == 'Convolution' or layer.type == 'Pooling' or layer.type == 'InnerProduct'):
# net_string += '\t<Layer>\n'
node_label = get_layer_label(layer, 'LR')
node_name = "%s_%s" % (layer.name, layer.type)
nodes_label.append(node_label)
nodes_name.append(node_name)
#find out what type of layer is this
# last layer is output layer by definition (this assumes that there is a Softmax or SoftmaxWithLoss
# layer at the very last in the prototxt network file)
if(count_lay == output_layer_num):
type_l = 'o'
count_xml_layer += 1
else:
if(layer.type == 'Convolution'):
type_l = 'c'
count_xml_layer += 1
elif(layer.type == 'LPConvolution'):
type_l = 'lpc'
count_xml_layer += 1
elif(layer.type == 'Deconvolution'):
type_l = 'd'
count_xml_layer += 1
elif(layer.type == 'Pooling'):
type_l = 's' #danny calls it subsampling instead of pooling
count_xml_layer += 1
elif(layer.type == 'InnerProduct'):
type_l = 'ip'
ip_present = True
count_xml_layer += 1
elif(layer.type == 'LPInnerProduct'):
type_l = 'lpip'
ip_present = True
count_xml_layer += 1
else:
type_l = '"%s%s(%s)"' % (layer.name, "\\n", layer.type)
#create xml entities
if(type_l == 'c'): #convolution
outputmaps = layer.convolution_param.num_output
stride = layer.convolution_param.stride
if (layer.convolution_param.kernel_size):
kernel_size = layer.convolution_param.kernel_size
else:
kernel_size = 1
this_kernels = this_classifier.params[layer.name][0].data
this_biases = this_classifier.params[layer.name][1].data
if(len(np.shape(this_biases)) > 3):
un1, un2, col_bi, row_bi = np.shape(this_biases)
this_biases_reshaped = np.reshape(this_biases, row_bi*col_bi)
else:
row_bi = np.shape(this_biases)
this_biases_reshaped = np.reshape(this_biases, row_bi)
s = " "
this_biases = s.join(str(this_biases_reshaped[i]) for i in range(len(this_biases_reshaped)))
nkernel, inputfeaturesmap, row_k, col_k = np.shape(this_kernels)
re_arrenged_kernels = []
counter = 0
for i in range(inputfeaturesmap):
for k in range(nkernel):
this_kernels[k,i,:,:] = (np.flipud(np.rot90(this_kernels[k,i,:,:])))
re_arrenged_kernels.append(this_kernels[k,i,:,:].reshape(row_k*col_k))
re_arrenged_kernels = np.array(re_arrenged_kernels)
final_k = []
this_kernels_reshaped = np.reshape(np.transpose(re_arrenged_kernels), row_k*col_k*nkernel*inputfeaturesmap, order="F")
this_kernels = s.join(str(this_kernels_reshaped[i]) for i in range(len(this_kernels_reshaped)))
next_layer = nets[this_net].layer[count_lay]
if ( next_layer.type == 'ReLU' ):
act_func = str.lower(str(next_layer.type))
elif( next_layer.type == 'Sigmoid' ):
act_func = str.lower(str(next_layer.type))
else:
act_func = 'none'
next_layer_two = nets[this_net].layer[count_lay_two]
if( next_layer_two.type == 'Pooling'):
pool_enabled = 1
else:
pool_enabled = 0
if(count_lay == 1):
compression_enabled = 0
else:
compression_enabled = 1
### write XML
net_string += str(compression_enabled)+' #compression_enabled \n'
net_string += str(kernel_size[0])+' #kernel_size \n'
net_string += str(inputmaps)+' #num_input_channels \n'
net_string += str(x)+' #num_input_column \n'
net_string += str(y)+' #num_input_rows \n'
net_string += str(outputmaps)+' #num_output_channels \n'
net_string += str(pool_enabled)+' #pooling_enabled \n'
if ( next_layer.type == 'ReLU' ): # TODO: # net_string += 'PROBLEM WITH ACTIVATION FUNCTION \n' # print(" *** PROBLEM WITH ACTIVATION FUNCTION *** ")
net_string += str(1)+' #relu_enabled\n'
else:
net_string += str(0)+' #relu_enabled\n'
net_string += str(next_layer_two.pooling_param.pad)+' #padding \n'
#net_string += '\t\t<index>'+str(count_xml_layer)+'</index>\n'
#net_string += '\t\t<type>'+str(type_l)+'</type>\n'
#net_string += '\t\t<inputMaps>'+str(inputmaps)+'</inputMaps>\n'
#net_string += '\t\t<outputMaps>'+str(outputmaps)+'</outputMaps>\n'
#net_string += '\t\t<kernelSize>'+str(kernel_size[0])+'</kernelSize>\n'
#net_string += '\t\t<activationFunction>'+act_func+'</activationFunction>\n'
net_string += '#KERNELS# \n'
for i in range(len(this_kernels)):
if(this_kernels[i] ==' '):
net_string +='\n'
else:
net_string+= this_kernels[i]
net_string += '\n'
net_string += '#BIASES# \n'
for i in range(len(this_biases)):
if(this_biases[i] ==' '):
net_string +='\n'
else:
net_string += this_biases[i]
net_string += '\n'
inputmaps = outputmaps
if(type_l == 'lpc'): #convolution
outputmaps = layer.param.num_output
stride = layer.param.stride
if (layer.param.kernel_size):
kernel_size = layer.param.kernel_size
else:
kernel_size = 1
this_kernels = this_classifier.params[layer.name][1].data
this_biases = this_classifier.params[layer.name][3].data
if(len(np.shape(this_biases)) > 3):
un1, un2, col_bi, row_bi = np.shape(this_biases)
this_biases_reshaped = np.reshape(this_biases, row_bi*col_bi)
else:
row_bi = np.shape(this_biases)
this_biases_reshaped = np.reshape(this_biases, row_bi)
s = " "
this_biases = s.join(str(this_biases_reshaped[i]) for i in range(len(this_biases_reshaped)))
nkernel, inputfeaturesmap, row_k, col_k = np.shape(this_kernels)
re_arrenged_kernels = []
counter = 0
for i in range(inputfeaturesmap):
for k in range(nkernel):
this_kernels[k,i,:,:] = (np.flipud(np.rot90(this_kernels[k,i,:,:])))
re_arrenged_kernels.append(this_kernels[k,i,:,:].reshape(row_k*col_k))
re_arrenged_kernels = np.array(re_arrenged_kernels)
final_k = []
this_kernels_reshaped = np.reshape(np.transpose(re_arrenged_kernels), row_k*col_k*nkernel*inputfeaturesmap, order="F")
this_kernels = s.join(str(this_kernels_reshaped[i]) for i in range(len(this_kernels_reshaped)))
next_layer = nets[this_net].layer[count_lay]
if ( next_layer.type == 'ReLU' ):
act_func = str.lower(str(next_layer.type))
elif( next_layer.type == 'Sigmoid' ):
act_func = str.lower(str(next_layer.type))
else:
act_func = 'none'
next_layer_two = nets[this_net].layer[count_lay_two]
if( next_layer_two.type == 'Pooling'):
pool_enabled = 1
else:
pool_enabled = 0
if(count_lay == 1):
compression_enabled = 0
else:
compression_enabled = 1
### write XML
net_string += str(compression_enabled)+' #compression_enabled \n'
net_string += str(kernel_size[0])+' #kernel_size \n'
net_string += str(inputmaps)+' #num_input_channels \n'
net_string += str(x)+' #num_input_column \n'
net_string += str(y)+' #num_input_rows \n'
net_string += str(outputmaps)+' #num_output_channels \n'
net_string += str(pool_enabled)+' #pooling_enabled \n'
if ( next_layer.type == 'ReLU' ): # TODO: # net_string += 'PROBLEM WITH ACTIVATION FUNCTION \n' # print(" *** PROBLEM WITH ACTIVATION FUNCTION *** ")
net_string += str(1)+' #relu_enabled\n'
else:
net_string += str(0)+' #relu_enabled\n'
net_string += str(next_layer_two.pooling_param.pad)+' #padding \n'
#net_string += '\t\t<index>'+str(count_xml_layer)+'</index>\n'
#net_string += '\t\t<type>'+str(type_l)+'</type>\n'
#net_string += '\t\t<inputMaps>'+str(inputmaps)+'</inputMaps>\n'
#net_string += '\t\t<outputMaps>'+str(outputmaps)+'</outputMaps>\n'
#net_string += '\t\t<kernelSize>'+str(kernel_size[0])+'</kernelSize>\n'
#net_string += '\t\t<activationFunction>'+act_func+'</activationFunction>\n'
net_string += '#KERNELS# \n'
for i in range(len(this_kernels)):
if(this_kernels[i] ==' '):
net_string +='\n'
else:
net_string+= this_kernels[i]
net_string += '\n'
net_string += '#BIASES# \n'
for i in range(len(this_biases)):
if(this_biases[i] ==' '):
net_string +='\n'
else:
net_string += this_biases[i]
net_string += '\n'
inputmaps = outputmaps
elif(type_l == 'd'): # deconvolution
print("deconvolution not yet implemented.. skipping this layer")
elif(type_l == 's'): # pooling or subsampling
#subsamplig = pooling
this_biases = this_classifier.blobs[layer.name].data
number1_bi, number2_bi, row_bi, col_bi = np.shape(this_biases)
for i in range(number2_bi):
for k in range(number1_bi):
this_biases[k,i,:,:] = (np.flipud(np.rot90(this_biases[k,i,:,:])))
this_biases_reshaped = np.reshape(this_biases, row_bi*col_bi*number1_bi*number2_bi)
s = " "
this_biases = s.join(str(this_biases_reshaped[i]) for i in range(len(this_biases_reshaped)))
### write XML
# net_string += '\t\t<index>'+str(count_xml_layer)+'</index>\n'
# net_string += '\t\t<type>'+str(type_l)+'</type>\n'
# net_string += '\t\t<poolingType>'+str.lower(get_pooling_types_dict()[layer.pooling_param.pool])+'</poolingType>\n'
# net_string += '\t\t<averageOver dt="ASCII-float32">'+str(layer.pooling_param.kernel_size)+'</averageOver>\n'
#net_string += '\t\t<biases dt="ASCII-float32">'+this_biases+'</biases>\n'
# net_string += '\t\t<strides>'+str(layer.pooling_param.stride)+'</strides>\n'
# net_string += '\t\t<pad>'+str(layer.pooling_param.pad)+'</pad>\n'
elif(type_l == 'ip' or type_l == 'o'): # fully connected or output
next_layer = nets[this_net].layer[count_lay]
if ( next_layer.type == 'ReLU' ):
act_func = str.lower(str(next_layer.type))
elif( next_layer.type == 'Sigmoid' ):
act_func = str.lower(str(next_layer.type))
else:
act_func = 'none'
fully_connected_weights = this_classifier.params[layer.name][0].data
if(len(np.shape(fully_connected_weights)) > 3):
if(type_l == 'ip'):
un1, un2, cols, rows = np.shape(fully_connected_weights)
featurespixels = rows/outputmaps ### ROWS
featureside = np.sqrt(featurespixels)
act=np.arange(featurespixels)
for j in range(cols):
for i in range(outputmaps):
fully_connected_weights = np.reshape(fully_connected_weights, [cols,rows])
act = fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)]
actback = np.reshape(act, (featureside,featureside))
actfix = actback
fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)] = np.reshape(actfix, featurespixels, order="F")
fully_connected_weights = np.transpose(fully_connected_weights)
fully_connected_weights_reshaped = np.reshape(fully_connected_weights, rows*cols)
if(type_l == 'o'):
un1, un2, cols, rows = np.shape(fully_connected_weights)
featurespixels = cols/outputmaps #### COLS
featureside = np.sqrt(featurespixels)
act=np.arange(featurespixels)
for j in range(cols):
for i in range(outputmaps):
fully_connected_weights = np.reshape(fully_connected_weights, [cols,rows])
act = fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)]
actback = np.reshape(act, (featureside,featureside))
actfix = (actback)
fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)] = np.reshape(actfix, featurespixels)
fully_connected_weights = np.transpose(fully_connected_weights)
fully_connected_weights_reshaped = np.reshape(fully_connected_weights, rows*cols)
else:
if(type_l == 'ip'):
cols, rows = np.shape(fully_connected_weights)
featurespixels = rows/outputmaps ### ROWS
featureside = np.sqrt(featurespixels)
act=np.arange(featurespixels)
for j in range(cols):
for i in range(outputmaps):
fully_connected_weights = np.reshape(fully_connected_weights, [cols,rows])
act = fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)]
actback = np.reshape(act, (featureside,featureside))
actfix = actback
fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)] = np.reshape(actfix, featurespixels, order="F")
fully_connected_weights = np.transpose(fully_connected_weights)
fully_connected_weights_reshaped = np.reshape(fully_connected_weights, rows*cols)
if(type_l == 'o'):
cols, rows = np.shape(fully_connected_weights)
if(ip_present):
featurespixels = cols/outputmaps #### COLS
else:
featurespixels = rows/outputmaps #### ROWS
featureside = np.sqrt(featurespixels)
act=np.arange(featurespixels)
for j in range(cols):
for i in range(outputmaps):
fully_connected_weights = np.reshape(fully_connected_weights, [cols,rows])
act = fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)]
actback = np.reshape(act, (featureside,featureside))
actfix = (actback)
fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)] = np.reshape(actfix, featurespixels)
fully_connected_weights = np.transpose(fully_connected_weights)
fully_connected_weights_reshaped = np.reshape(fully_connected_weights, rows*cols)
biases_output = this_classifier.params[layer.name][1].data
if(len(np.shape(biases_output)) > 3):
if(type_l == 'ip'):
un1, un2, cols_b, rows_b = np.shape(biases_output)
biases_output_reshaped = np.reshape(np.fliplr(np.flipud(np.rot90(biases_output))), un1*un2*cols_b*rows_b, order="F")
if(type_l == 'o'):
un1, un2, cols, rows = np.shape(biases_output)
featurespixels = cols/outputmaps
featureside = np.sqrt(featurespixels)
act=np.arange(featurespixels)
for j in range(cols):
for i in range(outputmaps):
fully_connected_weights = np.reshape(biases_output, [cols,rows])
act = fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)]
actback = np.reshape(act, (featureside,featureside))
actfix = (actback)
fully_connected_weights[j,featurespixels*(i):featurespixels+featurespixels*(i)] = np.reshape(actfix, featurespixels)
fully_connected_weights = (fully_connected_weights)
biases_output_reshaped = np.reshape(fully_connected_weights, rows*cols)
else:
rows_b = np.shape(biases_output)
biases_output_reshaped = np.reshape(biases_output, rows_b)
s = " "
biasweights = s.join(str(biases_output_reshaped[i]) for i in range(len(biases_output_reshaped)))
fully_connected_weights = s.join(str(fully_connected_weights_reshaped[i]) for i in range(len(fully_connected_weights_reshaped)))
### write XML
# net_string += '\t\t<activationFunction>'+act_func+'</activationFunction>\n'
# net_string += '\t\t<index>'+str(count_xml_layer)+'</index>\n'
# net_string += '\t\t<type>'+str(type_l)+'</type>\n'
# net_string += '\t\t<biases dt="ASCII-float32">'+biasweights+'</biases>\n'
# net_string += '\t\t<weights cols="'+str(cols)+'" dt="ASCII-float32" rows="'+str(rows)+'">'+fully_connected_weights+'</weights>\n'
#if( layer.type == 'Convolution' or layer.type == 'Pooling' or layer.type == 'InnerProduct' ):
### write XML
# net_string += '\t</Layer>\n' #end layer
count_lay += 1
count_lay_two += 1
# net_string += '</Network>\n'
#save xml to disc
file_xml_name = net_files[this_net]+str('_NullHop')
print("saving network in "+file_xml_name)
with open(file_xml_name, "w") as text_file:
text_file.write(net_string)
if __name__ == '__main__':
main()
| 31,660 | 49.335453 | 181 | py |
ADaPTION | ADaPTION-master/python/caffe/imagenet/convert_caffemodel_nullhop.py | import glob
import os
import numpy as np
import matplotlib.pyplot as plt
import caffe
caffe_root = '../../../'
caffe.set_mode_gpu()
caffe.set_device(0)
modelName = 'LP_VGG16'
if modelName == 'resnets':
model_def = '/users/hesham/trained_models/resNets/ResNet-50-deploy.prototxt'
model_weights = '/users/hesham/trained_models/resNets/ResNet-50-model.caffemodel'
elif modelName == 'googlenet':
model_def = '/users/hesham/trained_models/inception/deploy.prototxt'
model_weights = '/users/hesham/trained_models/inception/bvlc_googlenet.caffemodel'
elif modelName == 'LP_VGG16':
model_def = '/home/moritz/Repositories/caffe_lp/examples/low_precision/imagenet/models/LP_VGG16_5_10_deploy.prototxt'
model_weights = '/media/moritz/Ellesmera/ILSVRC2015/Snapshots/LP_VGG16_5_10_lr_00002_pad_iter_2640000.caffemodel.h5'
else:
model_def = '/users/hesham/trained_models/vgg_layers19/vgg19.model'
model_weights = '/users/hesham/trained_models/vgg_layers19/VGG_ILSVRC_19_layers.caffemodel'
net = caffe.Net(model_def, # defines the structure of the model
model_weights, # contains the trained weights
caffe.TEST) # use test mode (e.g., don't perform dropout)
# net.forward()
# print 'Forward pass done!'
convLayers = [y for (x, y) in zip(list(net._layer_names), list(net.layers)) if 'conv' in x]
print convLayers
origWeights = [x.blobs[1].data for x in convLayers]
origBiases = [x.blobs[3].data for x in convLayers]
# print 'Original Weights: ', origWeights
# imgPaths = glob.glob('/users/hesham/trained_models/data/ILSVRC2013_DET_val/*')
imgPaths = glob.glob('/media/moritz/Data/ILSVRC2015/Data/CLS-LOC/val/*')
# load the mean ImageNet image (as distributed with Caffe) for subtraction
mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')
mu = mu.mean(1).mean(1) # average over pixels to obtain the mean (BGR) pixel values
print 'mean-subtracted values:', zip('BGR', mu)
# create transformer for the input called 'data'
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2, 0, 1)) # move image channels to outermost dimension
transformer.set_mean('data', mu) # subtract the dataset-mean value in each channel
transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255]
transformer.set_channel_swap('data', (2, 1, 0)) # swap channels from RGB to BGR
img_scale = 1
for i in range(net.blobs['data'].data.shape[0]):
image = caffe.io.load_image(imgPaths[10 + i])
transformed_image = transformer.preprocess('data', image)
# plt.imshow(image)
# plt.show()
net.blobs['data'].data[i, ...] = transformed_image / img_scale
for i, x in enumerate(convLayers):
x.blobs[3].data[...] = origBiases[i] / img_scale
output = net.forward()
print 'Doing forward pass!'
# Since we want to extract the rounded weights
# We need index 1 = weights rounded and index 3 = rounded biases
allWeights = [x.blobs[1].data for x in convLayers]
allBiases = [x.blobs[3].data for x in convLayers]
# print 'All weights: ', allWeights
convBlobs = [y.data for (x, y) in net.blobs.items() if 'conv' in x]
print convBlobs
# wrapper around layer params. Currently does no special processing or error checking
class layerParam:
allParams = []
@staticmethod
def clearLayerParams():
layerParam.allParams = []
def __init__(self, width=None, height=None, nChIn=None, nChOut=128, kernel_size=3, pooling=True, relu=True, enableCompression=True, padding=0):
params = {}
self.width = width
self.height = height
self.kernel_size = kernel_size
self.nChIn = nChIn
self.nChOut = nChOut
self.pooling = pooling
self.relu = relu
self.enableCompression = enableCompression
self.padding = padding
if(len(layerParam.allParams) != 0):
prevParam = layerParam.allParams[-1]
divisor = 2 if prevParam.pooling else 1
self.width = (prevParam.width - prevParam.kernel_size + 1 + prevParam.padding * 2) / divisor
self.height = (prevParam.height - prevParam.kernel_size + 1 + prevParam.padding * 2) / divisor
self.nChIn = prevParam.nChOut
if not(self.width):
raise Exception("insufficienct information to get layer width")
if not(self.height):
raise Exception("insufficienct information to get layer height")
if not(self.nChIn):
raise Exception("insufficienct information to get layer input channel number")
print 'width : %d , height : %d , nChIn : %d' % (self.width, self.height, self.nChIn)
if not(self.nChIn):
if(len(allParams) == 0):
raise Exception("insufficient input feature map information")
prevParam = allParams[-1]
self.nChIn = prevParam.nChOut
self.kernels = np.random.randint(low=-64, high=64, size=(self.nChOut, self.nChIn, kernel_size, kernel_size))
self.biases = np.random.randint(low=-64, high=64, size=self.nChOut)
layerParam.allParams.append(self)
class network:
def __init__(self, image=None):
self.image = image
def dumpParamList(self, file, p):
file.write(' %d #compression_enabled\n' % (p.enableCompression))
file.write(' %d #kernel_size \n' % (p.kernel_size))
file.write(' %d #num input channels \n' % (p.nChIn))
file.write(' %d #num_input_column \n' % (p.width))
file.write(' %d #num_input_rows \n' % (p.height))
file.write(' %d #num_output_channels \n' % (p.nChOut))
file.write(' %d #pooling_enabled \n' % (p.pooling))
file.write(' %d #relu_enabled \n' % (p.relu))
file.write(' %d #padding \n' % (p.padding))
def dumpArray(self, file, marker, A):
file.write(marker + '\n')
file.write('\n'.join([str(x) for x in A.flatten()]) + '\n')
def dumpNetworkFile(self, path="network"):
file = open(path, 'w')
if len(layerParam.allParams) == 0:
raise Exception("empty layer parameters list")
firstLayerParams = layerParam.allParams[0]
if self.image:
if(self.image.size != firstLayerParams.num_input_channels * firstLayerParams.height * firstLayerParams.width):
raise Exception("image size does not match first layer parameters")
else:
self.image = np.random.randint(low=0, high=32, size=(firstLayerParams.nChIn, firstLayerParams.height, firstLayerParams.width))
file.write(str(len(layerParam.allParams)) + ' # num layers \n')
for (i, p) in enumerate(layerParam.allParams):
self.dumpParamList(file, p)
self.dumpArray(file, "#KERNELS#", p.kernels)
self.dumpArray(file, "#BIASES#", p.biases)
if(i == 0):
self.dumpArray(file, "#PIXELS#", self.image)
layerParam.clearLayerParams()
p1 = layerParam(width=224, height=224, nChIn=3, nChOut=64, kernel_size=3, enableCompression=False, padding=1)
p1.kernels = np.asarray(allWeights[0] * 256, 'int32')
nw = network()
nw.image = net.blobs['data'].data[0] * 256
nw = network()
# nw.dumpNetworkFile('/users/hesham/chimera_sim/systemVerilog/ini_zs/network')
pathToSave = '/home/moritz/Documents/NPP/network'
nw.dumpNetworkFile(pathToSave)
print 'Networked dumped to File: ' + pathToSave
layerParam.allParams
| 7,417 | 41.632184 | 147 | py |
ADaPTION | ADaPTION-master/python/caffe/test/test_coord_map.py | import unittest
import numpy as np
import random
import caffe
from caffe import layers as L
from caffe import params as P
from caffe.coord_map import coord_map_from_to, crop
def coord_net_spec(ks=3, stride=1, pad=0, pool=2, dstride=2, dpad=0):
"""
Define net spec for simple conv-pool-deconv pattern common to all
coordinate mapping tests.
"""
n = caffe.NetSpec()
n.data = L.Input(shape=dict(dim=[2, 1, 100, 100]))
n.aux = L.Input(shape=dict(dim=[2, 1, 20, 20]))
n.conv = L.Convolution(
n.data, num_output=10, kernel_size=ks, stride=stride, pad=pad)
n.pool = L.Pooling(
n.conv, pool=P.Pooling.MAX, kernel_size=pool, stride=pool, pad=0)
# for upsampling kernel size is 2x stride
try:
deconv_ks = [s*2 for s in dstride]
except:
deconv_ks = dstride*2
n.deconv = L.Deconvolution(
n.pool, num_output=10, kernel_size=deconv_ks, stride=dstride, pad=dpad)
return n
class TestCoordMap(unittest.TestCase):
def setUp(self):
pass
def test_conv_pool_deconv(self):
"""
Map through conv, pool, and deconv.
"""
n = coord_net_spec()
# identity for 2x pool, 2x deconv
ax, a, b = coord_map_from_to(n.deconv, n.data)
self.assertEquals(ax, 1)
self.assertEquals(a, 1)
self.assertEquals(b, 0)
# shift-by-one for 4x pool, 4x deconv
n = coord_net_spec(pool=4, dstride=4)
ax, a, b = coord_map_from_to(n.deconv, n.data)
self.assertEquals(ax, 1)
self.assertEquals(a, 1)
self.assertEquals(b, -1)
def test_pass(self):
"""
A pass-through layer (ReLU) and conv (1x1, stride 1, pad 0)
both do identity mapping.
"""
n = coord_net_spec()
ax, a, b = coord_map_from_to(n.deconv, n.data)
n.relu = L.ReLU(n.deconv)
n.conv1x1 = L.Convolution(
n.relu, num_output=10, kernel_size=1, stride=1, pad=0)
for top in [n.relu, n.conv1x1]:
ax_pass, a_pass, b_pass = coord_map_from_to(top, n.data)
self.assertEquals(ax, ax_pass)
self.assertEquals(a, a_pass)
self.assertEquals(b, b_pass)
def test_padding(self):
"""
Padding conv adds offset while padding deconv subtracts offset.
"""
n = coord_net_spec()
ax, a, b = coord_map_from_to(n.deconv, n.data)
pad = random.randint(0, 10)
# conv padding
n = coord_net_spec(pad=pad)
_, a_pad, b_pad = coord_map_from_to(n.deconv, n.data)
self.assertEquals(a, a_pad)
self.assertEquals(b - pad, b_pad)
# deconv padding
n = coord_net_spec(dpad=pad)
_, a_pad, b_pad = coord_map_from_to(n.deconv, n.data)
self.assertEquals(a, a_pad)
self.assertEquals(b + pad, b_pad)
# pad both to cancel out
n = coord_net_spec(pad=pad, dpad=pad)
_, a_pad, b_pad = coord_map_from_to(n.deconv, n.data)
self.assertEquals(a, a_pad)
self.assertEquals(b, b_pad)
def test_multi_conv(self):
"""
Multiple bottoms/tops of a layer are identically mapped.
"""
n = coord_net_spec()
# multi bottom/top
n.conv_data, n.conv_aux = L.Convolution(
n.data, n.aux, ntop=2, num_output=10, kernel_size=5, stride=2,
pad=0)
ax1, a1, b1 = coord_map_from_to(n.conv_data, n.data)
ax2, a2, b2 = coord_map_from_to(n.conv_aux, n.aux)
self.assertEquals(ax1, ax2)
self.assertEquals(a1, a2)
self.assertEquals(b1, b2)
def test_rect(self):
"""
Anisotropic mapping is equivalent to its isotropic parts.
"""
n3x3 = coord_net_spec(ks=3, stride=1, pad=0)
n5x5 = coord_net_spec(ks=5, stride=2, pad=10)
n3x5 = coord_net_spec(ks=[3, 5], stride=[1, 2], pad=[0, 10])
ax_3x3, a_3x3, b_3x3 = coord_map_from_to(n3x3.deconv, n3x3.data)
ax_5x5, a_5x5, b_5x5 = coord_map_from_to(n5x5.deconv, n5x5.data)
ax_3x5, a_3x5, b_3x5 = coord_map_from_to(n3x5.deconv, n3x5.data)
self.assertTrue(ax_3x3 == ax_5x5 == ax_3x5)
self.assertEquals(a_3x3, a_3x5[0])
self.assertEquals(b_3x3, b_3x5[0])
self.assertEquals(a_5x5, a_3x5[1])
self.assertEquals(b_5x5, b_3x5[1])
def test_nd_conv(self):
"""
ND conv maps the same way in more dimensions.
"""
n = caffe.NetSpec()
# define data with 3 spatial dimensions, otherwise the same net
n.data = L.Input(shape=dict(dim=[2, 3, 100, 100, 100]))
n.conv = L.Convolution(
n.data, num_output=10, kernel_size=[3, 3, 3], stride=[1, 1, 1],
pad=[0, 1, 2])
n.pool = L.Pooling(
n.conv, pool=P.Pooling.MAX, kernel_size=2, stride=2, pad=0)
n.deconv = L.Deconvolution(
n.pool, num_output=10, kernel_size=4, stride=2, pad=0)
ax, a, b = coord_map_from_to(n.deconv, n.data)
self.assertEquals(ax, 1)
self.assertTrue(len(a) == len(b))
self.assertTrue(np.all(a == 1))
self.assertEquals(b[0] - 1, b[1])
self.assertEquals(b[1] - 1, b[2])
def test_crop_of_crop(self):
"""
Map coordinates through Crop layer:
crop an already-cropped output to the input and check change in offset.
"""
n = coord_net_spec()
offset = random.randint(0, 10)
ax, a, b = coord_map_from_to(n.deconv, n.data)
n.crop = L.Crop(n.deconv, n.data, axis=2, offset=offset)
ax_crop, a_crop, b_crop = coord_map_from_to(n.crop, n.data)
self.assertEquals(ax, ax_crop)
self.assertEquals(a, a_crop)
self.assertEquals(b + offset, b_crop)
def test_crop_helper(self):
"""
Define Crop layer by crop().
"""
n = coord_net_spec()
crop(n.deconv, n.data)
def test_catch_unconnected(self):
"""
Catch mapping spatially unconnected tops.
"""
n = coord_net_spec()
n.ip = L.InnerProduct(n.deconv, num_output=10)
with self.assertRaises(RuntimeError):
coord_map_from_to(n.ip, n.data)
def test_catch_scale_mismatch(self):
"""
Catch incompatible scales, such as when the top to be cropped
is mapped to a differently strided reference top.
"""
n = coord_net_spec(pool=3, dstride=2) # pool 3x but deconv 2x
with self.assertRaises(AssertionError):
crop(n.deconv, n.data)
def test_catch_negative_crop(self):
"""
Catch impossible offsets, such as when the top to be cropped
is mapped to a larger reference top.
"""
n = coord_net_spec(dpad=10) # make output smaller than input
with self.assertRaises(AssertionError):
crop(n.deconv, n.data)
| 6,894 | 34.725389 | 79 | py |
ADaPTION | ADaPTION-master/python/caffe/test/test_python_layer_with_param_str.py | import unittest
import tempfile
import os
import six
import caffe
class SimpleParamLayer(caffe.Layer):
"""A layer that just multiplies by the numeric value of its param string"""
def setup(self, bottom, top):
try:
self.value = float(self.param_str)
except ValueError:
raise ValueError("Parameter string must be a legible float")
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].data.shape)
def forward(self, bottom, top):
top[0].data[...] = self.value * bottom[0].data
def backward(self, top, propagate_down, bottom):
bottom[0].diff[...] = self.value * top[0].diff
def python_param_net_file():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
f.write("""name: 'pythonnet' force_backward: true
input: 'data' input_shape { dim: 10 dim: 9 dim: 8 }
layer { type: 'Python' name: 'mul10' bottom: 'data' top: 'mul10'
python_param { module: 'test_python_layer_with_param_str'
layer: 'SimpleParamLayer' param_str: '10' } }
layer { type: 'Python' name: 'mul2' bottom: 'mul10' top: 'mul2'
python_param { module: 'test_python_layer_with_param_str'
layer: 'SimpleParamLayer' param_str: '2' } }""")
return f.name
@unittest.skipIf('Python' not in caffe.layer_type_list(),
'Caffe built without Python layer support')
class TestLayerWithParam(unittest.TestCase):
def setUp(self):
net_file = python_param_net_file()
self.net = caffe.Net(net_file, caffe.TRAIN)
os.remove(net_file)
def test_forward(self):
x = 8
self.net.blobs['data'].data[...] = x
self.net.forward()
for y in self.net.blobs['mul2'].data.flat:
self.assertEqual(y, 2 * 10 * x)
def test_backward(self):
x = 7
self.net.blobs['mul2'].diff[...] = x
self.net.backward()
for y in self.net.blobs['data'].diff.flat:
self.assertEqual(y, 2 * 10 * x)
| 2,031 | 31.774194 | 79 | py |
ADaPTION | ADaPTION-master/python/caffe/test/test_io.py | import numpy as np
import unittest
import caffe
class TestBlobProtoToArray(unittest.TestCase):
def test_old_format(self):
data = np.zeros((10,10))
blob = caffe.proto.caffe_pb2.BlobProto()
blob.data.extend(list(data.flatten()))
shape = (1,1,10,10)
blob.num, blob.channels, blob.height, blob.width = shape
arr = caffe.io.blobproto_to_array(blob)
self.assertEqual(arr.shape, shape)
def test_new_format(self):
data = np.zeros((10,10))
blob = caffe.proto.caffe_pb2.BlobProto()
blob.data.extend(list(data.flatten()))
blob.shape.dim.extend(list(data.shape))
arr = caffe.io.blobproto_to_array(blob)
self.assertEqual(arr.shape, data.shape)
def test_no_shape(self):
data = np.zeros((10,10))
blob = caffe.proto.caffe_pb2.BlobProto()
blob.data.extend(list(data.flatten()))
with self.assertRaises(ValueError):
caffe.io.blobproto_to_array(blob)
def test_scalar(self):
data = np.ones((1)) * 123
blob = caffe.proto.caffe_pb2.BlobProto()
blob.data.extend(list(data.flatten()))
arr = caffe.io.blobproto_to_array(blob)
self.assertEqual(arr, 123)
class TestArrayToDatum(unittest.TestCase):
def test_label_none_size(self):
# Set label
d1 = caffe.io.array_to_datum(
np.ones((10,10,3)), label=1)
# Don't set label
d2 = caffe.io.array_to_datum(
np.ones((10,10,3)))
# Not setting the label should result in a smaller object
self.assertGreater(
len(d1.SerializeToString()),
len(d2.SerializeToString()))
| 1,694 | 28.736842 | 65 | py |
ADaPTION | ADaPTION-master/python/caffe/test/test_solver.py | import unittest
import tempfile
import os
import numpy as np
import six
import caffe
from test_net import simple_net_file
class TestSolver(unittest.TestCase):
def setUp(self):
self.num_output = 13
net_f = simple_net_file(self.num_output)
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
f.write("""net: '""" + net_f + """'
test_iter: 10 test_interval: 10 base_lr: 0.01 momentum: 0.9
weight_decay: 0.0005 lr_policy: 'inv' gamma: 0.0001 power: 0.75
display: 100 max_iter: 100 snapshot_after_train: false
snapshot_prefix: "model" """)
f.close()
self.solver = caffe.SGDSolver(f.name)
# also make sure get_solver runs
caffe.get_solver(f.name)
caffe.set_mode_cpu()
# fill in valid labels
self.solver.net.blobs['label'].data[...] = \
np.random.randint(self.num_output,
size=self.solver.net.blobs['label'].data.shape)
self.solver.test_nets[0].blobs['label'].data[...] = \
np.random.randint(self.num_output,
size=self.solver.test_nets[0].blobs['label'].data.shape)
os.remove(f.name)
os.remove(net_f)
def test_solve(self):
self.assertEqual(self.solver.iter, 0)
self.solver.solve()
self.assertEqual(self.solver.iter, 100)
def test_net_memory(self):
"""Check that nets survive after the solver is destroyed."""
nets = [self.solver.net] + list(self.solver.test_nets)
self.assertEqual(len(nets), 2)
del self.solver
total = 0
for net in nets:
for ps in six.itervalues(net.params):
for p in ps:
total += p.data.sum() + p.diff.sum()
for bl in six.itervalues(net.blobs):
total += bl.data.sum() + bl.diff.sum()
def test_snapshot(self):
self.solver.snapshot()
# Check that these files exist and then remove them
files = ['model_iter_0.caffemodel', 'model_iter_0.solverstate']
for fn in files:
assert os.path.isfile(fn)
os.remove(fn)
| 2,165 | 33.380952 | 76 | py |
ADaPTION | ADaPTION-master/python/caffe/test/test_layer_type_list.py | import unittest
import caffe
class TestLayerTypeList(unittest.TestCase):
def test_standard_types(self):
#removing 'Data' from list
for type_name in ['Data', 'Convolution', 'InnerProduct']:
self.assertIn(type_name, caffe.layer_type_list(),
'%s not in layer_type_list()' % type_name)
| 338 | 27.25 | 65 | py |
ADaPTION | ADaPTION-master/python/caffe/test/test_net.py | import unittest
import tempfile
import os
import numpy as np
import six
from collections import OrderedDict
import caffe
def simple_net_file(num_output):
"""Make a simple net prototxt, based on test_net.cpp, returning the name
of the (temporary) file."""
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
f.write("""name: 'testnet' force_backward: true
layer { type: 'DummyData' name: 'data' top: 'data' top: 'label'
dummy_data_param { num: 5 channels: 2 height: 3 width: 4
num: 5 channels: 1 height: 1 width: 1
data_filler { type: 'gaussian' std: 1 }
data_filler { type: 'constant' } } }
layer { type: 'Convolution' name: 'conv' bottom: 'data' top: 'conv'
convolution_param { num_output: 11 kernel_size: 2 pad: 3
weight_filler { type: 'gaussian' std: 1 }
bias_filler { type: 'constant' value: 2 } }
param { decay_mult: 1 } param { decay_mult: 0 }
}
layer { type: 'InnerProduct' name: 'ip' bottom: 'conv' top: 'ip'
inner_product_param { num_output: """ + str(num_output) + """
weight_filler { type: 'gaussian' std: 2.5 }
bias_filler { type: 'constant' value: -3 } } }
layer { type: 'SoftmaxWithLoss' name: 'loss' bottom: 'ip' bottom: 'label'
top: 'loss' }""")
f.close()
return f.name
class TestNet(unittest.TestCase):
def setUp(self):
self.num_output = 13
net_file = simple_net_file(self.num_output)
self.net = caffe.Net(net_file, caffe.TRAIN)
# fill in valid labels
self.net.blobs['label'].data[...] = \
np.random.randint(self.num_output,
size=self.net.blobs['label'].data.shape)
os.remove(net_file)
def test_memory(self):
"""Check that holding onto blob data beyond the life of a Net is OK"""
params = sum(map(list, six.itervalues(self.net.params)), [])
blobs = self.net.blobs.values()
del self.net
# now sum everything (forcing all memory to be read)
total = 0
for p in params:
total += p.data.sum() + p.diff.sum()
for bl in blobs:
total += bl.data.sum() + bl.diff.sum()
def test_forward_backward(self):
self.net.forward()
self.net.backward()
def test_clear_param_diffs(self):
# Run a forward/backward step to have non-zero diffs
self.net.forward()
self.net.backward()
diff = self.net.params["conv"][0].diff
# Check that we have non-zero diffs
self.assertTrue(diff.max() > 0)
self.net.clear_param_diffs()
# Check that the diffs are now 0
self.assertTrue((diff == 0).all())
def test_inputs_outputs(self):
self.assertEqual(self.net.inputs, [])
self.assertEqual(self.net.outputs, ['loss'])
def test_top_bottom_names(self):
self.assertEqual(self.net.top_names,
OrderedDict([('data', ['data', 'label']),
('conv', ['conv']),
('ip', ['ip']),
('loss', ['loss'])]))
self.assertEqual(self.net.bottom_names,
OrderedDict([('data', []),
('conv', ['data']),
('ip', ['conv']),
('loss', ['ip', 'label'])]))
def test_save_and_read(self):
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
f.close()
self.net.save(f.name)
net_file = simple_net_file(self.num_output)
# Test legacy constructor
# should print deprecation warning
caffe.Net(net_file, f.name, caffe.TRAIN)
# Test named constructor
net2 = caffe.Net(net_file, caffe.TRAIN, weights=f.name)
os.remove(net_file)
os.remove(f.name)
for name in self.net.params:
for i in range(len(self.net.params[name])):
self.assertEqual(abs(self.net.params[name][i].data
- net2.params[name][i].data).sum(), 0)
def test_save_hdf5(self):
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
f.close()
self.net.save_hdf5(f.name)
net_file = simple_net_file(self.num_output)
net2 = caffe.Net(net_file, caffe.TRAIN)
net2.load_hdf5(f.name)
os.remove(net_file)
os.remove(f.name)
for name in self.net.params:
for i in range(len(self.net.params[name])):
self.assertEqual(abs(self.net.params[name][i].data
- net2.params[name][i].data).sum(), 0)
class TestLevels(unittest.TestCase):
TEST_NET = """
layer {
name: "data"
type: "DummyData"
top: "data"
dummy_data_param { shape { dim: 1 dim: 1 dim: 10 dim: 10 } }
}
layer {
name: "NoLevel"
type: "InnerProduct"
bottom: "data"
top: "NoLevel"
inner_product_param { num_output: 1 }
}
layer {
name: "Level0Only"
type: "InnerProduct"
bottom: "data"
top: "Level0Only"
include { min_level: 0 max_level: 0 }
inner_product_param { num_output: 1 }
}
layer {
name: "Level1Only"
type: "InnerProduct"
bottom: "data"
top: "Level1Only"
include { min_level: 1 max_level: 1 }
inner_product_param { num_output: 1 }
}
layer {
name: "Level>=0"
type: "InnerProduct"
bottom: "data"
top: "Level>=0"
include { min_level: 0 }
inner_product_param { num_output: 1 }
}
layer {
name: "Level>=1"
type: "InnerProduct"
bottom: "data"
top: "Level>=1"
include { min_level: 1 }
inner_product_param { num_output: 1 }
}
"""
def setUp(self):
self.f = tempfile.NamedTemporaryFile(mode='w+')
self.f.write(self.TEST_NET)
self.f.flush()
def tearDown(self):
self.f.close()
def check_net(self, net, blobs):
net_blobs = [b for b in net.blobs.keys() if 'data' not in b]
self.assertEqual(net_blobs, blobs)
def test_0(self):
net = caffe.Net(self.f.name, caffe.TEST)
self.check_net(net, ['NoLevel', 'Level0Only', 'Level>=0'])
def test_1(self):
net = caffe.Net(self.f.name, caffe.TEST, level=1)
self.check_net(net, ['NoLevel', 'Level1Only', 'Level>=0', 'Level>=1'])
class TestStages(unittest.TestCase):
TEST_NET = """
layer {
name: "data"
type: "DummyData"
top: "data"
dummy_data_param { shape { dim: 1 dim: 1 dim: 10 dim: 10 } }
}
layer {
name: "A"
type: "InnerProduct"
bottom: "data"
top: "A"
include { stage: "A" }
inner_product_param { num_output: 1 }
}
layer {
name: "B"
type: "InnerProduct"
bottom: "data"
top: "B"
include { stage: "B" }
inner_product_param { num_output: 1 }
}
layer {
name: "AorB"
type: "InnerProduct"
bottom: "data"
top: "AorB"
include { stage: "A" }
include { stage: "B" }
inner_product_param { num_output: 1 }
}
layer {
name: "AandB"
type: "InnerProduct"
bottom: "data"
top: "AandB"
include { stage: "A" stage: "B" }
inner_product_param { num_output: 1 }
}
"""
def setUp(self):
self.f = tempfile.NamedTemporaryFile(mode='w+')
self.f.write(self.TEST_NET)
self.f.flush()
def tearDown(self):
self.f.close()
def check_net(self, net, blobs):
net_blobs = [b for b in net.blobs.keys() if 'data' not in b]
self.assertEqual(net_blobs, blobs)
def test_A(self):
net = caffe.Net(self.f.name, caffe.TEST, stages=['A'])
self.check_net(net, ['A', 'AorB'])
def test_B(self):
net = caffe.Net(self.f.name, caffe.TEST, stages=['B'])
self.check_net(net, ['B', 'AorB'])
def test_AandB(self):
net = caffe.Net(self.f.name, caffe.TEST, stages=['A', 'B'])
self.check_net(net, ['A', 'B', 'AorB', 'AandB'])
class TestAllInOne(unittest.TestCase):
TEST_NET = """
layer {
name: "train_data"
type: "DummyData"
top: "data"
top: "label"
dummy_data_param {
shape { dim: 1 dim: 1 dim: 10 dim: 10 }
shape { dim: 1 dim: 1 dim: 1 dim: 1 }
}
include { phase: TRAIN stage: "train" }
}
layer {
name: "val_data"
type: "DummyData"
top: "data"
top: "label"
dummy_data_param {
shape { dim: 1 dim: 1 dim: 10 dim: 10 }
shape { dim: 1 dim: 1 dim: 1 dim: 1 }
}
include { phase: TEST stage: "val" }
}
layer {
name: "deploy_data"
type: "Input"
top: "data"
input_param { shape { dim: 1 dim: 1 dim: 10 dim: 10 } }
include { phase: TEST stage: "deploy" }
}
layer {
name: "ip"
type: "InnerProduct"
bottom: "data"
top: "ip"
inner_product_param { num_output: 2 }
}
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "ip"
bottom: "label"
top: "loss"
include: { phase: TRAIN stage: "train" }
include: { phase: TEST stage: "val" }
}
layer {
name: "pred"
type: "Softmax"
bottom: "ip"
top: "pred"
include: { phase: TEST stage: "deploy" }
}
"""
def setUp(self):
self.f = tempfile.NamedTemporaryFile(mode='w+')
self.f.write(self.TEST_NET)
self.f.flush()
def tearDown(self):
self.f.close()
def check_net(self, net, outputs):
self.assertEqual(list(net.blobs['data'].shape), [1,1,10,10])
self.assertEqual(net.outputs, outputs)
def test_train(self):
net = caffe.Net(self.f.name, caffe.TRAIN, stages=['train'])
self.check_net(net, ['loss'])
def test_val(self):
net = caffe.Net(self.f.name, caffe.TEST, stages=['val'])
self.check_net(net, ['loss'])
def test_deploy(self):
net = caffe.Net(self.f.name, caffe.TEST, stages=['deploy'])
self.check_net(net, ['pred'])
| 9,656 | 26.910405 | 78 | py |
ADaPTION | ADaPTION-master/python/caffe/test/test_net_spec.py | import unittest
import tempfile
import caffe
from caffe import layers as L
from caffe import params as P
def lenet(batch_size):
n = caffe.NetSpec()
n.data, n.label = L.DummyData(shape=[dict(dim=[batch_size, 1, 28, 28]),
dict(dim=[batch_size, 1, 1, 1])],
transform_param=dict(scale=1./255), ntop=2)
n.conv1 = L.Convolution(n.data, kernel_size=5, num_output=20,
weight_filler=dict(type='xavier'))
n.pool1 = L.Pooling(n.conv1, kernel_size=2, stride=2, pool=P.Pooling.MAX)
n.conv2 = L.Convolution(n.pool1, kernel_size=5, num_output=50,
weight_filler=dict(type='xavier'))
n.pool2 = L.Pooling(n.conv2, kernel_size=2, stride=2, pool=P.Pooling.MAX)
n.ip1 = L.InnerProduct(n.pool2, num_output=500,
weight_filler=dict(type='xavier'))
n.relu1 = L.ReLU(n.ip1, in_place=True)
n.ip2 = L.InnerProduct(n.relu1, num_output=10,
weight_filler=dict(type='xavier'))
n.loss = L.SoftmaxWithLoss(n.ip2, n.label)
return n.to_proto()
def anon_lenet(batch_size):
data, label = L.DummyData(shape=[dict(dim=[batch_size, 1, 28, 28]),
dict(dim=[batch_size, 1, 1, 1])],
transform_param=dict(scale=1./255), ntop=2)
conv1 = L.Convolution(data, kernel_size=5, num_output=20,
weight_filler=dict(type='xavier'))
pool1 = L.Pooling(conv1, kernel_size=2, stride=2, pool=P.Pooling.MAX)
conv2 = L.Convolution(pool1, kernel_size=5, num_output=50,
weight_filler=dict(type='xavier'))
pool2 = L.Pooling(conv2, kernel_size=2, stride=2, pool=P.Pooling.MAX)
ip1 = L.InnerProduct(pool2, num_output=500,
weight_filler=dict(type='xavier'))
relu1 = L.ReLU(ip1, in_place=True)
ip2 = L.InnerProduct(relu1, num_output=10,
weight_filler=dict(type='xavier'))
loss = L.SoftmaxWithLoss(ip2, label)
return loss.to_proto()
def silent_net():
n = caffe.NetSpec()
n.data, n.data2 = L.DummyData(shape=dict(dim=3), ntop=2)
n.silence_data = L.Silence(n.data, ntop=0)
n.silence_data2 = L.Silence(n.data2, ntop=0)
return n.to_proto()
class TestNetSpec(unittest.TestCase):
def load_net(self, net_proto):
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
f.write(str(net_proto))
f.close()
return caffe.Net(f.name, caffe.TEST)
def test_lenet(self):
"""Construct and build the Caffe version of LeNet."""
net_proto = lenet(50)
# check that relu is in-place
self.assertEqual(net_proto.layer[6].bottom,
net_proto.layer[6].top)
net = self.load_net(net_proto)
# check that all layers are present
self.assertEqual(len(net.layers), 9)
# now the check the version with automatically-generated layer names
net_proto = anon_lenet(50)
self.assertEqual(net_proto.layer[6].bottom,
net_proto.layer[6].top)
net = self.load_net(net_proto)
self.assertEqual(len(net.layers), 9)
def test_zero_tops(self):
"""Test net construction for top-less layers."""
net_proto = silent_net()
net = self.load_net(net_proto)
self.assertEqual(len(net.forward()), 0)
| 3,287 | 39.097561 | 77 | py |
ADaPTION | ADaPTION-master/python/caffe/test/test_python_layer.py | import unittest
import tempfile
import os
import six
import caffe
class SimpleLayer(caffe.Layer):
"""A layer that just multiplies by ten"""
def setup(self, bottom, top):
pass
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].data.shape)
def forward(self, bottom, top):
top[0].data[...] = 10 * bottom[0].data
def backward(self, top, propagate_down, bottom):
bottom[0].diff[...] = 10 * top[0].diff
class ExceptionLayer(caffe.Layer):
"""A layer for checking exceptions from Python"""
def setup(self, bottom, top):
raise RuntimeError
class ParameterLayer(caffe.Layer):
"""A layer that just multiplies by ten"""
def setup(self, bottom, top):
self.blobs.add_blob(1)
self.blobs[0].data[0] = 0
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].data.shape)
def forward(self, bottom, top):
pass
def backward(self, top, propagate_down, bottom):
self.blobs[0].diff[0] = 1
class PhaseLayer(caffe.Layer):
"""A layer for checking attribute `phase`"""
def setup(self, bottom, top):
pass
def reshape(self, bootom, top):
top[0].reshape()
def forward(self, bottom, top):
top[0].data[()] = self.phase
def python_net_file():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
f.write("""name: 'pythonnet' force_backward: true
input: 'data' input_shape { dim: 10 dim: 9 dim: 8 }
layer { type: 'Python' name: 'one' bottom: 'data' top: 'one'
python_param { module: 'test_python_layer' layer: 'SimpleLayer' } }
layer { type: 'Python' name: 'two' bottom: 'one' top: 'two'
python_param { module: 'test_python_layer' layer: 'SimpleLayer' } }
layer { type: 'Python' name: 'three' bottom: 'two' top: 'three'
python_param { module: 'test_python_layer' layer: 'SimpleLayer' } }""")
return f.name
def exception_net_file():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
f.write("""name: 'pythonnet' force_backward: true
input: 'data' input_shape { dim: 10 dim: 9 dim: 8 }
layer { type: 'Python' name: 'layer' bottom: 'data' top: 'top'
python_param { module: 'test_python_layer' layer: 'ExceptionLayer' } }
""")
return f.name
def parameter_net_file():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
f.write("""name: 'pythonnet' force_backward: true
input: 'data' input_shape { dim: 10 dim: 9 dim: 8 }
layer { type: 'Python' name: 'layer' bottom: 'data' top: 'top'
python_param { module: 'test_python_layer' layer: 'ParameterLayer' } }
""")
return f.name
def phase_net_file():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
f.write("""name: 'pythonnet' force_backward: true
layer { type: 'Python' name: 'layer' top: 'phase'
python_param { module: 'test_python_layer' layer: 'PhaseLayer' } }
""")
return f.name
@unittest.skipIf('Python' not in caffe.layer_type_list(),
'Caffe built without Python layer support')
class TestPythonLayer(unittest.TestCase):
def setUp(self):
net_file = python_net_file()
self.net = caffe.Net(net_file, caffe.TRAIN)
os.remove(net_file)
def test_forward(self):
x = 8
self.net.blobs['data'].data[...] = x
self.net.forward()
for y in self.net.blobs['three'].data.flat:
self.assertEqual(y, 10**3 * x)
def test_backward(self):
x = 7
self.net.blobs['three'].diff[...] = x
self.net.backward()
for y in self.net.blobs['data'].diff.flat:
self.assertEqual(y, 10**3 * x)
def test_reshape(self):
s = 4
self.net.blobs['data'].reshape(s, s, s, s)
self.net.forward()
for blob in six.itervalues(self.net.blobs):
for d in blob.data.shape:
self.assertEqual(s, d)
def test_exception(self):
net_file = exception_net_file()
self.assertRaises(RuntimeError, caffe.Net, net_file, caffe.TEST)
os.remove(net_file)
def test_parameter(self):
net_file = parameter_net_file()
net = caffe.Net(net_file, caffe.TRAIN)
# Test forward and backward
net.forward()
net.backward()
layer = net.layers[list(net._layer_names).index('layer')]
self.assertEqual(layer.blobs[0].data[0], 0)
self.assertEqual(layer.blobs[0].diff[0], 1)
layer.blobs[0].data[0] += layer.blobs[0].diff[0]
self.assertEqual(layer.blobs[0].data[0], 1)
# Test saving and loading
h, caffemodel_file = tempfile.mkstemp()
net.save(caffemodel_file)
layer.blobs[0].data[0] = -1
self.assertEqual(layer.blobs[0].data[0], -1)
net.copy_from(caffemodel_file)
self.assertEqual(layer.blobs[0].data[0], 1)
os.remove(caffemodel_file)
# Test weight sharing
net2 = caffe.Net(net_file, caffe.TRAIN)
net2.share_with(net)
layer = net.layers[list(net2._layer_names).index('layer')]
self.assertEqual(layer.blobs[0].data[0], 1)
os.remove(net_file)
def test_phase(self):
net_file = phase_net_file()
for phase in caffe.TRAIN, caffe.TEST:
net = caffe.Net(net_file, phase)
self.assertEqual(net.forward()['phase'], phase)
| 5,510 | 31.609467 | 81 | py |
ADaPTION | ADaPTION-master/python/caffe/quantization/convert_weights.py | '''
This script converts weights, which are trained without rounding, to match the size of the
data blobs of low precison rounded weights.
In high precision each conv layer has two blob allocated for the weights and the biases
However in low precision, since we are using dual copy roudning/pow2quantization, we basically
have 4 blobs weights in high and low precision and biases in high and low precision
List of functions, for further details see below
- download_model
- convert_weights
Author: Moritz Milde
Date: 02.11.2016
E-Mail: mmilde@ini.uzh.ch
'''
import numpy as np
import caffe
import os
class convert_weights():
def __init__(self):
self.caffe_root = '/home/moritz/Repositories/caffe_lp/'
self.model_dir = 'examples/low_precision/imagenet/models/'
self.weight_dir = '/media/moritz/Data/ILSVRC2015/pre_trained/'
def download_model(self, net_name, current_dir, url=None):
'''
This function will create a subfolder in current_dir based on the network name
Input:
- net_name: A string which refer to the network, e.g. VGG16 or GoogleNet (type: string)
- current_dir: The directory where you want to save the .caffemodel files (type: string)
- url: URL to download a caffemodel from. If not specified it is set to non and
currently only VGG16 is supported. Other Networks will be added in the future (type: str)
Output:
- flag: saying if automatic download succeeded. If not script stops and you have to manually download
the caffemodel (type: bool)
If you have to manually download the caffemodel please follow naming convention:
/path/to/weight_dir/{net_name}/{net_name}_original.caffemodel
'''
if not os.path.exists(current_dir):
print 'Create working direcory'
os.makedirs(current_dir)
if url is not None:
print 'Downloading to ' + current_dir
filename = '%s.caffemodel' % (net_name + '_original')
if not os.path.isfile(current_dir + filename):
os.system('wget -O %s %s' % (current_dir + filename, url))
print 'Done'
else:
print 'File already downloaded'
return True
print 'Downloading to ' + current_dir
filename = '%s.caffemodel' % (net_name + '_original')
print current_dir + filename
if not os.path.isfile(current_dir + filename):
if url is None:
if net_name == 'VGG16':
url = 'http://www.robots.ox.ac.uk/%7Evgg/software/very_deep/caffe/VGG_ILSVRC_16_layers.caffemodel'
else:
print 'Please download disired files from https://github.com/BVLC/caffe/wiki/Model-Zoo'
return False
os.system('wget -O %s %s' % (current_dir + filename, url))
print 'Done'
return True
else:
print 'File already downloaded'
return True
def convert_weights(self, net_name, save_name=None, caffe_root=None, model_dir=None, weight_dir=None, url=None, debug=False):
'''
This function will extract weights and biases from a pre_trained network and overwrites a dummy
low precision network. After this conversion the network can be used later for finetuning
after extracting layer-wise Qm.f notation
Input:
- net_name: A string which refer to the network, e.g. VGG16 or GoogleNet (type: string)
- save_name: A string which refer to the name you want to save your new caffemodel to be used later for
bit_distribution and finetuning. The convention is HP_{net_name}_v2.caffemodel (type: string)
- caffe_root: Path to your caffe_lp folder (type: string)
- model_dir: Relative path from caffe_root to model directory (where .prototxt files are located). This is usually
examples/low_precision/imagenet/models/
Please change accordingly! (type: string)
- weight_dir Path where you want save the .caffemodel files, e.g. on your HDD (type: string)
- debug: Flag to turn printing of helpful information on and off (type: bool)
Output:
This script does not output anything directly. However 5 files are generated
- CaffemodelCopy: A copy made from the original .caffemodel file to ensure that we don't change anything in the original file
- HP_{net_name}_v2.caffemodel: The high precision weights copied to the low precision blob structure
HP: 0 = weights, 1 = biases
LP: 0 = hp weights, 1 = lp weights, 2 = hp biases, 3 = lp biases
- Sparsity measure: Saves two txt files for weight sparsity in the high and low precision setting while converting
These files only makes sense if dummyLP_{net_name}.caffemodel was copied from a working lp.caffemodel
'''
if caffe_root is not None:
self.caffe_root = caffe_root
if model_dir is not None:
self.model_dir = model_dir
if weight_dir is not None:
self.weight_dir = weight_dir
if save_name is None:
self.save_name = 'HP_{}_v2.caffemodel'.format(net_name)
net_original = '{}_original.caffemodel'.format(net_name)
net_new = 'HP_{}.caffemodel'.format(net_name)
current_dir = weight_dir + net_name + '/'
if url is not None:
flag = convert_weights.download_model(self, net_name, current_dir, url)
else:
flag = convert_weights.download_model(self, net_name, current_dir)
assert flag, 'Please download caffemodel manually. This type of network currently not supported for automatized download.'
if debug:
print 'Copying {} to {}'.format(net_original, net_new)
print current_dir
os.system('cp %s %s' % (current_dir + net_original, current_dir + net_new))
weights_hp = current_dir + net_new
# Build prototxt based on deploy --> dummyLP_NetName_deploy.prototxt
# if not os.path.isfile(current_dir + 'dummyLP_{}.caffemodel.h5'):
# pass
# simulate for 1 iteration and save weights as dummyLP_NetName.caffemodel.h5
weights_lp = current_dir + 'dummyLP_{}.caffemodel.h5'.format(net_name)
prototxt_hp = self.caffe_root + self.model_dir + '{}_deploy.prototxt'.format(net_name)
prototxt_lp = self.caffe_root + self.model_dir + 'dummyLP_{}_deploy.prototxt'.format(net_name)
caffe.set_mode_gpu()
caffe.set_device(0)
net_hp = caffe.Net(prototxt_hp, weights_hp, caffe.TEST)
if debug:
print('Doing forward pass for original high precision network')
print 'Network file: {}'.format(prototxt_hp)
net_hp.forward()
if debug:
print('Done.')
caffe.set_mode_gpu()
caffe.set_device(0)
net_lp = caffe.Net(prototxt_lp, weights_lp, caffe.TEST)
if debug:
print('Doing forward pass for low precision network')
print 'Network file: {}'.format(prototxt_lp)
net_lp.forward()
if debug:
print('Done.')
sparsity_hp = open(self.weight_dir + 'sparsity_hp.txt', 'w')
sparsity_lp = open(self.weight_dir + 'sparsity_lp.txt', 'w')
for i, ldx in enumerate(net_hp.params.keys()):
if debug:
print 'Original net'
print 'Layer {}'.format(ldx)
print np.shape(net_hp.params[ldx][0].data[...])
print '\n'
ldx_lp = net_lp.params.keys()[i]
if debug:
print 'Low precision net'
print 'Layer {}'.format(ldx_lp)
print np.shape(net_lp.params[ldx_lp][0].data[...])
print '---------------'
W = net_hp.params[ldx][0].data[...]
b = net_hp.params[ldx][1].data[...]
# Calculate sparsity for each layer
W_reshape = np.reshape(W, [1, -1])
sparsity1 = float(np.sum(W_reshape[0, :] == 0)) / float(len(W_reshape[0, :])) * 100.
sparsity_hp.write('%s layer: %f \n' % (ldx, sparsity1))
W_reshape = np.reshape(net_lp.params[ldx_lp][1].data[...], [1, -1])
sparsity2 = float(np.sum(W_reshape[0, :] == 0)) / float(len(W_reshape[0, :])) * 100.
sparsity_lp.write('%s layer: %f \n' % (ldx_lp, sparsity2))
net_lp.params[ldx_lp][0].data[...] = W
net_lp.params[ldx_lp][1].data[...] = W
net_lp.params[ldx_lp][2].data[...] = b
net_lp.params[ldx_lp][3].data[...] = b
if save_name is not None:
self.save_name = '{}.caffemodel'.format(save_name)
net_lp.save(current_dir + self.save_name)
sparsity_hp.close()
sparsity_lp.close()
print 'Saving done caffemodel to {}'.format(current_dir + self.save_name)
| 9,219 | 49.382514 | 137 | py |
ADaPTION | ADaPTION-master/python/caffe/quantization/qmf_check.py | '''
This script loads an already trained CNN and prepares the Qm.f notation for each layer. Weights and activation are considered.
This distribution is used by net_descriptor to build a new prototxt file to finetune the quantized weights and activations
List of functions, for further details see below
- forward_pass
- get_qmf
- activation
- weights
Author: Moritz Milde
Date: 03.11.2016
E-Mail: mmilde@ini.uzh.ch
'''
import numpy as np
import caffe
class distribute_bits():
def __init__(self):
self.caffe_root = '/home/moritz/Repositories/caffe_lp/'
self.model_dir = 'examples/low_precision/imagenet/models/'
self.weight_dir = '/media/moritz/Data/ILSVRC2015/pre_trained/'
self.n_bits = 16
def forward_pass(self):
'''
This function performs the forward pass to extract activations from network.
net is an instance of self, to prevent multiple forward passes which usually ends in a kernel crash
Input:
- self
.net_protoxt: holds the path to prototxt file (type: string)
.net_weights: holds the path to caffemodel file (type:string)
Output:
- self.net: caffe instance of network which was forward passed
net is used later to extract activation and propose Qm.f notation
'''
self.net = caffe.Net(self.net_prototxt, self.net_weights, caffe.TEST)
self.net.forward()
def get_qmf(self, x, key=None, debug=False):
'''
This function estimates the minimum number of integer bits (m) to represent the largest number
in either activation or weights.
Input:
- x: current blob flattened, e.g. blob.data.flatten() for activation or
net.params[key][1].data.flatten() for weights (type: caffe blob)
- key: Identification key of the current layer. Only used for debugging (type: string)
- debug: Flag to turn printing of helpful information on and off (type: bool)
Output:
- m: Number of bits needed to represent integer part of maximum weight/activation value (type: int)
- f: Number of bits available to represent fractional part after m was estimated (type: int)
'''
m = 0
while np.max(x) > 2 ** m:
if m > self.n_bits - 1:
break
m += 1
f = self.n_bits - m
if debug:
print 'Layer ' + str(key) + ': ' 'Max: ' + str(np.max(x))
print 'Layer ' + str(key) + ': ' 'Min: ' + str(np.min(x[np.nonzero(x)]))
return m, f
def activation(self, net_name, n_bits=None, load_mode='high_precision', threshold=0.1,
caffe_root=None, model_dir=None,
weight_dir=None, debug=False):
'''
This function distributes a given amount of bits optimally between integer and fractional part of fixed point number
based on I) the minimum number of bits required to represent the biggest number in activation, e.g. integer part and
on II) the percentage of values we would loose with a given m.
Input:
- net_name: A string which refer to the network, e.g. VGG16 or GoogleNet (type: string)
- n_bits: Number of available bits, e.g. 16. Default is 16 (type: int)
- load_mode: A flag to select the right layers. The keys differ between high and low precision
can either be 'high_precision' or 'low_precision'. Default is 'high_precision'.
low_precision should only be used if weights/activations of a network trained in low_precision
should be qunatized further a smaller number of bits (type: string)
- threshold: Threshold regulating how many parameters we allow to be dropped (0.1 == 10 %)
with a given number if integer bits, before we fix the Qm.f
- caffe_root: Path to your caffe_lp folder (type: string)
- model_dir: Relative path from caffe_root to model directory (where .prototxt files are located). This is usually
examples/low_precision/imagenet/models/
Please change accordingly! (type: string)
- weight_dir Path where you want save the .caffemodel files, e.g. on your HDD (type: string)
- debug: Flag to turn printing of helpful information on and off (type: bool)
'''
if model_dir is not None:
self.model_dir = model_dir
if weight_dir is not None:
self.weight_dir = weight_dir
if caffe_root is not None:
self.caffe_root = caffe_root
if n_bits is not None:
self.n_bits = n_bits
self.net_prototxt = self.caffe_root + self.model_dir + net_name + '_deploy.prototxt'
# try:
# self.net_weights = self.weight_dir + net_name + '.caffemodel.h5'
# except RuntimeError:
self.net_weights = self.weight_dir + net_name + '/' + net_name + '_original.caffemodel'
if debug:
print 'Checking if network was already simulated... '
# if 'self.net' not in locals() or 'self.net' not in globals():
if not hasattr(self, 'net'):
if debug:
print 'No. Doing forward pass'
distribute_bits.forward_pass(self)
if debug:
print 'Forward pass done'
else:
if debug:
print 'Yes'
i = 0
if load_mode == 'high_precision':
select_key1 = 'conv'
select_key2 = 'fc'
# We have to substract 2 since we have to ignore split layers
bit_distribution = np.zeros((2, len(filter(lambda x: select_key1 in x, self.net.blobs.keys())) +
len(filter(lambda x: select_key2 in x, self.net.blobs.keys()))))
if debug:
print 'Bit distribution activation: {}'.format(np.shape(bit_distribution))
else:
select_key = 'act'
bit_distribution = np.zeros((2, len(filter(lambda x: select_key in x, self.net.blobs.keys()))))
if debug:
print 'Starting extracting activation distribution layer-wise'
print '-------------------'
for key, blob in self.net.blobs.items():
if load_mode == 'high_precision':
if select_key2 in key:
select_key = select_key2
else:
select_key = select_key1
if 'split' in key:
continue
if select_key in key: # VERIFY FOR HIGH PRECISION VGG16!!
# do all l's in layers have an activation?
# only act and pooling
# check indices low prec. should be index 1
# Calculate number of bits (Qm.f)
m, f = distribute_bits.get_qmf(self, blob.data.flatten(), key, debug)
assert (m + f) <= self.n_bits, 'Too many bits assigned!'
if debug:
print key
print 'Before optimaization:\nNumber of integer bits: {} \nNumber of fractional bits: {}'.format(m, f)
# If we already cover the entire dynamic range
# distribute the remaining bits randomly between m & f
while (m + f < self.n_bits):
coin_flip = np.random.rand()
if coin_flip > 0.5:
m += 1
else:
f += 1
cut = 0
while cut < threshold:
cut = np.sum(blob.data.flatten() > 2**m - 1) / float(len(blob.data.flatten()))
if m < 2:
break
m -= 1
if debug:
print 'While optimization:\nNumber of integer bits: {} \nPercentage of ignored parameters: {} %'.format(m, cut)
# Account for sign bit!!!
m += 1
assert m > 0, 'No sign bit reserved!'
f = self.n_bits - m
if debug:
print 'After optimaization:\nNumber of integer bits: {} \nNumber of fractional bits: {}'.format(m, f)
bit_distribution[0, i] = m
bit_distribution[1, i] = f
i += 1
if debug:
print 'Done: ' + str(key)
print '-------------------'
return bit_distribution, self.net
def weights(self, net_name, n_bits=None, load_mode='high_precision', threshold=0.1,
caffe_root=None, model_dir=None,
weight_dir=None, debug=False):
'''
This function distributes a given amount of bits optimally between integer and fractional part of fixed point number
based on I) the minimum number of bits required to represent the biggest number in the weights, e.g. integer part and
on II) the percentage of values we would loose with a given m.
Input:
- net_name: A string which refer to the network, e.g. VGG16 or GoogleNet (type: string)
- n_bits: Number of available bits, e.g. 16. Default is 16 (type: int)
- load_mode: A flag to select the right layers. The keys differ between high and low precision
can either be 'high_precision' or 'low_precision'. Default is 'high_precision'.
low_precision should only be used if weights/activations of a network trained in low_precision
should be qunatized further a smaller number of bits (type: string)
- threshold: Threshold regulating how many parameters we allow to be dropped (0.1 == 10 %)
with a given number if integer bits, before we fix the Qm.f
- caffe_root: Path to your caffe_lp folder (type: string)
- model_dir: Relative path from caffe_root to model directory (where .prototxt files are located). This is usually
examples/low_precision/imagenet/models/
Please change accordingly! (type: string)
- weight_dir Path where you want save the .caffemodel files, e.g. on your HDD (type: string)
- debug: Flag to turn printing of helpful information on and off (type: bool)
'''
if model_dir is not None:
self.model_dir = model_dir
if weight_dir is not None:
self.weight_dir = weight_dir
if caffe_root is not None:
self.caffe_root = caffe_root
if n_bits is not None:
self.n_bits = n_bits
self.net_prototxt = self.caffe_root + self.model_dir + net_name + '_deploy.prototxt'
# check if h5 or not??
self.net_weights = self.weight_dir + net_name + '/' + net_name + '_original.caffemodel'
if debug:
print 'Checking if network was already simulated... '
# if 'self.net' not in locals() or 'self.net' not in globals():
if not hasattr(self, 'net'):
if debug:
print 'No. Doing forward pass'
distribute_bits.forward_pass(self)
if debug:
print 'Forward pass done'
else:
if debug:
print 'Yes!'
# Specify which images are loaded in one batch?
if load_mode == 'high_precision':
select_key1 = 'conv'
select_key2 = 'fc'
else:
select_key1 = 'conv_lp'
select_key2 = 'fc_lp'
i = 0
if debug:
print 'Starting extracting weight distribution layer-wise'
print '-------------------'
print self.net.blobs.keys()
bit_distribution = np.zeros((2, len(filter(lambda x: select_key1 in x, self.net.blobs.keys())) +
len(filter(lambda x: select_key2 in x, self.net.blobs.keys()))))
if debug:
print np.shape(bit_distribution)
# we have to substract 2 since normally the last fc layer splits into two accuracy layers
for key in self.net.blobs.keys():
if select_key1 in key or select_key2 in key: # VERIFY FOR HIGH PRECISION VGG16!!
# Caffe introduces split layer from the 1000 way classifier to Accurace layer and Softmax layer for example
# to not use these layer, since they also contain a key we have to explicitely skip these layers
if 'split' in key:
continue
# 0 HP Weights, 1 LP Weights, 2 HP Biases, 3 KP Biases
# Calculate number of bits (Qm.f)
m, f = distribute_bits.get_qmf(self, self.net.params[key][1].data.flatten(), key, debug)
assert (m + f) <= self.n_bits, 'Too many bits assigned!'
if debug:
print key
print 'Before optimaization:\nNumber of integer bits: {} \nNumber of fractional bits: {}'.format(m, f)
# If we already covert the entire dynamic range
# distribute the remaining bits randomly between m & f
while (m + f < self.n_bits):
coin_flip = np.random.rand()
if coin_flip > 0.5:
m += 1
else:
f += 1
cut = 0
while cut < threshold:
cut = np.sum(self.net.params[key][1].data.flatten() > 2**m - 1) / float(len(self.net.params[key][1].data.flatten()))
if m < 2:
break
m -= 1
if debug:
print 'While optimization:\nNumber of integer bits: {} \nPercentage of ignored parameters: {} %'.format(m, cut)
m += 1
assert m > 0, 'No sign bit reserved!'
f = self.n_bits - m
if debug:
print 'After optimaization:\nNumber of integer bits: {} \nNumber of fractional bits: {}'.format(m, f)
bit_distribution[0, i] = m
bit_distribution[1, i] = f
i += 1
if debug:
print 'Done: ' + str(key)
print '-------------------'
return bit_distribution, self.net
| 14,568 | 48.386441 | 136 | py |
ADaPTION | ADaPTION-master/python/caffe/quantization/net_descriptor.py | '''
This script reads out a given prototxt file to extract the network layout
Based on this network layout we create a new prototxt for either training or testing
List of functions, for further details see below
- get_model
- extract
- create
Author: Moritz Milde
Date: 02.11.2016
E-Mail: mmilde@ini.uzh.ch
'''
import numpy as np
import caffe
import collections as c
from caffe.proto import caffe_pb2
from google.protobuf import text_format
class net_prototxt():
def __init__(self):
self.caffe_root = '/home/moritz/Repositories/caffe_lp/'
self.model_dir = 'examples/low_precision/imagenet/models/'
self.weight_dir = '/media/moritz/Data/ILSVRC/pre_trained/'
self.layer_dir = 'examples/create_prototxt/layers/'
self.save_dir = self.caffe_root + 'examples/low_precision/imagenet/models/'
def get_model(self, prototxt, caffemodel):
'''
This function initialize a given network based on prototxt file and caffemodel file
Input:
- prototxt: holds the path to prototxt file (type: string)
- caffemodel holds the path to caffemodel file (type: string)
Output:
- model: Dictonary which holds all information present in the prototxt, such as
kernel_size, stride, num_outputs etc. For further detail see extract() with debug active
(type: dict)
'''
model = caffe.Net(prototxt, caffemodel, caffe.TEST)
model_protobuf = caffe_pb2.NetParameter()
text_format.Merge(open(prototxt).read(), model_protobuf)
return {'model': (model, model_protobuf), 'val_fn': model.forward_all}
def extract(self, net_name, mode='deploy',
model=None, stride_conv=1, pad=0,
caffe_root=None, model_dir=None, weight_dir=None, debug=False):
'''
This function extracts the network structure from a given prototxt file and creates
a net_descriptor which is used by create() to create a new protoxt file
Input:
- net_name: A string which refer to the network, e.g. VGG16 or GoogleNet (type: string)
- mode: The mode the network should be operated in. Either 'deploy' for testing only
or 'train' to also be able to finetune the net. Default: 'deploy' (type: string)
- model: The caffe object which hold the current model. If not specified this function will
initilize the network.
- stride_conv: Default stride parameter is 1, in case a prototxt did not specify the stride, since
caffe's default stride is 1. (type: int)
- pad: Default pad parameter is 0, in cas a prototxt did not specify the stride, since caffe's
defaul pad is 0. (type: int)
- caffe_root: Path to your caffe_lp folder (type: string)
- model_dir: Relative path from caffe_root to model directory (where .prototxt files are located). This is usually
examples/low_precision/imagenet/models/
Please change accordingly! (type: string)
- weight_dir: Path where you want save the .caffemodel files, e.g. on your HDD (type: string)
- debug: Flag to turn printing of helpful information on and off (type: bool)
Output:
- net_descriptor: List of strings where each entry is one layer of the network with its specific parameter (type: List)
Example:
iet_descriptor = ['64C3S1p1', 'A', 'ReLU', '64C3S1p1', 'A', 'ReLU', '2P2',
'128C3S1p1', 'A', 'ReLU', '128C3S1p1', 'A', 'ReLU', '2P2',
'256C3S1p1', 'A', 'ReLU', '256C3S1p1', 'A', 'ReLU', '256C3S1p1', 'A', 'ReLU', '2P2',
'512C3S1p1', 'A', 'ReLU', '512C3S1p1', 'A', 'ReLU', '512C3S1p1', 'A', 'ReLU', '2P2',
'512C3S1p1', 'A', 'ReLU', '512C3S1p1', 'A', 'ReLU', '512C3S1p1', 'A', 'ReLU', '2P2',
'4096F', 'A', 'ReLU', 'D5',
'4096F', 'A', 'ReLU', 'D5',
'1000F',
'Accuracy', 'loss']
'''
if model_dir is not None:
self.model_dir = model_dir
if weight_dir is not None:
self.weight_dir = weight_dir
if caffe_root is not None:
self.caffe_root = caffe_root
prototxt = self.caffe_root + self.model_dir + net_name + '_deploy.prototxt'
# check if h5 or not??
net_weights = self.weight_dir + net_name + '/' + net_name + '.caffemodel'
# Check if model is specified, e.g. already initiated by qmf_check()
# If not specified model will be newly initilaized
if model is None:
model = net_prototxt.get_model(self, prototxt, net_weights)
else:
model_protobuf = caffe_pb2.NetParameter()
text_format.Merge(open(prototxt).read(), model_protobuf)
model = {'model': (model, model_protobuf)}
caffe_model = model['model'][0]
caffe_layers = model['model'][1].layer
self.net_descriptor = []
for (layer_num, layer) in enumerate(caffe_layers):
if debug:
print 'Layer type: {}'.format(layer)
if layer.type == 'Convolution':
p = layer.convolution_param
print 'Type: {}'.format(layer.type)
print 'Pad: {}'.format(p.pad._values[0])
print 'Stride {}'.format(p.stride._values[0])
print 'Kernel size: {}'.format(p.kernel_size._values[0])
print 'Output Channels {}'.format(p.num_output)
print '----------------------'
if layer.type == 'Pooling':
p = layer.pooling_param
print 'Type: {}'.format(layer.type)
print 'Kernel size: {}'.format(p.kernel_size)
print 'Stride: {}'.format(p.stride)
print '----------------------'
if layer.type == 'Dropout':
p = layer.dropout_param
print 'Type: {}'.format(layer.type)
print 'Dropout ratio: {}'.format(p.dropout_ratio)
print '----------------------'
if 'Conv' in layer.type or 'LPConv' in layer.type:
p = layer.convolution_param
layer_output = str(p.num_output)
layer_type = 'C'
if not p.stride:
layer_stride = 'S' + str(stride_conv)
else:
layer_stride = 'S' + str(p.stride._values[0])
if not p.pad:
layer_pad = 'p' + str(pad)
else:
layer_pad = 'p' + str(p.pad._values[0])
layer_kernel = str(p.kernel_size._values[0])
layer_descriptor = layer_output + layer_type + \
layer_kernel + layer_stride + layer_pad
# 2P2 POOLING
elif layer.type == 'Pooling':
p = layer.pooling_param
layer_type = 'P'
layer_kernel = str(p.kernel_size)
layer_stride = str(p.stride)
layer_descriptor = layer_kernel + layer_type + layer_stride
elif 'Drop' in layer.type:
p = layer.dropout_param
layer_type = 'D'
layer_ratio = str(int(p.dropout_ratio * 10))
layer_descriptor = layer_type + layer_ratio
elif 'Inner' in layer.type or 'LPInner' in layer.type:
p = layer.inner_product_param
layer_type = 'F'
layer_output = str(p.num_output)
layer_descriptor = layer_output + layer_type
elif layer.type == 'ReLU':
layer_type = 'ReLU'
layer_descriptor = layer_type
elif layer.type == 'LRN':
layer_type = 'norm'
layer_descriptor = layer_type
elif layer.type == 'Accuracy':
p = layer.accuracy_param
layer_type = 'Accuracy'
if p.top_k == 5:
continue
layer_descriptor = layer_type
else:
layer_descriptor = ''
continue
try:
self.net_descriptor.append(layer_descriptor)
except UnboundLocalError:
pass
try:
if layer_type == 'C':
self.net_descriptor.append('A')
elif layer_type == 'F' and p.num_output > 1001:
self.net_descriptor.append('A')
except UnboundLocalError:
pass
if layer_type == 'Accuracy':
if mode == 'train':
self.net_descriptor.append('loss')
return self.net_descriptor
def create(self, net_name, net_descriptor, bit_distribution_weights=None, bit_distribution_act=None, scale=True,
init_method='xavier', lp=True, deploy=False, visualize=False, round_bias='false', rounding_scheme=None,
caffe_root=None, model_dir=None, layer_dir=None, save_dir=None, debug=False):
'''
This function will create a prototxt file based on the network layout extracted from a pre defined caffemodel
using extract(). The layer-wise Qm.f notation provided by qmf_check() is used to have layer-specific Qm.f rounding
Input:
- net_name: A string which refer to the network, e.g. VGG16 or GoogleNet (type: string)
- net_descriptor: List of strings where each entry is one layer of the network with its specific parameter (type: List)
Example:
net_descriptor = ['64C3S1p1', 'A', 'ReLU', '64C3S1p1', 'A', 'ReLU', '2P2',
'128C3S1p1', 'A', 'ReLU', '128C3S1p1', 'A', 'ReLU', '2P2',
'256C3S1p1', 'A', 'ReLU', '256C3S1p1', 'A', 'ReLU', '256C3S1p1', 'A', 'ReLU', '2P2',
'512C3S1p1', 'A', 'ReLU', '512C3S1p1', 'A', 'ReLU', '512C3S1p1', 'A', 'ReLU', '2P2',
'512C3S1p1', 'A', 'ReLU', '512C3S1p1', 'A', 'ReLU', '512C3S1p1', 'A', 'ReLU', '2P2',
'4096F', 'A', 'ReLU', 'D5',
'4096F', 'A', 'ReLU', 'D5',
'1000F',
'Accuracy', 'loss']
- bit_distribution_weights: Numpy array specifying for each layer the Qm.f notation for the weights (type: numpy.ndarray)
- bit_distribution_act: Numpy array specifying for each layer the Qm.f notation for the activation (type: numpy.ndarray)
Both distribution can also be a [2, 1] numpy array. This will cause a global Qm.f notation\
- scale: Flag to include scaling parameter in the prototxt. This factor normalize the the input image to
range between 0 and 1. This is especially for low precision important, since otherwise the
input already saturates at the max value of a given fixed point. Default 'True' (type: bool)
- init_method: Weight initlialization method if deploy is false. Currently 'gaussian' and 'xavier' supported
Recommended init_method is 'xavier'
- lp: Flag specifying if network should be created using low precision layers.
Default 'True' (type: bool)
- deploy: Flag specifying if network should be only use for testing. Default 'False'
If 'False' network can be trained/finetuned. (type: bool)
- visualize: Flag if network is used to draw network schematics. Can be ignored! Default 'False'
(type: bool)
- round_bias: Flag if biases should also be rounded to specific Qm.f notation. Currently not supported!
Default 'False' (type: bool)
- rounding_scheme: Flag to either round parameters deterministically or stochastically. Default 'DETERMINISTIC'
possible 'STOCHASTIC'. (type: string)
- caffe_root: Path to your caffe_lp folder (type: string)
- model_dir: Relative path from caffe_root to model directory (where .prototxt files are located).
This is usually 'examples/low_precision/imagenet/models/'
Please change accordingly! (type: string)
- layer_dir: Path to layer_base and header_base files.
Default $caffe_root/examples/create_prototxt/layers (type: string)
- save_dir: Path where new created prototxt should be saved.
` Default $caffe_root/examples/low_precision/imagenet/models/ (type: string)
- debug: Flag to turn printing of helpful information on and off (type: bool)
Output:
- prototxt: Prototxt file (network description) is written to save_dir
'''
# This function should either call or execute the create_prototxt
# script
if caffe_root is not None:
self.caffe_root = caffe_root
if layer_dir is not None:
self.layer_dir = layer_dir
if model_dir is not None:
self.model_dir = model_dir
if save_dir is not None:
self.save_dir = save_dir
if rounding_scheme is not None:
self.rounding_scheme = rounding_scheme
else:
self.rounding_scheme = 'DETERMINISTIC'
self.net_descriptor = net_descriptor
if not lp:
for i, j in enumerate(self.net_descriptor):
if j == 'A':
self.net_descriptor.pop(i)
layer = c.namedtuple('layer', ['name', 'name_old' 'type', 'bottom', 'top', 'counter', 'bd', 'ad', 'kernel', 'group',
'stride', 'pad', 'bias', 'output', 'pool_size', 'pool_type', 'round_bias', 'dropout_rate'])
# Perform layerwise assignment
layer.round_bias = round_bias
layer.counter = 1
layer.name_old = 'data'
if lp:
assert bit_distribution_act is not None, 'Please specify the desired Qm.f notation.'
if deploy:
filename = '%s_%i_bit_deploy.prototxt' % (
net_name, bit_distribution_weights[0, 0] + bit_distribution_weights[1, 0])
filename = 'LP_' + filename
if visualize:
filename = '%s_%i_bit_vis.prototxt' % (
net_name, bit_distribution_weights[0, 0] + bit_distribution_weights[1, 0])
filename = 'LP_' + filename
else:
filename = '%s_%i_bit_train.prototxt' % (
net_name, bit_distribution_weights[0, 0] + bit_distribution_weights[1, 0])
filename = 'LP_' + filename
else:
if deploy:
filename = '%s_deploy.prototxt' % (net_name)
if visualize:
filename = '%s_vis.prototxt' % (net_name)
else:
filename = '%s_train.prototxt' % (net_name)
if debug:
print 'Generating ' + filename
weight_counter = 0
act_counter = 0
for cLayer in self.net_descriptor:
if lp:
if np.size(bit_distribution_weights, 1) > 1:
if cLayer == 'A':
# Set bit precision of Conv and ReLUs
layer.bd = bit_distribution_act[0, act_counter]
layer.ad = bit_distribution_act[1, act_counter]
act_counter += 1
elif 'C' in cLayer or 'F' in cLayer:
# Set bit precision of Conv and ReLUs
layer.bd = bit_distribution_weights[0, weight_counter]
layer.ad = bit_distribution_weights[1, weight_counter]
weight_counter += 1
else:
layer.bd = bit_distribution_weights[0, 0]
layer.ad = bit_distribution_weights[1, 0]
if layer.counter < 2:
layer_base = open(self.caffe_root + self.layer_dir + 'layer_base.prototxt', 'wr')
else:
layer_base = open(self.caffe_root + self.layer_dir + 'layer_base.prototxt', 'a')
if 'C' in cLayer:
# print 'Convolution'
layer.name = 'conv'
layer.type = 'Convolution'
layer.output = cLayer.partition("C")[0]
layer.kernel = cLayer.partition("C")[2].partition("S")[0]
layer.stride = cLayer.partition("S")[2][0]
if 'p' in cLayer:
layer.pad = cLayer.partition("S")[2].partition("p")[2]
else:
layer.pad = 0
if deploy:
if lp:
layer.name += '_lp'
layer.type = 'LPConvolution'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' }\n',
' lpfp_param {\n', ' bd: %i\n' % (layer.bd),
' ad: %i\n' % (layer.ad),
' round_bias: %s\n' % (layer.round_bias),
' rounding_scheme: %s\n' % (self.rounding_scheme), ' }\n',
' convolution_param {\n', ' num_output: %s\n' % (layer.output), ' stride: %s\n' % (
layer.stride), ' kernel_size: %s\n' % (layer.kernel), ' pad: %s\n' % (layer.pad),
' }\n',
'}\n']
else:
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' }\n',
' convolution_param {\n', ' num_output: %s\n' % (
layer.output), ' stride: %s\n' % (layer.stride),
' kernel_size: %s\n' % (
layer.kernel), ' pad: %s\n' % (layer.pad),
' }\n',
'}\n']
else:
if init_method == 'gaussian':
if lp:
layer.name += '_lp'
layer.type = 'LPConvolution'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' decay_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' decay_mult: 0\n', ' }\n',
' lpfp_param {\n', ' bd: %i\n' % (layer.bd),
' ad: %i\n' % (layer.ad),
' round_bias: %s\n' % (layer.round_bias),
' rounding_scheme: %s\n' % (self.rounding_scheme), ' }\n',
' convolution_param {\n', ' num_output: %s\n' % (layer.output), ' stride: %s\n' % (
layer.stride), ' kernel_size: %s\n' % (layer.kernel),
' weight_filler {\n', ' type: "gaussian"\n', ' std: 0.01\n', ' }\n',
' bias_filler {\n', ' type: "constant"\n', ' value: 0.0\n', ' }\n',
' }\n',
'}\n']
else:
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' decay_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' decay_mult: 0\n', ' }\n',
' convolution_param {\n', ' num_output: %s\n' % (
layer.output), ' stride: %s\n' % (layer.stride),
' kernel_size: %s\n' % (
layer.kernel), ' pad: %s\n' % (layer.pad),
' weight_filler {\n', ' type: "gaussian"\n', ' std: 0.01\n', ' }\n',
' bias_filler {\n', ' type: "constant"\n', ' value: 0.0\n', ' }\n',
' }\n',
'}\n']
if init_method == 'xavier':
if lp:
layer.name += '_lp'
layer.type = 'LPConvolution'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' decay_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' decay_mult: 0\n', ' }\n',
' lpfp_param {\n', ' bd: %i\n' % (layer.bd),
' ad: %i\n' % (layer.ad),
' round_bias: %s\n' % (layer.round_bias),
' rounding_scheme: %s\n' % (self.rounding_scheme), ' }\n',
' convolution_param {\n', ' num_output: %s\n' % (layer.output), ' stride: %s\n' % (
layer.stride), ' kernel_size: %s\n' % (layer.kernel), ' pad: %s\n' % (layer.pad),
' weight_filler {\n', ' type: "xavier"\n', ' }\n',
' bias_filler {\n', ' type: "constant"\n', ' value: 0.0\n', ' }\n',
' }\n',
'}\n']
else:
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' decay_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' decay_mult: 0\n', ' }\n',
' convolution_param {\n', ' num_output: %s\n' % (layer.output), ' stride: %s\n' % (
layer.stride), ' kernel_size: %s\n' % (layer.kernel), ' pad: %s\n' % (layer.pad),
' weight_filler {\n', ' type: "xavier"\n', ' }\n',
' bias_filler {\n', ' type: "constant"\n', ' value: 0.0\n', ' }\n',
' }\n',
'}\n']
layer_base.writelines(lines_to_write)
if cLayer == 'A':
# print 'Activation'
layer.name = 'act'
layer.type = 'Act'
if lp:
layer.name += '_lp'
layer.type = 'LPAct'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' lpfp_param {\n', ' bd: %i\n' % (layer.bd),
' ad: %i\n' % (layer.ad),
' round_bias: %s\n' % (layer.round_bias),
' rounding_scheme: %s\n' % (self.rounding_scheme), ' }\n',
'}\n']
layer_base.writelines(lines_to_write)
if cLayer == 'ReLU':
# print 'ReLU'
if lp:
layer.name = 'relu'
layer.type = 'ReLU'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (
layer.name_old), ' top: "%s"\n' % (layer.name_old),
'}\n']
else:
layer.name = 'relu'
layer.type = 'ReLU'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (
layer.name_old), ' top: "%s"\n' % (layer.name_old),
'}\n']
layer_base.writelines(lines_to_write)
if 'P' in cLayer:
# print 'Pooling'
layer.name = 'pool'
layer.type = 'Pooling'
layer.pool_type = 'MAX'
layer.pool_size = cLayer.partition("P")[0]
layer.stride = cLayer.partition("P")[2]
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' pooling_param {\n', ' pool: %s\n' % (layer.pool_type), ' kernel_size: %s\n' % (
layer.pool_size), ' stride: %s\n' % (layer.stride),
' }\n',
'}\n']
layer_base.writelines(lines_to_write)
if cLayer == 'RoI':
layer.name = 'roi'
layer.type = 'ROIPooling'
roi_width = 7
roi_height = 7
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' bottom: "rois"\n', ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' roi_pooling_param {\n', ' pooled_w: %i\n' % (
roi_width), ' pooled_h: %i\n' % (roi_height),
' spatial_scale: 0.625\n',
' }\n',
'}\n']
layer_base.writelines(lines_to_write)
if 'F' in cLayer:
# print 'Fully Connected'
layer.name = 'fc'
layer.type = 'InnerProduct'
layer.output = cLayer.partition("F")[0]
if deploy:
if lp:
layer.name += '_lp'
layer.type = 'LPInnerProduct'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' }\n',
' lpfp_param {\n', ' bd: %i\n' % (layer.bd),
' ad: %i\n' % (layer.ad),
' round_bias: %s\n' % (layer.round_bias),
' rounding_scheme: %s\n' % (self.rounding_scheme), ' }\n',
' inner_product_param {\n', ' num_output: %s\n' % (
layer.output),
' }\n',
'}\n']
else:
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' }\n',
' inner_product_param {\n', ' num_output: %s\n' % (
layer.output),
' }\n',
'}\n']
else:
if init_method == 'gaussian':
if lp:
layer.name += '_lp'
layer.type = 'LPInnerProduct'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' decay_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' decay_mult: 0\n', ' }\n',
' lpfp_param {\n', ' bd: %i\n' % (layer.bd),
' ad: %i\n' % (layer.ad),
' round_bias: %s\n' % (layer.round_bias),
' rounding_scheme: %s\n' % (self.rounding_scheme), ' }\n',
' inner_product_param {\n', ' num_output: %s\n' % (
layer.output),
' weight_filler {\n', ' type: "gaussian"\n', ' std: 0.005\n', ' }\n',
' bias_filler {\n', ' type: "constant"\n', ' value: 0.1\n', ' }\n',
' }\n',
'}\n']
else:
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' decay_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' decay_mult: 0\n', ' }\n',
' inner_product_param {\n', ' num_output: %s\n' % (
layer.output),
' weight_filler {\n', ' type: "gaussian"\n', ' std: 0.005\n', ' }\n',
' bias_filler {\n', ' type: "constant"\n', ' value: 0.1\n', ' }\n',
' }\n',
'}\n']
if init_method == 'xavier':
if lp:
layer.name += '_lp'
layer.type = 'LPInnerProduct'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' decay_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' decay_mult: 0\n', ' }\n',
' lpfp_param {\n', ' bd: %i\n' % (layer.bd),
' ad: %i\n' % (layer.ad),
' round_bias: %s\n' % (layer.round_bias),
' rounding_scheme: %s\n' % (self.rounding_scheme), ' }\n',
' inner_product_param {\n', ' num_output: %s\n' % (
layer.output),
' weight_filler {\n', ' type: "xavier"\n', ' }\n',
' bias_filler {\n', ' type: "constant"\n', ' value: 0.1\n', ' }\n',
' }\n',
'}\n']
else:
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 1\n', ' decay_mult: 1\n', ' }\n',
' param {\n', ' lr_mult: 2\n', ' decay_mult: 0\n', ' }\n',
' inner_product_param {\n', ' num_output: %s\n' % (
layer.output),
' weight_filler {\n', ' type: "xavier"\n', ' }\n',
' bias_filler {\n', ' type: "constant"\n', ' value: 0.1\n', ' }\n',
' }\n',
'}\n']
layer_base.writelines(lines_to_write)
if 'D' in cLayer:
# print 'Dropout'
layer.name = 'drop'
layer.type = 'Dropout'
layer.dropout_rate = cLayer.partition("D")[2]
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (
layer.name_old), ' top: "%s"\n' % (layer.name_old),
' dropout_param {\n', ' dropout_ratio: 0.%s\n' % (
layer.dropout_rate), ' }\n',
'}\n']
layer_base.writelines(lines_to_write)
if cLayer == 'Accuracy':
# print 'Accuracy'
layer.name = 'accuracy'
layer.type = 'Accuracy'
lines_to_write = ['layer {\n', ' name: "%s"\n' % (layer.name), ' type: "%s"\n' % (layer.type), ' bottom: "%s"\n' % (layer.name_old),
' bottom: "label"\n', ' top: "%s"\n' % (
layer.name),
' include {\n', ' phase: TEST\n', ' }\n',
'}\n']
if deploy:
layer_name = 'accuracy_top5'
lines_to_write = ['layer {\n', ' name: "%s"\n' % (layer.name), ' type: "%s"\n' % (layer.type), ' bottom: "%s"\n' % (layer.name_old),
' bottom: "label"\n', ' top: "%s"\n' % (
layer.name),
' include {\n', ' phase: TEST\n', ' }\n',
'}\n'
'layer {\n', ' name: "%s"\n' % (layer_name), ' type: "%s"\n' % (
layer.type), ' bottom: "%s"\n' % (layer.name_old),
' bottom: "label"\n', ' top: "%s"\n' % (
layer_name),
' include {\n', ' phase: TEST\n', ' }\n',
' accuracy_param {\n', ' top_k: 5\n', ' }\n',
'}\n']
layer_base.writelines(lines_to_write)
if cLayer == 'loss':
# print 'Loss'
layer.name = 'loss'
layer.type = 'SoftmaxWithLoss'
lines_to_write = ['layer {\n', ' name: "%s"\n' % (layer.name), ' type: "%s"\n' % (layer.type), ' bottom: "%s"\n' % (layer.name_old),
' bottom: "label"\n', ' top: "%s"\n' % (
layer.name),
'}\n']
layer_base.writelines(lines_to_write)
if cLayer == 'norm':
layer.name = 'norm'
layer.type = 'LRN'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' lrn_param {\n', ' local_size: 5\n', ' alpha: 0.0001\n', ' beta: 0.75\n', ' }\n',
'}\n']
layer_base.writelines(lines_to_write)
if cLayer == 'bnorm':
layer.name = 'bn'
layer.type = 'BatchNorm'
lines_to_write = ['layer {\n', ' name: "%s_%i"\n' % (layer.name, layer.counter), ' type: "%s"\n' % (layer.type),
' bottom: "%s"\n' % (layer.name_old), ' top: "%s_%i"\n' % (
layer.name, layer.counter),
' param {\n', ' lr_mult: 0\n', ' }\n',
' param {\n', ' lr_mult: 0\n', ' }\n',
' param {\n', ' lr_mult: 0\n', ' }\n',
'}\n']
layer_base.writelines(lines_to_write)
update = True
if cLayer == "ReLU":
update = False
if cLayer == "D5":
update = False
if cLayer == "Accuracy":
update = False
if cLayer == "loss":
update = False
if update:
layer.name_old = layer.name + '_' + str(layer.counter)
layer.counter += 1
layer_base.close()
# To include the standard header, which handles directories and the input data
# we need to write first the header and afterwards the layer_basis into
# new prototxt
if lp:
if deploy:
header = open(self.caffe_root + self.layer_dir + 'header_deploy.prototxt', 'r')
if not scale:
header = open(self.caffe_root + self.layer_dir + 'header_deploy_noscale.prototxt', 'r')
if visualize:
header = open(self.caffe_root + self.layer_dir + 'header_vis.prototxt', 'r')
if not scale:
header = open(self.caffe_root + self.layer_dir + 'header_vis_noscale.prototxt', 'r')
else:
header = open(self.caffe_root + self.layer_dir + 'header.prototxt', 'r')
if not scale:
header = open(self.caffe_root + self.layer_dir + 'header_noscale.prototxt', 'r')
else:
if deploy:
header = open(
self.caffe_root + self.layer_dir + 'header_deploy_noscale.prototxt', 'r')
if scale:
header = open(self.caffe_root + self.layer_dir + 'header_deploy.prototxt', 'r')
if visualize:
header = open(
self.caffe_root + self.layer_dir + 'header_vis_noscale.prototxt', 'r')
if scale:
header = open(self.caffe_root + self.layer_dir + 'header_vis.prototxt', 'r')
else:
header = open(self.caffe_root + self.layer_dir + 'header_noscale.prototxt', 'r')
if scale:
header = open(self.caffe_root + self.layer_dir + 'header.prototxt', 'r')
base = open(self.caffe_root + self.layer_dir + 'layer_base.prototxt', 'r')
net = open(self.save_dir + filename, "w")
net.write('name: "{}"\n'.format(net_name))
net.write(header.read() + '\n')
net.write(base.read())
header.close()
net.close()
| 42,894 | 58.825662 | 155 | py |
ADaPTION | ADaPTION-master/scripts/cpp_lint.py | #!/usr/bin/python2
#
# Copyright (c) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Does google-lint on c++ files.
The goal of this script is to identify places in the code that *may*
be in non-compliance with google style. It does not attempt to fix
up these problems -- the point is to educate. It does also not
attempt to find all problems, or to ensure that everything it does
find is legitimately a problem.
In particular, we can get very confused by /* and // inside strings!
We do a small hack, which is to ignore //'s with "'s after them on the
same line, but it is far from perfect (in either direction).
"""
import codecs
import copy
import getopt
import math # for log
import os
import re
import sre_compile
import string
import sys
import unicodedata
_USAGE = """
Syntax: cpp_lint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
[--counting=total|toplevel|detailed] [--root=subdir]
[--linelength=digits]
<file> [file] ...
The style guidelines this tries to follow are those in
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
Every problem is given a confidence score from 1-5, with 5 meaning we are
certain of the problem, and 1 meaning it could be a legitimate construct.
This will miss some errors, and is not a substitute for a code review.
To suppress false-positive errors of a certain category, add a
'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
suppresses errors of all categories on that line.
The files passed in will be linted; at least one file must be provided.
Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
extensions with the --extensions flag.
Flags:
output=vs7
By default, the output is formatted to ease emacs parsing. Visual Studio
compatible output (vs7) may also be used. Other formats are unsupported.
verbose=#
Specify a number 0-5 to restrict errors to certain verbosity levels.
filter=-x,+y,...
Specify a comma-separated list of category-filters to apply: only
error messages whose category names pass the filters will be printed.
(Category names are printed with the message and look like
"[whitespace/indent]".) Filters are evaluated left to right.
"-FOO" and "FOO" means "do not print categories that start with FOO".
"+FOO" means "do print categories that start with FOO".
Examples: --filter=-whitespace,+whitespace/braces
--filter=whitespace,runtime/printf,+runtime/printf_format
--filter=-,+build/include_what_you_use
To see a list of all the categories used in cpplint, pass no arg:
--filter=
counting=total|toplevel|detailed
The total number of errors found is always printed. If
'toplevel' is provided, then the count of errors in each of
the top-level categories like 'build' and 'whitespace' will
also be printed. If 'detailed' is provided, then a count
is provided for each category like 'build/class'.
root=subdir
The root directory used for deriving header guard CPP variable.
By default, the header guard CPP variable is calculated as the relative
path to the directory that contains .git, .hg, or .svn. When this flag
is specified, the relative path is calculated from the specified
directory. If the specified directory does not exist, this flag is
ignored.
Examples:
Assuing that src/.git exists, the header guard CPP variables for
src/chrome/browser/ui/browser.h are:
No flag => CHROME_BROWSER_UI_BROWSER_H_
--root=chrome => BROWSER_UI_BROWSER_H_
--root=chrome/browser => UI_BROWSER_H_
linelength=digits
This is the allowed line length for the project. The default value is
80 characters.
Examples:
--linelength=120
extensions=extension,extension,...
The allowed file extensions that cpplint will check
Examples:
--extensions=hpp,cpp
"""
# We categorize each error message we print. Here are the categories.
# We want an explicit list so we can list them all in cpplint --filter=.
# If you add a new error message with a new category, add it to the list
# here! cpplint_unittest.py should tell you if you forget to do this.
_ERROR_CATEGORIES = [
'build/class',
'build/deprecated',
'build/endif_comment',
'build/explicit_make_pair',
'build/forward_decl',
'build/header_guard',
'build/include',
'build/include_alpha',
'build/include_dir',
'build/include_order',
'build/include_what_you_use',
'build/namespaces',
'build/printf_format',
'build/storage_class',
'caffe/alt_fn',
'caffe/data_layer_setup',
'caffe/random_fn',
'legal/copyright',
'readability/alt_tokens',
'readability/braces',
'readability/casting',
'readability/check',
'readability/constructors',
'readability/fn_size',
'readability/function',
'readability/multiline_comment',
'readability/multiline_string',
'readability/namespace',
'readability/nolint',
'readability/nul',
'readability/streams',
'readability/todo',
'readability/utf8',
'runtime/arrays',
'runtime/casting',
'runtime/explicit',
'runtime/int',
'runtime/init',
'runtime/invalid_increment',
'runtime/member_string_references',
'runtime/memset',
'runtime/operator',
'runtime/printf',
'runtime/printf_format',
'runtime/references',
'runtime/string',
'runtime/threadsafe_fn',
'runtime/vlog',
'whitespace/blank_line',
'whitespace/braces',
'whitespace/comma',
'whitespace/comments',
'whitespace/empty_conditional_body',
'whitespace/empty_loop_body',
'whitespace/end_of_line',
'whitespace/ending_newline',
'whitespace/forcolon',
'whitespace/indent',
'whitespace/line_length',
'whitespace/newline',
'whitespace/operators',
'whitespace/parens',
'whitespace/semicolon',
'whitespace/tab',
'whitespace/todo'
]
# The default state of the category filter. This is overrided by the --filter=
# flag. By default all errors are on, so only add here categories that should be
# off by default (i.e., categories that must be enabled by the --filter= flags).
# All entries here should start with a '-' or '+', as in the --filter= flag.
_DEFAULT_FILTERS = [
'-build/include_dir',
'-readability/todo',
]
# We used to check for high-bit characters, but after much discussion we
# decided those were OK, as long as they were in UTF-8 and didn't represent
# hard-coded international strings, which belong in a separate i18n file.
# C++ headers
_CPP_HEADERS = frozenset([
# Legacy
'algobase.h',
'algo.h',
'alloc.h',
'builtinbuf.h',
'bvector.h',
'complex.h',
'defalloc.h',
'deque.h',
'editbuf.h',
'fstream.h',
'function.h',
'hash_map',
'hash_map.h',
'hash_set',
'hash_set.h',
'hashtable.h',
'heap.h',
'indstream.h',
'iomanip.h',
'iostream.h',
'istream.h',
'iterator.h',
'list.h',
'map.h',
'multimap.h',
'multiset.h',
'ostream.h',
'pair.h',
'parsestream.h',
'pfstream.h',
'procbuf.h',
'pthread_alloc',
'pthread_alloc.h',
'rope',
'rope.h',
'ropeimpl.h',
'set.h',
'slist',
'slist.h',
'stack.h',
'stdiostream.h',
'stl_alloc.h',
'stl_relops.h',
'streambuf.h',
'stream.h',
'strfile.h',
'strstream.h',
'tempbuf.h',
'tree.h',
'type_traits.h',
'vector.h',
# 17.6.1.2 C++ library headers
'algorithm',
'array',
'atomic',
'bitset',
'chrono',
'codecvt',
'complex',
'condition_variable',
'deque',
'exception',
'forward_list',
'fstream',
'functional',
'future',
'initializer_list',
'iomanip',
'ios',
'iosfwd',
'iostream',
'istream',
'iterator',
'limits',
'list',
'locale',
'map',
'memory',
'mutex',
'new',
'numeric',
'ostream',
'queue',
'random',
'ratio',
'regex',
'set',
'sstream',
'stack',
'stdexcept',
'streambuf',
'string',
'strstream',
'system_error',
'thread',
'tuple',
'typeindex',
'typeinfo',
'type_traits',
'unordered_map',
'unordered_set',
'utility',
'valarray',
'vector',
# 17.6.1.2 C++ headers for C library facilities
'cassert',
'ccomplex',
'cctype',
'cerrno',
'cfenv',
'cfloat',
'cinttypes',
'ciso646',
'climits',
'clocale',
'cmath',
'csetjmp',
'csignal',
'cstdalign',
'cstdarg',
'cstdbool',
'cstddef',
'cstdint',
'cstdio',
'cstdlib',
'cstring',
'ctgmath',
'ctime',
'cuchar',
'cwchar',
'cwctype',
])
# Assertion macros. These are defined in base/logging.h and
# testing/base/gunit.h. Note that the _M versions need to come first
# for substring matching to work.
_CHECK_MACROS = [
'DCHECK', 'CHECK',
'EXPECT_TRUE_M', 'EXPECT_TRUE',
'ASSERT_TRUE_M', 'ASSERT_TRUE',
'EXPECT_FALSE_M', 'EXPECT_FALSE',
'ASSERT_FALSE_M', 'ASSERT_FALSE',
]
# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
('>=', 'GE'), ('>', 'GT'),
('<=', 'LE'), ('<', 'LT')]:
_CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
_CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
_CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
_CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
_CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
_CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
('>=', 'LT'), ('>', 'LE'),
('<=', 'GT'), ('<', 'GE')]:
_CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
_CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
_CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
_CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
# Alternative tokens and their replacements. For full list, see section 2.5
# Alternative tokens [lex.digraph] in the C++ standard.
#
# Digraphs (such as '%:') are not included here since it's a mess to
# match those on a word boundary.
_ALT_TOKEN_REPLACEMENT = {
'and': '&&',
'bitor': '|',
'or': '||',
'xor': '^',
'compl': '~',
'bitand': '&',
'and_eq': '&=',
'or_eq': '|=',
'xor_eq': '^=',
'not': '!',
'not_eq': '!='
}
# Compile regular expression that matches all the above keywords. The "[ =()]"
# bit is meant to avoid matching these keywords outside of boolean expressions.
#
# False positives include C-style multi-line comments and multi-line strings
# but those have always been troublesome for cpplint.
_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
# These constants define types of headers for use with
# _IncludeState.CheckNextIncludeOrder().
_C_SYS_HEADER = 1
_CPP_SYS_HEADER = 2
_LIKELY_MY_HEADER = 3
_POSSIBLE_MY_HEADER = 4
_OTHER_HEADER = 5
# These constants define the current inline assembly state
_NO_ASM = 0 # Outside of inline assembly block
_INSIDE_ASM = 1 # Inside inline assembly block
_END_ASM = 2 # Last line of inline assembly block
_BLOCK_ASM = 3 # The whole block is an inline assembly block
# Match start of assembly blocks
_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
r'(?:\s+(volatile|__volatile__))?'
r'\s*[{(]')
_regexp_compile_cache = {}
# Finds occurrences of NOLINT[_NEXT_LINE] or NOLINT[_NEXT_LINE](...).
_RE_SUPPRESSION = re.compile(r'\bNOLINT(_NEXT_LINE)?\b(\([^)]*\))?')
# {str, set(int)}: a map from error categories to sets of linenumbers
# on which those errors are expected and should be suppressed.
_error_suppressions = {}
# Finds Copyright.
_RE_COPYRIGHT = re.compile(r'Copyright')
# The root directory used for deriving header guard CPP variable.
# This is set by --root flag.
_root = None
# The allowed line length of files.
# This is set by --linelength flag.
_line_length = 80
# The allowed extensions for file names
# This is set by --extensions flag.
_valid_extensions = set(['cc', 'h', 'cpp', 'hpp', 'cu', 'cuh'])
def ParseNolintSuppressions(filename, raw_line, linenum, error):
"""Updates the global list of error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of the input file.
raw_line: str, the line of input text, with comments.
linenum: int, the number of the current line.
error: function, an error handler.
"""
# FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
matched = _RE_SUPPRESSION.search(raw_line)
if matched:
if matched.group(1) == '_NEXT_LINE':
linenum += 1
category = matched.group(2)
if category in (None, '(*)'): # => "suppress all"
_error_suppressions.setdefault(None, set()).add(linenum)
else:
if category.startswith('(') and category.endswith(')'):
category = category[1:-1]
if category in _ERROR_CATEGORIES:
_error_suppressions.setdefault(category, set()).add(linenum)
else:
error(filename, linenum, 'readability/nolint', 5,
'Unknown NOLINT error category: %s' % category)
def ResetNolintSuppressions():
"Resets the set of NOLINT suppressions to empty."
_error_suppressions.clear()
def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment.
"""
return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set()))
def Match(pattern, s):
"""Matches the string with the pattern, caching the compiled regexp."""
# The regexp compilation caching is inlined in both Match and Search for
# performance reasons; factoring it out into a separate function turns out
# to be noticeably expensive.
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].match(s)
def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s)
def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s)
class _IncludeState(dict):
"""Tracks line numbers for includes, and the order in which includes appear.
As a dict, an _IncludeState object serves as a mapping between include
filename and line number on which that file was included.
Call CheckNextIncludeOrder() once for each header in the file, passing
in the type constants defined above. Calls in an illegal order will
raise an _IncludeError with an appropriate error message.
"""
# self._section will move monotonically through this set. If it ever
# needs to move backwards, CheckNextIncludeOrder will raise an error.
_INITIAL_SECTION = 0
_MY_H_SECTION = 1
_C_SECTION = 2
_CPP_SECTION = 3
_OTHER_H_SECTION = 4
_TYPE_NAMES = {
_C_SYS_HEADER: 'C system header',
_CPP_SYS_HEADER: 'C++ system header',
_LIKELY_MY_HEADER: 'header this file implements',
_POSSIBLE_MY_HEADER: 'header this file may implement',
_OTHER_HEADER: 'other header',
}
_SECTION_NAMES = {
_INITIAL_SECTION: "... nothing. (This can't be an error.)",
_MY_H_SECTION: 'a header this file implements',
_C_SECTION: 'C system header',
_CPP_SECTION: 'C++ system header',
_OTHER_H_SECTION: 'other header',
}
def __init__(self):
dict.__init__(self)
self.ResetSection()
def ResetSection(self):
# The name of the current section.
self._section = self._INITIAL_SECTION
# The path of last found header.
self._last_header = ''
def SetLastHeader(self, header_path):
self._last_header = header_path
def CanonicalizeAlphabeticalOrder(self, header_path):
"""Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path.
"""
return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
"""Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order.
"""
# If previous section is different from current section, _last_header will
# be reset to empty string, so it's always less than current header.
#
# If previous line was a blank line, assume that the headers are
# intentionally sorted the way they are.
if (self._last_header > header_path and
not Match(r'^\s*$', clean_lines.elided[linenum - 1])):
return False
return True
def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong.
"""
error_message = ('Found %s after %s' %
(self._TYPE_NAMES[header_type],
self._SECTION_NAMES[self._section]))
last_section = self._section
if header_type == _C_SYS_HEADER:
if self._section <= self._C_SECTION:
self._section = self._C_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _CPP_SYS_HEADER:
if self._section <= self._CPP_SECTION:
self._section = self._CPP_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _LIKELY_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
self._section = self._OTHER_H_SECTION
elif header_type == _POSSIBLE_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
# This will always be the fallback because we're not sure
# enough that the header is associated with this file.
self._section = self._OTHER_H_SECTION
else:
assert header_type == _OTHER_HEADER
self._section = self._OTHER_H_SECTION
if last_section != self._section:
self._last_header = ''
return ''
class _CppLintState(object):
"""Maintains module-wide state.."""
def __init__(self):
self.verbose_level = 1 # global setting.
self.error_count = 0 # global count of reported errors
# filters to apply when emitting error messages
self.filters = _DEFAULT_FILTERS[:]
self.counting = 'total' # In what way are we counting errors?
self.errors_by_category = {} # string to int dict storing error counts
# output format:
# "emacs" - format that emacs can parse (default)
# "vs7" - format that Microsoft Visual Studio 7 can parse
self.output_format = 'emacs'
def SetOutputFormat(self, output_format):
"""Sets the output format for errors."""
self.output_format = output_format
def SetVerboseLevel(self, level):
"""Sets the module's verbosity, and returns the previous setting."""
last_verbose_level = self.verbose_level
self.verbose_level = level
return last_verbose_level
def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style
def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
for filt in filters.split(','):
clean_filt = filt.strip()
if clean_filt:
self.filters.append(clean_filt)
for filt in self.filters:
if not (filt.startswith('+') or filt.startswith('-')):
raise ValueError('Every filter in --filters must start with + or -'
' (%s does not)' % filt)
def ResetErrorCounts(self):
"""Sets the module's error statistic back to zero."""
self.error_count = 0
self.errors_by_category = {}
def IncrementErrorCount(self, category):
"""Bumps the module's error statistic."""
self.error_count += 1
if self.counting in ('toplevel', 'detailed'):
if self.counting != 'detailed':
category = category.split('/')[0]
if category not in self.errors_by_category:
self.errors_by_category[category] = 0
self.errors_by_category[category] += 1
def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in self.errors_by_category.iteritems():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stderr.write('Total errors found: %d\n' % self.error_count)
_cpplint_state = _CppLintState()
def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format
def _SetOutputFormat(output_format):
"""Sets the module's output format."""
_cpplint_state.SetOutputFormat(output_format)
def _VerboseLevel():
"""Returns the module's verbosity setting."""
return _cpplint_state.verbose_level
def _SetVerboseLevel(level):
"""Sets the module's verbosity, and returns the previous setting."""
return _cpplint_state.SetVerboseLevel(level)
def _SetCountingStyle(level):
"""Sets the module's counting options."""
_cpplint_state.SetCountingStyle(level)
def _Filters():
"""Returns the module's list of output filters, as a list."""
return _cpplint_state.filters
def _SetFilters(filters):
"""Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.SetFilters(filters)
class _FunctionState(object):
"""Tracks current function name and the number of lines in its body."""
_NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
_TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
def __init__(self):
self.in_a_function = False
self.lines_in_function = 0
self.current_function = ''
def Begin(self, function_name):
"""Start analyzing function body.
Args:
function_name: The name of the function being tracked.
"""
self.in_a_function = True
self.lines_in_function = 0
self.current_function = function_name
def Count(self):
"""Count line in current function body."""
if self.in_a_function:
self.lines_in_function += 1
def Check(self, error, filename, linenum):
"""Report if too many lines in function body.
Args:
error: The function to call with any errors found.
filename: The name of the current file.
linenum: The number of the line to check.
"""
if Match(r'T(EST|est)', self.current_function):
base_trigger = self._TEST_TRIGGER
else:
base_trigger = self._NORMAL_TRIGGER
trigger = base_trigger * 2**_VerboseLevel()
if self.lines_in_function > trigger:
error_level = int(math.log(self.lines_in_function / base_trigger, 2))
# 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
if error_level > 5:
error_level = 5
error(filename, linenum, 'readability/fn_size', error_level,
'Small and focused functions are preferred:'
' %s has %d non-comment lines'
' (error triggered by exceeding %d lines).' % (
self.current_function, self.lines_in_function, trigger))
def End(self):
"""Stop analyzing function body."""
self.in_a_function = False
class _IncludeError(Exception):
"""Indicates a problem with the include order in a file."""
pass
class FileInfo:
"""Provides utility functions for filenames.
FileInfo provides easy access to the components of a file's path
relative to the project root.
"""
def __init__(self, filename):
self._filename = filename
def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/')
def RepositoryName(self):
"""FullName after removing the local path to the repository.
If we have a real absolute path name here we can try to do something smart:
detecting the root of the checkout and truncating /path/to/checkout from
the name so that we get header guards that don't include things like
"C:\Documents and Settings\..." or "/home/username/..." in them and thus
people on different computers who have checked the source out to different
locations won't see bogus errors.
"""
fullname = self.FullName()
if os.path.exists(fullname):
project_dir = os.path.dirname(fullname)
if os.path.exists(os.path.join(project_dir, ".svn")):
# If there's a .svn file in the current directory, we recursively look
# up the directory tree for the top of the SVN checkout
root_dir = project_dir
one_up_dir = os.path.dirname(root_dir)
while os.path.exists(os.path.join(one_up_dir, ".svn")):
root_dir = os.path.dirname(root_dir)
one_up_dir = os.path.dirname(one_up_dir)
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
# Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
# searching up from the current path.
root_dir = os.path.dirname(fullname)
while (root_dir != os.path.dirname(root_dir) and
not os.path.exists(os.path.join(root_dir, ".git")) and
not os.path.exists(os.path.join(root_dir, ".hg")) and
not os.path.exists(os.path.join(root_dir, ".svn"))):
root_dir = os.path.dirname(root_dir)
if (os.path.exists(os.path.join(root_dir, ".git")) or
os.path.exists(os.path.join(root_dir, ".hg")) or
os.path.exists(os.path.join(root_dir, ".svn"))):
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
# Don't know what to do; header guard warnings may be wrong...
return fullname
def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest)
def BaseName(self):
"""File base name - text after the final slash, before the final period."""
return self.Split()[1]
def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2]
def NoExtension(self):
"""File has no source file extension."""
return '/'.join(self.Split()[0:2])
def IsSource(self):
"""File has a source file extension."""
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
def _ShouldPrintError(category, confidence, linenum):
"""If confidence >= verbose, category passes filter and is not suppressed."""
# There are three ways we might decide not to print an error message:
# a "NOLINT(category)" comment appears in the source,
# the verbosity level isn't high enough, or the filters filter it out.
if IsErrorSuppressedByNolint(category, linenum):
return False
if confidence < _cpplint_state.verbose_level:
return False
is_filtered = False
for one_filter in _Filters():
if one_filter.startswith('-'):
if category.startswith(one_filter[1:]):
is_filtered = True
elif one_filter.startswith('+'):
if category.startswith(one_filter[1:]):
is_filtered = False
else:
assert False # should have been checked for in SetFilter.
if is_filtered:
return False
return True
def Error(filename, linenum, category, confidence, message):
"""Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message.
"""
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
elif _cpplint_state.output_format == 'eclipse':
sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
else:
sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
# Matches strings. Escape codes should already be removed by ESCAPES.
_RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
# Matches characters. Escape codes should already be removed by ESCAPES.
_RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
# Matches multi-line C++ comments.
# This RE is a little bit more complicated than one might expect, because we
# have to take care of space removals tools so we can handle comments inside
# statements better.
# The current rule is: We only clear spaces from both sides when we're at the
# end of the line. Otherwise, we try to remove spaces from the right side,
# if this doesn't work we try on left side but only if there's a non-character
# on the right.
_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
r"""(\s*/\*.*\*/\s*$|
/\*.*\*/\s+|
\s+/\*.*\*/(?=\W)|
/\*.*\*/)""", re.VERBOSE)
def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant.
"""
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
def CleanseRawStrings(raw_lines):
"""Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings.
"""
delimiter = None
lines_without_raw_strings = []
for line in raw_lines:
if delimiter:
# Inside a raw string, look for the end
end = line.find(delimiter)
if end >= 0:
# Found the end of the string, match leading space for this
# line and resume copying the original lines, and also insert
# a "" on the last line.
leading_space = Match(r'^(\s*)\S', line)
line = leading_space.group(1) + '""' + line[end + len(delimiter):]
delimiter = None
else:
# Haven't found the end yet, append a blank line.
line = ''
else:
# Look for beginning of a raw string.
# See 2.14.15 [lex.string] for syntax.
matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
if matched:
delimiter = ')' + matched.group(2) + '"'
end = matched.group(3).find(delimiter)
if end >= 0:
# Raw string ended on same line
line = (matched.group(1) + '""' +
matched.group(3)[end + len(delimiter):])
delimiter = None
else:
# Start of a multi-line raw string
line = matched.group(1) + '""'
lines_without_raw_strings.append(line)
# TODO(unknown): if delimiter is not None here, we might want to
# emit a warning for unterminated string.
return lines_without_raw_strings
def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return lineix
lineix += 1
return len(lines)
def FindNextMultiLineCommentEnd(lines, lineix):
"""We are inside a comment, find the end marker."""
while lineix < len(lines):
if lines[lineix].strip().endswith('*/'):
return lineix
lineix += 1
return len(lines)
def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '// dummy'
def RemoveMultiLineComments(filename, lines, error):
"""Removes multiline (c-style) comments from lines."""
lineix = 0
while lineix < len(lines):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if lineix_begin >= len(lines):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if lineix_end >= len(lines):
error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
'Could not find end of multi-line comment')
return
RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
lineix = lineix_end + 1
def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
class CleansedLines(object):
"""Holds 3 copies of all lines with different preprocessing applied to them.
1) elided member contains lines without strings and comments,
2) lines member contains lines without comments, and
3) raw_lines member contains all the lines without processing.
All these three members are of <type 'list'>, and of the same length.
"""
def __init__(self, lines):
self.elided = []
self.lines = []
self.raw_lines = lines
self.num_lines = len(lines)
self.lines_without_raw_strings = CleanseRawStrings(lines)
for linenum in range(len(self.lines_without_raw_strings)):
self.lines.append(CleanseComments(
self.lines_without_raw_strings[linenum]))
elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
self.elided.append(CleanseComments(elided))
def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines
@staticmethod
def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if not _RE_PATTERN_INCLUDE.match(elided):
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
return elided
def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
"""Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching endchar: (index just after matching endchar, 0)
Otherwise: (-1, new depth at end of this line)
"""
for i in xrange(startpos, len(line)):
if line[i] == startchar:
depth += 1
elif line[i] == endchar:
depth -= 1
if depth == 0:
return (i + 1, 0)
return (-1, depth)
def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
startchar = line[pos]
if startchar not in '({[<':
return (line, clean_lines.NumLines(), -1)
if startchar == '(': endchar = ')'
if startchar == '[': endchar = ']'
if startchar == '{': endchar = '}'
if startchar == '<': endchar = '>'
# Check first line
(end_pos, num_open) = FindEndOfExpressionInLine(
line, pos, 0, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, num_open) = FindEndOfExpressionInLine(
line, 0, num_open, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find endchar before end of file, give up
return (line, clean_lines.NumLines(), -1)
def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar):
"""Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line)
"""
for i in xrange(endpos, -1, -1):
if line[i] == endchar:
depth += 1
elif line[i] == startchar:
depth -= 1
if depth == 0:
return (i, 0)
return (-1, depth)
def ReverseCloseExpression(clean_lines, linenum, pos):
"""If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
endchar = line[pos]
if endchar not in ')}]>':
return (line, 0, -1)
if endchar == ')': startchar = '('
if endchar == ']': startchar = '['
if endchar == '}': startchar = '{'
if endchar == '>': startchar = '<'
# Check last line
(start_pos, num_open) = FindStartOfExpressionInLine(
line, pos, 0, startchar, endchar)
if start_pos > -1:
return (line, linenum, start_pos)
# Continue scanning backward
while linenum > 0:
linenum -= 1
line = clean_lines.elided[linenum]
(start_pos, num_open) = FindStartOfExpressionInLine(
line, len(line) - 1, num_open, startchar, endchar)
if start_pos > -1:
return (line, linenum, start_pos)
# Did not find startchar before beginning of file, give up
return (line, 0, -1)
def CheckForCopyright(filename, lines, error):
"""Logs an error if a Copyright message appears at the top of the file."""
# We'll check up to line 10. Don't forget there's a
# dummy line at the front.
for line in xrange(1, min(len(lines), 11)):
if _RE_COPYRIGHT.search(lines[line], re.I):
error(filename, 0, 'legal/copyright', 5,
'Copyright message found. '
'You should not include a copyright line.')
def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
"""
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
if _root:
file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
def CheckForHeaderGuard(filename, lines, error):
"""Checks that the file contains a header guard.
Logs an error if no #ifndef header guard is present. For other
headers, checks that the full pathname is used.
Args:
filename: The name of the C++ header file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
cppvar = GetHeaderGuardCPPVariable(filename)
ifndef = None
ifndef_linenum = 0
define = None
endif = None
endif_linenum = 0
for linenum, line in enumerate(lines):
linesplit = line.split()
if len(linesplit) >= 2:
# find the first occurrence of #ifndef and #define, save arg
if not ifndef and linesplit[0] == '#ifndef':
# set ifndef to the header guard presented on the #ifndef line.
ifndef = linesplit[1]
ifndef_linenum = linenum
if not define and linesplit[0] == '#define':
define = linesplit[1]
# find the last occurrence of #endif, save entire line
if line.startswith('#endif'):
endif = line
endif_linenum = linenum
if not ifndef:
error(filename, 0, 'build/header_guard', 5,
'No #ifndef header guard found, suggested CPP variable is: %s' %
cppvar)
return
if not define:
error(filename, 0, 'build/header_guard', 5,
'No #define header guard found, suggested CPP variable is: %s' %
cppvar)
return
# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
# for backward compatibility.
if ifndef != cppvar:
error_level = 0
if ifndef != cppvar + '_':
error_level = 5
ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum,
error)
error(filename, ifndef_linenum, 'build/header_guard', error_level,
'#ifndef header guard has wrong style, please use: %s' % cppvar)
if define != ifndef:
error(filename, 0, 'build/header_guard', 5,
'#ifndef and #define don\'t match, suggested CPP variable is: %s' %
cppvar)
return
if endif != ('#endif // %s' % cppvar):
error_level = 0
if endif != ('#endif // %s' % (cppvar + '_')):
error_level = 5
ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum,
error)
error(filename, endif_linenum, 'build/header_guard', error_level,
'#endif line should be "#endif // %s"' % cppvar)
def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.')
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
"""Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Remove all \\ (escaped backslashes) from the line. They are OK, and the
# second (escaped) slash may trigger later \" detection erroneously.
line = line.replace('\\\\', '')
if line.count('/*') > line.count('*/'):
error(filename, linenum, 'readability/multiline_comment', 5,
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. '
'Consider replacing these with //-style comments, '
'with #if 0...#endif, '
'or with more clearly structured multi-line comments.')
if (line.count('"') - line.count('\\"')) % 2:
error(filename, linenum, 'readability/multiline_string', 5,
'Multi-line string ("...") found. This lint script doesn\'t '
'do well with such strings, and may give bogus warnings. '
'Use C++11 raw strings or concatenation instead.')
caffe_alt_function_list = (
('memset', ['caffe_set', 'caffe_memset']),
('cudaMemset', ['caffe_gpu_set', 'caffe_gpu_memset']),
('memcpy', ['caffe_copy']),
('cudaMemcpy', ['caffe_copy', 'caffe_gpu_memcpy']),
)
def CheckCaffeAlternatives(filename, clean_lines, linenum, error):
"""Checks for C(++) functions for which a Caffe substitute should be used.
For certain native C functions (memset, memcpy), there is a Caffe alternative
which should be used instead.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for function, alts in caffe_alt_function_list:
ix = line.find(function + '(')
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
disp_alts = ['%s(...)' % alt for alt in alts]
error(filename, linenum, 'caffe/alt_fn', 2,
'Use Caffe function %s instead of %s(...).' %
(' or '.join(disp_alts), function))
def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error):
"""Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
ix = line.find('DataLayer<Dtype>::LayerSetUp')
if ix >= 0 and (
line.find('void DataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void ImageDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void MemoryDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void WindowDataLayer<Dtype>::LayerSetUp') != -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.')
ix = line.find('DataLayer<Dtype>::DataLayerSetUp')
if ix >= 0 and (
line.find('void Base') == -1 and
line.find('void DataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void ImageDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void MemoryDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void WindowDataLayer<Dtype>::DataLayerSetUp') == -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.')
c_random_function_list = (
'rand(',
'rand_r(',
'random(',
)
def CheckCaffeRandom(filename, clean_lines, linenum, error):
"""Checks for calls to C random functions (rand, rand_r, random, ...).
Caffe code should (almost) always use the caffe_rng_* functions rather
than these, as the internal state of these C functions is independent of the
native Caffe RNG system which should produce deterministic results for a
fixed Caffe seed set using Caffe::set_random_seed(...).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for function in c_random_function_list:
ix = line.find(function)
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
error(filename, linenum, 'caffe/random_fn', 2,
'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '
+ function +
') to ensure results are deterministic for a fixed Caffe seed.')
threading_list = (
('asctime(', 'asctime_r('),
('ctime(', 'ctime_r('),
('getgrgid(', 'getgrgid_r('),
('getgrnam(', 'getgrnam_r('),
('getlogin(', 'getlogin_r('),
('getpwnam(', 'getpwnam_r('),
('getpwuid(', 'getpwuid_r('),
('gmtime(', 'gmtime_r('),
('localtime(', 'localtime_r('),
('strtok(', 'strtok_r('),
('ttyname(', 'ttyname_r('),
)
def CheckPosixThreading(filename, clean_lines, linenum, error):
"""Checks for calls to thread-unsafe functions.
Much code has been originally written without consideration of
multi-threading. Also, engineers are relying on their old experience;
they have learned posix before threading extensions were added. These
tests guide the engineers to use thread-safe functions (when using
posix directly).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for single_thread_function, multithread_safe_function in threading_list:
ix = line.find(single_thread_function)
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
error(filename, linenum, 'runtime/threadsafe_fn', 2,
'Consider using ' + multithread_safe_function +
'...) instead of ' + single_thread_function +
'...) for improved thread safety.')
def CheckVlogArguments(filename, clean_lines, linenum, error):
"""Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
error(filename, linenum, 'runtime/vlog', 5,
'VLOG() should be used with numeric verbosity level. '
'Use LOG() if you want symbolic severity levels.')
# Matches invalid increment: *count++, which moves pointer instead of
# incrementing a value.
_RE_PATTERN_INVALID_INCREMENT = re.compile(
r'^\s*\*\w+(\+\+|--);')
def CheckInvalidIncrement(filename, clean_lines, linenum, error):
"""Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if _RE_PATTERN_INVALID_INCREMENT.match(line):
error(filename, linenum, 'runtime/invalid_increment', 5,
'Changing pointer instead of value (or unused value of operator*).')
class _BlockInfo(object):
"""Stores information about a generic block of code."""
def __init__(self, seen_open_brace):
self.seen_open_brace = seen_open_brace
self.open_parentheses = 0
self.inline_asm = _NO_ASM
def CheckBegin(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass
def CheckEnd(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass
class _ClassInfo(_BlockInfo):
"""Stores information about a class."""
def __init__(self, name, class_or_struct, clean_lines, linenum):
_BlockInfo.__init__(self, False)
self.name = name
self.starting_linenum = linenum
self.is_derived = False
if class_or_struct == 'struct':
self.access = 'public'
self.is_struct = True
else:
self.access = 'private'
self.is_struct = False
# Remember initial indentation level for this class. Using raw_lines here
# instead of elided to account for leading comments.
initial_indent = Match(r'^( *)\S', clean_lines.raw_lines[linenum])
if initial_indent:
self.class_indent = len(initial_indent.group(1))
else:
self.class_indent = 0
# Try to find the end of the class. This will be confused by things like:
# class A {
# } *x = { ...
#
# But it's still good enough for CheckSectionSpacing.
self.last_line = 0
depth = 0
for i in range(linenum, clean_lines.NumLines()):
line = clean_lines.elided[i]
depth += line.count('{') - line.count('}')
if not depth:
self.last_line = i
break
def CheckBegin(self, filename, clean_lines, linenum, error):
# Look for a bare ':'
if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
self.is_derived = True
def CheckEnd(self, filename, clean_lines, linenum, error):
# Check that closing brace is aligned with beginning of the class.
# Only do this if the closing brace is indented by only whitespaces.
# This means we will not check single-line class definitions.
indent = Match(r'^( *)\}', clean_lines.elided[linenum])
if indent and len(indent.group(1)) != self.class_indent:
if self.is_struct:
parent = 'struct ' + self.name
else:
parent = 'class ' + self.name
error(filename, linenum, 'whitespace/indent', 3,
'Closing brace should be aligned with beginning of %s' % parent)
class _NamespaceInfo(_BlockInfo):
"""Stores information about a namespace."""
def __init__(self, name, linenum):
_BlockInfo.__init__(self, False)
self.name = name or ''
self.starting_linenum = linenum
def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
line = clean_lines.raw_lines[linenum]
# Check how many lines is enclosed in this namespace. Don't issue
# warning for missing namespace comments if there aren't enough
# lines. However, do apply checks if there is already an end of
# namespace comment and it's incorrect.
#
# TODO(unknown): We always want to check end of namespace comments
# if a namespace is large, but sometimes we also want to apply the
# check if a short namespace contained nontrivial things (something
# other than forward declarations). There is currently no logic on
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
# preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
# expected namespace.
if self.name:
# Named namespace
if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace"')
class _PreprocessorInfo(object):
"""Stores checkpoints of nesting stacks when #if/#else is seen."""
def __init__(self, stack_before_if):
# The entire nesting stack before #if
self.stack_before_if = stack_before_if
# The entire nesting stack up to #else
self.stack_before_else = []
# Whether we have already seen #else or #elif
self.seen_else = False
class _NestingState(object):
"""Holds states related to parsing braces."""
def __init__(self):
# Stack for tracking all braces. An object is pushed whenever we
# see a "{", and popped when we see a "}". Only 3 types of
# objects are possible:
# - _ClassInfo: a class or struct.
# - _NamespaceInfo: a namespace.
# - _BlockInfo: some other type of block.
self.stack = []
# Stack of _PreprocessorInfo objects.
self.pp_stack = []
def SeenOpenBrace(self):
"""Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace.
"""
return (not self.stack) or self.stack[-1].seen_open_brace
def InNamespaceBody(self):
"""Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass
def Update(self, filename, clean_lines, linenum, error):
"""Update nesting state with current line.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Update pp_stack first
self.UpdatePreprocessor(line)
# Count parentheses. This is to avoid adding struct arguments to
# the nesting stack.
if self.stack:
inner_block = self.stack[-1]
depth_change = line.count('(') - line.count(')')
inner_block.open_parentheses += depth_change
# Also check if we are starting or ending an inline assembly block.
if inner_block.inline_asm in (_NO_ASM, _END_ASM):
if (depth_change != 0 and
inner_block.open_parentheses == 1 and
_MATCH_ASM.match(line)):
# Enter assembly block
inner_block.inline_asm = _INSIDE_ASM
else:
# Not entering assembly block. If previous line was _END_ASM,
# we will now shift to _NO_ASM state.
inner_block.inline_asm = _NO_ASM
elif (inner_block.inline_asm == _INSIDE_ASM and
inner_block.open_parentheses == 0):
# Exit assembly block
inner_block.inline_asm = _END_ASM
# Consume namespace declaration at the beginning of the line. Do
# this in a loop so that we catch same line declarations like this:
# namespace proto2 { namespace bridge { class MessageSet; } }
while True:
# Match start of namespace. The "\b\s*" below catches namespace
# declarations even if it weren't followed by a whitespace, this
# is so that we don't confuse our namespace checker. The
# missing spaces will be flagged by CheckSpacing.
namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
if not namespace_decl_match:
break
new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
self.stack.append(new_namespace)
line = namespace_decl_match.group(2)
if line.find('{') != -1:
new_namespace.seen_open_brace = True
line = line[line.find('{') + 1:]
# Look for a class declaration in whatever is left of the line
# after parsing namespaces. The regexp accounts for decorated classes
# such as in:
# class LOCKABLE API Object {
# };
#
# Templates with class arguments may confuse the parser, for example:
# template <class T
# class Comparator = less<T>,
# class Vector = vector<T> >
# class HeapQueue {
#
# Because this parser has no nesting state about templates, by the
# time it saw "class Comparator", it may think that it's a new class.
# Nested templates have a similar problem:
# template <
# typename ExportedType,
# typename TupleType,
# template <typename, typename> class ImplTemplate>
#
# To avoid these cases, we ignore classes that are followed by '=' or '>'
class_decl_match = Match(
r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
r'(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)'
r'(([^=>]|<[^<>]*>|<[^<>]*<[^<>]*>\s*>)*)$', line)
if (class_decl_match and
(not self.stack or self.stack[-1].open_parentheses == 0)):
self.stack.append(_ClassInfo(
class_decl_match.group(4), class_decl_match.group(2),
clean_lines, linenum))
line = class_decl_match.group(5)
# If we have not yet seen the opening brace for the innermost block,
# run checks here.
if not self.SeenOpenBrace():
self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
# Update access control if we are inside a class/struct
if self.stack and isinstance(self.stack[-1], _ClassInfo):
classinfo = self.stack[-1]
access_match = Match(
r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
r':(?:[^:]|$)',
line)
if access_match:
classinfo.access = access_match.group(2)
# Check that access keywords are indented +1 space. Skip this
# check if the keywords are not preceded by whitespaces.
indent = access_match.group(1)
if (len(indent) != classinfo.class_indent + 1 and
Match(r'^\s*$', indent)):
if classinfo.is_struct:
parent = 'struct ' + classinfo.name
else:
parent = 'class ' + classinfo.name
slots = ''
if access_match.group(3):
slots = access_match.group(3)
error(filename, linenum, 'whitespace/indent', 3,
'%s%s: should be indented +1 space inside %s' % (
access_match.group(2), slots, parent))
# Consume braces or semicolons from what's left of the line
while True:
# Match first brace, semicolon, or closed parenthesis.
matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
if not matched:
break
token = matched.group(1)
if token == '{':
# If namespace or class hasn't seen a opening brace yet, mark
# namespace/class head as complete. Push a new block onto the
# stack otherwise.
if not self.SeenOpenBrace():
self.stack[-1].seen_open_brace = True
else:
self.stack.append(_BlockInfo(True))
if _MATCH_ASM.match(line):
self.stack[-1].inline_asm = _BLOCK_ASM
elif token == ';' or token == ')':
# If we haven't seen an opening brace yet, but we already saw
# a semicolon, this is probably a forward declaration. Pop
# the stack for these.
#
# Similarly, if we haven't seen an opening brace yet, but we
# already saw a closing parenthesis, then these are probably
# function arguments with extra "class" or "struct" keywords.
# Also pop these stack for these.
if not self.SeenOpenBrace():
self.stack.pop()
else: # token == '}'
# Perform end of block checks and pop the stack.
if self.stack:
self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
self.stack.pop()
line = matched.group(2)
def InnermostClass(self):
"""Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise.
"""
for i in range(len(self.stack), 0, -1):
classinfo = self.stack[i - 1]
if isinstance(classinfo, _ClassInfo):
return classinfo
return None
def CheckCompletedBlocks(self, filename, error):
"""Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
"""
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
elif isinstance(obj, _NamespaceInfo):
error(filename, obj.starting_linenum, 'build/namespaces', 5,
'Failed to find complete declaration of namespace %s' %
obj.name)
def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args and
args.group(1) != 'void' and
not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), args.group(1).strip())):
error(filename, linenum, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.')
def CheckSpacingForFunctionCall(filename, line, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'#\s*define|typedef', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )')
def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace()
def CheckForFunctionLengths(filename, clean_lines, linenum,
function_state, error):
"""Reports for long function bodies.
For an overview why this is done, see:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found.
"""
lines = clean_lines.lines
line = lines[linenum]
raw = clean_lines.raw_lines
raw_line = raw[linenum]
joined_line = ''
starting_func = False
regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
match_result = Match(regexp, line)
if match_result:
# If the name is all caps and underscores, figure it's a macro and
# ignore it, unless it's TEST or TEST_F.
function_name = match_result.group(1).split()[-1]
if function_name == 'TEST' or function_name == 'TEST_F' or (
not Match(r'[A-Z_]+$', function_name)):
starting_func = True
if starting_func:
body_found = False
for start_linenum in xrange(linenum, clean_lines.NumLines()):
start_line = lines[start_linenum]
joined_line += ' ' + start_line.lstrip()
if Search(r'(;|})', start_line): # Declarations and trivial functions
body_found = True
break # ... ignore
elif Search(r'{', start_line):
body_found = True
function = Search(r'((\w|:)*)\(', line).group(1)
if Match(r'TEST', function): # Handle TEST... macros
parameter_regexp = Search(r'(\(.*\))', joined_line)
if parameter_regexp: # Ignore bad syntax
function += parameter_regexp.group(1)
else:
function += '()'
function_state.Begin(function)
break
if not body_found:
# No body for the function (or evidence of a non-function) was found.
error(filename, linenum, 'readability/fn_size', 5,
'Lint failed to find start of function body.')
elif Match(r'^\}\s*$', line): # function end
function_state.Check(error, filename, linenum)
function_state.End()
elif not Match(r'^\s*$', line):
function_state.Count() # Count non-blank/non-comment lines.
_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
def CheckComment(comment, filename, linenum, error):
"""Checks for common mistakes in TODO comments.
Args:
comment: The text of the comment from the line in question.
filename: The name of the current file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
match = _RE_PATTERN_TODO.match(comment)
if match:
# One whitespace is correct; zero whitespace is handled elsewhere.
leading_whitespace = match.group(1)
if len(leading_whitespace) > 1:
error(filename, linenum, 'whitespace/todo', 2,
'Too many spaces before TODO')
username = match.group(2)
if not username:
error(filename, linenum, 'readability/todo', 2,
'Missing username in TODO; it should look like '
'"// TODO(my_username): Stuff."')
middle_whitespace = match.group(3)
# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
if middle_whitespace != ' ' and middle_whitespace != '':
error(filename, linenum, 'whitespace/todo', 2,
'TODO(my_username) should be followed by a space')
def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
"""Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
r'DISALLOW_EVIL_CONSTRUCTORS|'
r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
if not matched:
return
if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
if nesting_state.stack[-1].access != 'private':
error(filename, linenum, 'readability/constructors', 3,
'%s must be in the private: section' % matched.group(1))
else:
# Found DISALLOW* macro outside a class declaration, or perhaps it
# was used inside a function when it should have been part of the
# class declaration. We could issue a warning here, but it
# probably resulted in a compiler error already.
pass
def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
"""Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists.
"""
line = init_suffix
nesting_stack = ['<']
while True:
# Find the next operator that can tell us whether < is used as an
# opening bracket or as a less-than operator. We only want to
# warn on the latter case.
#
# We could also check all other operators and terminate the search
# early, e.g. if we got something like this "a<b+c", the "<" is
# most likely a less-than operator, but then we will get false
# positives for default arguments and other template expressions.
match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
if match:
# Found an operator, update nesting stack
operator = match.group(1)
line = match.group(2)
if nesting_stack[-1] == '<':
# Expecting closing angle bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator == '>':
nesting_stack.pop()
if not nesting_stack:
# Found matching angle bracket
return True
elif operator == ',':
# Got a comma after a bracket, this is most likely a template
# argument. We have not seen a closing angle bracket yet, but
# it's probably a few lines later if we look for it, so just
# return early here.
return True
else:
# Got some other operator.
return False
else:
# Expecting closing parenthesis or closing bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator in (')', ']'):
# We don't bother checking for matching () or []. If we got
# something like (] or [), it would have been a syntax error.
nesting_stack.pop()
else:
# Scan the next line
linenum += 1
if linenum >= len(clean_lines.elided):
break
line = clean_lines.elided[linenum]
# Exhausted all remaining lines and still no matching angle bracket.
# Most likely the input was incomplete, otherwise we should have
# seen a semicolon and returned early.
return True
def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix):
"""Find the corresponding < that started a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_prefix: Part of the current line before the initial >.
Returns:
True if a matching bracket exists.
"""
line = init_prefix
nesting_stack = ['>']
while True:
# Find the previous operator
match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line)
if match:
# Found an operator, update nesting stack
operator = match.group(2)
line = match.group(1)
if nesting_stack[-1] == '>':
# Expecting opening angle bracket
if operator in ('>', ')', ']'):
nesting_stack.append(operator)
elif operator == '<':
nesting_stack.pop()
if not nesting_stack:
# Found matching angle bracket
return True
elif operator == ',':
# Got a comma before a bracket, this is most likely a
# template argument. The opening angle bracket is probably
# there if we look for it, so just return early here.
return True
else:
# Got some other operator.
return False
else:
# Expecting opening parenthesis or opening bracket
if operator in ('>', ')', ']'):
nesting_stack.append(operator)
elif operator in ('(', '['):
nesting_stack.pop()
else:
# Scan the previous line
linenum -= 1
if linenum < 0:
break
line = clean_lines.elided[linenum]
# Exhausted all earlier lines and still no matching angle bracket.
return False
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
#
# Skip all the blank line checks if we are immediately inside a
# namespace body. In other words, don't issue blank line warnings
# for this block:
# namespace {
#
# }
#
# A warning about missing end of namespace comments will be issued instead.
if IsBlankLine(line) and not nesting_state.InNamespaceBody():
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Redundant blank line at the start of a code block '
'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Redundant blank line at the end of a code block '
'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, we complain if there's a comment too near the text
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if (line.count('"', 0, commentpos) -
line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
# Allow one space for new scopes, two spaces otherwise:
if (not Match(r'^\s*{ //', line) and
((commentpos >= 1 and
line[commentpos-1] not in string.whitespace) or
(commentpos >= 2 and
line[commentpos-2] not in string.whitespace))):
error(filename, linenum, 'whitespace/comments', 2,
'At least two spaces is best between code and comments')
# There should always be a space between the // and the comment
commentend = commentpos + 2
if commentend < len(line) and not line[commentend] == ' ':
# but some lines are exceptions -- e.g. if they're big
# comment delimiters like:
# //----------------------------------------------------------
# or are an empty C++ style Doxygen comment, like:
# ///
# or C++ style Doxygen comments placed after the variable:
# ///< Header comment
# //!< Header comment
# or they begin with multiple slashes followed by a space:
# //////// Header comment
match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
Search(r'^/$', line[commentend:]) or
Search(r'^!< ', line[commentend:]) or
Search(r'^/< ', line[commentend:]) or
Search(r'^/+ ', line[commentend:]))
if not match:
error(filename, linenum, 'whitespace/comments', 4,
'Should have a space between // and comment')
CheckComment(line[commentpos:], filename, linenum, error)
line = clean_lines.elided[linenum] # get rid of comments and strings
# Don't try to do spacing checks for operator methods
line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
# We allow no-spaces around << when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
# Also ignore using ns::operator<<;
match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
if (match and
not (match.group(1).isdigit() and match.group(2).isdigit()) and
not (match.group(1) == 'operator' and match.group(2) == ';')):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <<')
elif not Match(r'#.*include', line):
# Avoid false positives on ->
reduced_line = line.replace('->', '')
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
if (match and
not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
if (match and
not FindPreviousMatchingAngleBracket(clean_lines, linenum,
match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
# most cases when ">>" is not followed by a space.
#
# We still warn on ">>" followed by alpha character, because that is
# likely due to ">>" being used for right shifts, e.g.:
# value >> alpha
#
# When ">>" is used to close templates, the alphanumeric letter that
# follows would be part of an identifier, and there should still be
# a space separating the template type and the identifier.
# type<type<type>> alpha
match = Search(r'>>[a-zA-Z_]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >>')
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
# A pet peeve of mine: no spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
# You should always have a space after a comma (either as fn arg or operator)
#
# This does not apply when the non-space character following the
# comma is another comma, since the only time when that happens is
# for empty macro arguments.
#
# We run this check in two passes: first pass on elided lines to
# verify that lines contain missing whitespaces, second pass on raw
# lines to confirm that those missing whitespaces are not due to
# elided comments.
if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
# Next we will look for issues with function calls.
CheckSpacingForFunctionCall(filename, line, linenum, error)
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces. And since you should never have braces at the beginning of a line,
# this is an easy test.
match = Match(r'^(.*[^ ({]){', line)
if match:
# Try a bit harder to check for brace initialization. This
# happens in one of the following forms:
# Constructor() : initializer_list_{} { ... }
# Constructor{}.MemberFunction()
# Type variable{};
# FunctionCall(type{}, ...);
# LastArgument(..., type{});
# LOG(INFO) << type{} << " ...";
# map_of_type[{...}] = ...;
#
# We check for the character following the closing brace, and
# silence the warning if it's one of those listed above, i.e.
# "{.;,)<]".
#
# To account for nested initializer list, we allow any number of
# closing braces up to "{;,)<". We can't simply silence the
# warning on first sight of closing brace, because that would
# cause false negatives for things that are not initializer lists.
# Silence this: But not this:
# Outer{ if (...) {
# Inner{...} if (...){ // Missing space before {
# }; }
#
# There is a false negative with this approach if people inserted
# spurious semicolons, e.g. "if (cond){};", but we will catch the
# spurious semicolon with a separate check.
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
trailing_text = ''
if endpos > -1:
trailing_text = endline[endpos:]
for offset in xrange(endlinenum + 1,
min(endlinenum + 3, clean_lines.NumLines() - 1)):
trailing_text += clean_lines.elided[offset]
if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'new char * []'.
if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use {} instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use {} instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search('for *\(.*[^:]:[^: ]', line) or
Search('for *\(.*[^: ]:[^:]', line)):
error(filename, linenum, 'whitespace/forcolon', 2,
'Missing space around colon in range-based for loop')
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
"""Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Skip checks if the class is small, where small means 25 lines or less.
# 25 lines seems like a good cutoff since that's the usual height of
# terminals, and any class that can't fit in one screen can't really
# be considered "small".
#
# Also skip checks if we are on the first line. This accounts for
# classes that look like
# class Foo { public: ... };
#
# If we didn't find the end of the class, last_line would be zero,
# and the check will be skipped by the first condition.
if (class_info.last_line - class_info.starting_linenum <= 24 or
linenum <= class_info.starting_linenum):
return
matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
if matched:
# Issue warning if the line before public/protected/private was
# not a blank line, but don't do this if the previous line contains
# "class" or "struct". This can happen two ways:
# - We are at the beginning of the class.
# - We are forward-declaring an inner class that is semantically
# private, but needed to be public for implementation reasons.
# Also ignores cases where the previous line ends with a backslash as can be
# common when defining classes in C macros.
prev_line = clean_lines.lines[linenum - 1]
if (not IsBlankLine(prev_line) and
not Search(r'\b(class|struct)\b', prev_line) and
not Search(r'\\$', prev_line)):
# Try a bit harder to find the beginning of the class. This is to
# account for multi-line base-specifier lists, e.g.:
# class Derived
# : public Base {
end_class_head = class_info.starting_linenum
for i in range(class_info.starting_linenum, linenum):
if Search(r'\{\s*$', clean_lines.lines[i]):
end_class_head = i
break
if end_class_head < linenum - 1:
error(filename, linenum, 'whitespace/blank_line', 3,
'"%s:" should be preceded by a blank line' % matched.group(1))
def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1)
def CheckBraces(filename, clean_lines, linenum, error):
"""Looks for misplaced braces (e.g. at the end of line).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
if Match(r'\s*{\s*$', line):
# We allow an open brace to start a line in the case where someone is using
# braces in a block to explicitly create a new scope, which is commonly used
# to control the lifetime of stack-allocated variables. Braces are also
# used for brace initializers inside function calls. We don't detect this
# perfectly: we just don't complain if the last non-whitespace character on
# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
# previous line starts a preprocessor block.
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if (not Search(r'[,;:}{(]\s*$', prevline) and
not Match(r'\s*#', prevline)):
error(filename, linenum, 'whitespace/braces', 4,
'{ should almost always be at the end of the previous line')
# An else clause should be on the same line as the preceding closing brace.
if Match(r'\s*else\s*', line):
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if Match(r'\s*}\s*$', prevline):
error(filename, linenum, 'whitespace/newline', 4,
'An else should appear on the same line as the preceding }')
# If braces come on one side of an else, they should be on both.
# However, we have to worry about "else if" that spans multiple lines!
if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
# find the ( after the if
pos = line.find('else if')
pos = line.find('(', pos)
if pos > 0:
(endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
if endline[endpos:].find('{') == -1: # must be brace after if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
else: # common case: else not followed by a multi-line if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
# Likewise, an else should never have the else clause on the same line
if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
error(filename, linenum, 'whitespace/newline', 4,
'Else clause should never be on same line as else (use 2 lines)')
# In the same way, a do/while should never be on one line
if Match(r'\s*do [^\s{]', line):
error(filename, linenum, 'whitespace/newline', 4,
'do/while clauses should not be on a single line')
# Block bodies should not be followed by a semicolon. Due to C++11
# brace initialization, there are more places where semicolons are
# required than not, so we use a whitelist approach to check these
# rather than a blacklist. These are the places where "};" should
# be replaced by just "}":
# 1. Some flavor of block following closing parenthesis:
# for (;;) {};
# while (...) {};
# switch (...) {};
# Function(...) {};
# if (...) {};
# if (...) else if (...) {};
#
# 2. else block:
# if (...) else {};
#
# 3. const member function:
# Function(...) const {};
#
# 4. Block following some statement:
# x = 42;
# {};
#
# 5. Block at the beginning of a function:
# Function(...) {
# {};
# }
#
# Note that naively checking for the preceding "{" will also match
# braces inside multi-dimensional arrays, but this is fine since
# that expression will not contain semicolons.
#
# 6. Block following another block:
# while (true) {}
# {};
#
# 7. End of namespaces:
# namespace {};
#
# These semicolons seems far more common than other kinds of
# redundant semicolons, possibly due to people converting classes
# to namespaces. For now we do not warn for this case.
#
# Try matching case 1 first.
match = Match(r'^(.*\)\s*)\{', line)
if match:
# Matched closing parenthesis (case 1). Check the token before the
# matching opening parenthesis, and don't warn if it looks like a
# macro. This avoids these false positives:
# - macro that defines a base class
# - multi-line macro that defines a base class
# - macro that defines the whole class-head
#
# But we still issue warnings for macros that we know are safe to
# warn, specifically:
# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
# - TYPED_TEST
# - INTERFACE_DEF
# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
#
# We implement a whitelist of safe macros instead of a blacklist of
# unsafe macros, even though the latter appears less frequently in
# google code and would have been easier to implement. This is because
# the downside for getting the whitelist wrong means some extra
# semicolons, while the downside for getting the blacklist wrong
# would result in compile errors.
#
# In addition to macros, we also don't want to warn on compound
# literals.
closing_brace_pos = match.group(1).rfind(')')
opening_parenthesis = ReverseCloseExpression(
clean_lines, linenum, closing_brace_pos)
if opening_parenthesis[2] > -1:
line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
macro = Search(r'\b([A-Z_]+)\s*$', line_prefix)
if ((macro and
macro.group(1) not in (
'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
Search(r'\s+=\s*$', line_prefix)):
match = None
else:
# Try matching cases 2-3.
match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
if not match:
# Try matching cases 4-6. These are always matched on separate lines.
#
# Note that we can't simply concatenate the previous line to the
# current line and do a single match, otherwise we may output
# duplicate warnings for the blank line case:
# if (cond) {
# // blank line
# }
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if prevline and Search(r'[;{}]\s*$', prevline):
match = Match(r'^(\s*)\{', line)
# Check matching closing brace
if match:
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
# Current {} pair is eligible for semicolon check, and we have found
# the redundant semicolon, output warning here.
#
# Note: because we are scanning forward for opening braces, and
# outputting warnings for the matching closing brace, if there are
# nested blocks with trailing semicolons, we will get the error
# messages in reversed order.
error(filename, endlinenum, 'readability/braces', 4,
"You don't need a ; after a }")
def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
"""Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" blocks here, since an empty conditional block
# is likely an error.
line = clean_lines.elided[linenum]
matched = Match(r'\s*(for|while|if)\s*\(', line)
if matched:
# Find the end of the conditional expression
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
# Output warning if what follows the condition expression is a semicolon.
# No warning for all other cases, including whitespace or newline, since we
# have a separate check for semicolons preceded by whitespace.
if end_pos >= 0 and Match(r';', end_line[end_pos:]):
if matched.group(1) == 'if':
error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
'Empty conditional bodies should use {}')
else:
error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
'Empty loop bodies should use {} or continue')
def CheckCheck(filename, clean_lines, linenum, error):
"""Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Decide the set of replacement macros that should be suggested
lines = clean_lines.elided
check_macro = None
start_pos = -1
for macro in _CHECK_MACROS:
i = lines[linenum].find(macro)
if i >= 0:
check_macro = macro
# Find opening parenthesis. Do a regular expression match here
# to make sure that we are matching the expected CHECK macro, as
# opposed to some other macro that happens to contain the CHECK
# substring.
matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum])
if not matched:
continue
start_pos = len(matched.group(1))
break
if not check_macro or start_pos < 0:
# Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
return
# Find end of the boolean expression by matching parentheses
(last_line, end_line, end_pos) = CloseExpression(
clean_lines, linenum, start_pos)
if end_pos < 0:
return
if linenum == end_line:
expression = lines[linenum][start_pos + 1:end_pos - 1]
else:
expression = lines[linenum][start_pos + 1:]
for i in xrange(linenum + 1, end_line):
expression += lines[i]
expression += last_line[0:end_pos - 1]
# Parse expression so that we can take parentheses into account.
# This avoids false positives for inputs like "CHECK((a < 4) == b)",
# which is not replaceable by CHECK_LE.
lhs = ''
rhs = ''
operator = None
while expression:
matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
r'==|!=|>=|>|<=|<|\()(.*)$', expression)
if matched:
token = matched.group(1)
if token == '(':
# Parenthesized operand
expression = matched.group(2)
(end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')')
if end < 0:
return # Unmatched parenthesis
lhs += '(' + expression[0:end]
expression = expression[end:]
elif token in ('&&', '||'):
# Logical and/or operators. This means the expression
# contains more than one term, for example:
# CHECK(42 < a && a < b);
#
# These are not replaceable with CHECK_LE, so bail out early.
return
elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
# Non-relational operator
lhs += token
expression = matched.group(2)
else:
# Relational operator
operator = token
rhs = matched.group(2)
break
else:
# Unparenthesized operand. Instead of appending to lhs one character
# at a time, we do another regular expression match to consume several
# characters at once if possible. Trivial benchmark shows that this
# is more efficient when the operands are longer than a single
# character, which is generally the case.
matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
if not matched:
matched = Match(r'^(\s*\S)(.*)$', expression)
if not matched:
break
lhs += matched.group(1)
expression = matched.group(2)
# Only apply checks if we got all parts of the boolean expression
if not (lhs and operator and rhs):
return
# Check that rhs do not contain logical operators. We already know
# that lhs is fine since the loop above parses out && and ||.
if rhs.find('&&') > -1 or rhs.find('||') > -1:
return
# At least one of the operands must be a constant literal. This is
# to avoid suggesting replacements for unprintable things like
# CHECK(variable != iterator)
#
# The following pattern matches decimal, hex integers, strings, and
# characters (in that order).
lhs = lhs.strip()
rhs = rhs.strip()
match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
if Match(match_constant, lhs) or Match(match_constant, rhs):
# Note: since we know both lhs and rhs, we can provide a more
# descriptive error message like:
# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
# Instead of:
# Consider using CHECK_EQ instead of CHECK(a == b)
#
# We are still keeping the less descriptive message because if lhs
# or rhs gets long, the error message might become unreadable.
error(filename, linenum, 'readability/check', 2,
'Consider using %s instead of %s(a %s b)' % (
_CHECK_REPLACEMENT[check_macro][operator],
check_macro, operator))
def CheckAltTokens(filename, clean_lines, linenum, error):
"""Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line)
def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
error):
"""Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw_lines = clean_lines.lines_without_raw_strings
line = raw_lines[linenum]
if line.find('\t') != -1:
error(filename, linenum, 'whitespace/tab', 1,
'Tab found; better to use spaces')
# One or three blank spaces at the beginning of the line is weird; it's
# hard to reconcile that with 2-space indents.
# NOTE: here are the conditions rob pike used for his tests. Mine aren't
# as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
# if(RLENGTH > 20) complain = 0;
# if(match($0, " +(error|private|public|protected):")) complain = 0;
# if(match(prev, "&& *$")) complain = 0;
# if(match(prev, "\\|\\| *$")) complain = 0;
# if(match(prev, "[\",=><] *$")) complain = 0;
# if(match($0, " <<")) complain = 0;
# if(match(prev, " +for \\(")) complain = 0;
# if(prevodd && match(prevprev, " +for \\(")) complain = 0;
initial_spaces = 0
cleansed_line = clean_lines.elided[linenum]
while initial_spaces < len(line) and line[initial_spaces] == ' ':
initial_spaces += 1
if line and line[-1].isspace():
error(filename, linenum, 'whitespace/end_of_line', 4,
'Line ends in whitespace. Consider deleting these extra spaces.')
# There are certain situations we allow one space, notably for section labels
elif ((initial_spaces == 1 or initial_spaces == 3) and
not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
error(filename, linenum, 'whitespace/indent', 3,
'Weird number of spaces at line-start. '
'Are you using a 2-space indent?')
# Check if the line is a header guard.
is_header_guard = False
if file_extension == 'h':
cppvar = GetHeaderGuardCPPVariable(filename)
if (line.startswith('#ifndef %s' % cppvar) or
line.startswith('#define %s' % cppvar) or
line.startswith('#endif // %s' % cppvar)):
is_header_guard = True
# #include lines and header guards can be long, since there's no clean way to
# split them.
#
# URLs can be long too. It's possible to split these, but it makes them
# harder to cut&paste.
#
# The "$Id:...$" comment may also get very long without it being the
# developers fault.
if (not line.startswith('#include') and not is_header_guard and
not Match(r'^\s*//.*http(s?)://\S*$', line) and
not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
line_width = GetLineWidth(line)
extended_length = int((_line_length * 1.25))
if line_width > extended_length:
error(filename, linenum, 'whitespace/line_length', 4,
'Lines should very rarely be longer than %i characters' %
extended_length)
elif line_width > _line_length:
error(filename, linenum, 'whitespace/line_length', 2,
'Lines should be <= %i characters long' % _line_length)
if (cleansed_line.count(';') > 1 and
# for loops are allowed two ;'s (and may run over two lines).
cleansed_line.find('for') == -1 and
(GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
# It's ok to have many commands in a switch case that fits in 1 line
not ((cleansed_line.find('case ') != -1 or
cleansed_line.find('default:') != -1) and
cleansed_line.find('break;') != -1)):
error(filename, linenum, 'whitespace/newline', 0,
'More than one command on the same line')
# Some more style checks
CheckBraces(filename, clean_lines, linenum, error)
CheckEmptyBlockBody(filename, clean_lines, linenum, error)
CheckAccess(filename, clean_lines, linenum, nesting_state, error)
CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
CheckCheck(filename, clean_lines, linenum, error)
CheckAltTokens(filename, clean_lines, linenum, error)
classinfo = nesting_state.InnermostClass()
if classinfo:
CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
_RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
# Matches the first component of a filename delimited by -s and _s. That is:
# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
def _DropCommonSuffixes(filename):
"""Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed.
"""
for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
'inl.h', 'impl.h', 'internal.h'):
if (filename.endswith(suffix) and len(filename) > len(suffix) and
filename[-len(suffix) - 1] in ('-', '_')):
return filename[:-len(suffix) - 1]
return os.path.splitext(filename)[0]
def _IsTestFilename(filename):
"""Determines if the given filename has a suffix that identifies it as a test.
Args:
filename: The input filename.
Returns:
True if 'filename' looks like a test, False otherwise.
"""
if (filename.endswith('_test.cc') or
filename.endswith('_unittest.cc') or
filename.endswith('_regtest.cc')):
return True
else:
return False
def _ClassifyInclude(fileinfo, include, is_system):
"""Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER
"""
# This is a list of all standard c++ header files, except
# those already checked for above.
is_cpp_h = include in _CPP_HEADERS
if is_system:
if is_cpp_h:
return _CPP_SYS_HEADER
else:
return _C_SYS_HEADER
# If the target file and the include we're checking share a
# basename when we drop common extensions, and the include
# lives in . , then it's likely to be owned by the target file.
target_dir, target_base = (
os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
if target_base == include_base and (
include_dir == target_dir or
include_dir == os.path.normpath(target_dir + '/../public')):
return _LIKELY_MY_HEADER
# If the target and include share some initial basename
# component, it's possible the target is implementing the
# include, so it's allowed to be first, but we'll never
# complain if it's not there.
target_first_component = _RE_FIRST_COMPONENT.match(target_base)
include_first_component = _RE_FIRST_COMPONENT.match(include_base)
if (target_first_component and include_first_component and
target_first_component.group(0) ==
include_first_component.group(0)):
return _POSSIBLE_MY_HEADER
return _OTHER_HEADER
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
error(filename, linenum, 'build/include_dir', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
if include in include_state:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, include_state[include]))
else:
include_state[include] = linenum
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include)
# Look for any of the stream classes that are part of standard C++.
match = _RE_PATTERN_INCLUDE.match(line)
if match:
include = match.group(2)
if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
# Many unit tests use cout, so we exempt them.
if not _IsTestFilename(filename):
error(filename, linenum, 'readability/streams', 3,
'Streams are highly discouraged.')
def _GetTextInside(text, start_pattern):
r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found.
"""
# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
# rewritten to use _GetTextInside (and use inferior regexp matching today).
# Give opening punctuations to get the matching close-punctuations.
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set(matching_punctuation.itervalues())
# Find the position to start extracting text.
match = re.search(start_pattern, text, re.M)
if not match: # start_pattern not found in text.
return None
start_position = match.end(0)
assert start_position > 0, (
'start_pattern must ends with an opening punctuation.')
assert text[start_position - 1] in matching_punctuation, (
'start_pattern must ends with an opening punctuation.')
# Stack of closing punctuations we expect to have in text after position.
punctuation_stack = [matching_punctuation[text[start_position - 1]]]
position = start_position
while punctuation_stack and position < len(text):
if text[position] == punctuation_stack[-1]:
punctuation_stack.pop()
elif text[position] in closing_punctuation:
# A closing punctuation without matching opening punctuations.
return None
elif text[position] in matching_punctuation:
punctuation_stack.append(matching_punctuation[text[position]])
position += 1
if punctuation_stack:
# Opening punctuations left without matching close-punctuations.
return None
# punctuations match.
return text[start_position:position - 1]
# Patterns for matching call-by-reference parameters.
#
# Supports nested templates up to 2 levels deep using this messy pattern:
# < (?: < (?: < [^<>]*
# >
# | [^<>] )*
# >
# | [^<>] )*
# >
_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
_RE_PATTERN_TYPE = (
r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
r'(?:\w|'
r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
r'::)+')
# A call-by-reference parameter ends with '& identifier'.
_RE_PATTERN_REF_PARAM = re.compile(
r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
# A call-by-const-reference parameter either ends with 'const& identifier'
# or looks like 'const type& identifier' when 'type' is atomic.
_RE_PATTERN_CONST_REF_PARAM = (
r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
def CheckLanguage(filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# If the line is empty or consists of entirely a comment, no need to
# check it.
line = clean_lines.elided[linenum]
if not line:
return
match = _RE_PATTERN_INCLUDE.search(line)
if match:
CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
return
# Reset include state across preprocessor directives. This is meant
# to silence warnings for conditional includes.
if Match(r'^\s*#\s*(?:ifdef|elif|else|endif)\b', line):
include_state.ResetSection()
# Make Windows paths like Unix.
fullname = os.path.abspath(filename).replace('\\', '/')
# TODO(unknown): figure out if they're using default arguments in fn proto.
# Check to see if they're using an conversion function cast.
# I just try to capture the most common basic types, though there are more.
# Parameterless conversion functions, such as bool(), are allowed as they are
# probably a member operator declaration or default constructor.
match = Search(
r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
r'(\([^)].*)', line)
if match:
matched_new = match.group(1)
matched_type = match.group(2)
matched_funcptr = match.group(3)
# gMock methods are defined using some variant of MOCK_METHODx(name, type)
# where type may be float(), int(string), etc. Without context they are
# virtually indistinguishable from int(x) casts. Likewise, gMock's
# MockCallback takes a template parameter of the form return_type(arg_type),
# which looks much like the cast we're trying to detect.
#
# std::function<> wrapper has a similar problem.
#
# Return types for function pointers also look like casts if they
# don't have an extra space.
if (matched_new is None and # If new operator, then this isn't a cast
not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
Search(r'\bMockCallback<.*>', line) or
Search(r'\bstd::function<.*>', line)) and
not (matched_funcptr and
Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
matched_funcptr))):
# Try a bit harder to catch gmock lines: the only place where
# something looks like an old-style cast is where we declare the
# return type of the mocked method, and the only time when we
# are missing context is if MOCK_METHOD was split across
# multiple lines. The missing MOCK_METHOD is usually one or two
# lines back, so scan back one or two lines.
#
# It's not possible for gmock macros to appear in the first 2
# lines, since the class head + section name takes up 2 lines.
if (linenum < 2 or
not (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]))):
error(filename, linenum, 'readability/casting', 4,
'Using deprecated casting style. '
'Use static_cast<%s>(...) instead' %
matched_type)
CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'static_cast',
r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
# This doesn't catch all cases. Consider (const char * const)"hello".
#
# (char *) "foo" should always be a const_cast (reinterpret_cast won't
# compile).
if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
pass
else:
# Check pointer casts for other than string constants
CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
# In addition, we look for people taking the address of a cast. This
# is dangerous -- casts can assign to temporaries, so the pointer doesn't
# point where you think.
match = Search(
r'(?:&\(([^)]+)\)[\w(])|'
r'(?:&(static|dynamic|down|reinterpret)_cast\b)', line)
if match and match.group(1) != '*':
error(filename, linenum, 'runtime/casting', 4,
('Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'))
# Create an extended_line, which is the concatenation of the current and
# next lines, for more effective checking of code that may span more than one
# line.
if linenum + 1 < clean_lines.NumLines():
extended_line = line + clean_lines.elided[linenum + 1]
else:
extended_line = line
# Check for people declaring static/global STL strings at the top level.
# This is dangerous because the C++ language does not guarantee that
# globals with constructors are initialized before the first access.
match = Match(
r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
line)
# Make sure it's not a function.
# Function template specialization looks like: "string foo<Type>(...".
# Class template definitions look like: "string Foo<Type>::Method(...".
#
# Also ignore things that look like operators. These are matched separately
# because operator names cross non-word boundaries. If we change the pattern
# above, we would decrease the accuracy of matching identifiers.
if (match and
not Search(r'\boperator\W', line) and
not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', match.group(3))):
error(filename, linenum, 'runtime/string', 4,
'For a static/global string constant, use a C style string instead: '
'"%schar %s[]".' %
(match.group(1), match.group(2)))
if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
error(filename, linenum, 'runtime/init', 4,
'You seem to be initializing a member variable with itself.')
if file_extension == 'h':
# TODO(unknown): check that 1-arg constructors are explicit.
# How to tell it's a constructor?
# (handled in CheckForNonStandardConstructs for now)
# TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
# (level 1 error)
pass
# Check if people are using the verboten C basic types. The only exception
# we regularly allow is "unsigned short port" for port.
if Search(r'\bshort port\b', line):
if not Search(r'\bunsigned short port\b', line):
error(filename, linenum, 'runtime/int', 4,
'Use "unsigned short" for ports, not "short"')
else:
match = Search(r'\b(short|long(?! +double)|long long)\b', line)
if match:
error(filename, linenum, 'runtime/int', 4,
'Use int16/int64/etc, rather than the C type %s' % match.group(1))
# When snprintf is used, the second argument shouldn't be a literal.
match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
if match and match.group(2) != '0':
# If 2nd arg is zero, snprintf is used to calculate size.
error(filename, linenum, 'runtime/printf', 3,
'If you can, use sizeof(%s) instead of %s as the 2nd arg '
'to snprintf.' % (match.group(1), match.group(2)))
# Check if some verboten C functions are being used.
if Search(r'\bsprintf\b', line):
error(filename, linenum, 'runtime/printf', 5,
'Never use sprintf. Use snprintf instead.')
match = Search(r'\b(strcpy|strcat)\b', line)
if match:
error(filename, linenum, 'runtime/printf', 4,
'Almost always, snprintf is better than %s' % match.group(1))
# Check if some verboten operator overloading is going on
# TODO(unknown): catch out-of-line unary operator&:
# class X {};
# int operator&(const X& x) { return 42; } // unary operator&
# The trick is it's hard to tell apart from binary operator&:
# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
if Search(r'\boperator\s*&\s*\(\s*\)', line):
error(filename, linenum, 'runtime/operator', 4,
'Unary operator& is dangerous. Do not use it.')
# Check for suspicious usage of "if" like
# } if (a == b) {
if Search(r'\}\s*if\s*\(', line):
error(filename, linenum, 'readability/braces', 4,
'Did you mean "else if"? If not, start a new line for "if".')
# Check for potential format string bugs like printf(foo).
# We constrain the pattern not to pick things like DocidForPrintf(foo).
# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
# TODO(sugawarayu): Catch the following case. Need to change the calling
# convention of the whole function to process multiple line to handle it.
# printf(
# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
if printf_args:
match = Match(r'([\w.\->()]+)$', printf_args)
if match and match.group(1) != '__VA_ARGS__':
function_name = re.search(r'\b((?:string)?printf)\s*\(',
line, re.I).group(1)
error(filename, linenum, 'runtime/printf', 4,
'Potential format string bug. Do %s("%%s", %s) instead.'
% (function_name, match.group(1)))
# Check for potential memset bugs like memset(buf, sizeof(buf), 0).
match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
error(filename, linenum, 'runtime/memset', 4,
'Did you mean "memset(%s, 0, %s)"?'
% (match.group(1), match.group(2)))
if Search(r'\busing namespace\b', line):
error(filename, linenum, 'build/namespaces', 5,
'Do not use namespace using-directives. '
'Use using-declarations instead.')
# Detect variable-length arrays.
match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
match.group(3).find(']') == -1):
# Split the size using space and arithmetic operators as delimiters.
# If any of the resulting tokens are not compile time constants then
# report the error.
tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
is_const = True
skip_next = False
for tok in tokens:
if skip_next:
skip_next = False
continue
if Search(r'sizeof\(.+\)', tok): continue
if Search(r'arraysize\(\w+\)', tok): continue
tok = tok.lstrip('(')
tok = tok.rstrip(')')
if not tok: continue
if Match(r'\d+', tok): continue
if Match(r'0[xX][0-9a-fA-F]+', tok): continue
if Match(r'k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
# A catch all for tricky sizeof cases, including 'sizeof expression',
# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
# requires skipping the next token because we split on ' ' and '*'.
if tok.startswith('sizeof'):
skip_next = True
continue
is_const = False
break
if not is_const:
error(filename, linenum, 'runtime/arrays', 1,
'Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size.")
# If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
# DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
# in the class declaration.
match = Match(
(r'\s*'
r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
r'\(.*\);$'),
line)
if match and linenum + 1 < clean_lines.NumLines():
next_line = clean_lines.elided[linenum + 1]
# We allow some, but not all, declarations of variables to be present
# in the statement that defines the class. The [\w\*,\s]* fragment of
# the regular expression below allows users to declare instances of
# the class or pointers to instances, but not less common types such
# as function pointers or arrays. It's a tradeoff between allowing
# reasonable code and avoiding trying to parse more C++ using regexps.
if not Search(r'^\s*}[\w\*,\s]*;', next_line):
error(filename, linenum, 'readability/constructors', 3,
match.group(1) + ' should be the last thing in the class')
# Check for use of unnamed namespaces in header files. Registration
# macros are typically OK, so we allow use of "namespace {" on lines
# that end with backslashes.
if (file_extension == 'h'
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.')
def CheckForNonConstReference(filename, clean_lines, linenum,
nesting_state, error):
"""Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Do nothing if there is no '&' on current line.
line = clean_lines.elided[linenum]
if '&' not in line:
return
# Long type names may be broken across multiple lines, usually in one
# of these forms:
# LongType
# ::LongTypeContinued &identifier
# LongType::
# LongTypeContinued &identifier
# LongType<
# ...>::LongTypeContinued &identifier
#
# If we detected a type split across two lines, join the previous
# line to current line so that we can match const references
# accordingly.
#
# Note that this only scans back one line, since scanning back
# arbitrary number of lines would be expensive. If you have a type
# that spans more than 2 lines, please use a typedef.
if linenum > 1:
previous = None
if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
# previous_line\n + ::current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
clean_lines.elided[linenum - 1])
elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
# previous_line::\n + current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
clean_lines.elided[linenum - 1])
if previous:
line = previous.group(1) + line.lstrip()
else:
# Check for templated parameter that is split across multiple lines
endpos = line.rfind('>')
if endpos > -1:
(_, startline, startpos) = ReverseCloseExpression(
clean_lines, linenum, endpos)
if startpos > -1 and startline < linenum:
# Found the matching < on an earlier line, collect all
# pieces up to current line.
line = ''
for i in xrange(startline, linenum + 1):
line += clean_lines.elided[i].strip()
# Check for non-const references in function parameters. A single '&' may
# found in the following places:
# inside expression: binary & for bitwise AND
# inside expression: unary & for taking the address of something
# inside declarators: reference parameter
# We will exclude the first two cases by checking that we are not inside a
# function body, including one that was just introduced by a trailing '{'.
# TODO(unknwon): Doesn't account for preprocessor directives.
# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
check_params = False
if not nesting_state.stack:
check_params = True # top level
elif (isinstance(nesting_state.stack[-1], _ClassInfo) or
isinstance(nesting_state.stack[-1], _NamespaceInfo)):
check_params = True # within class or namespace
elif Match(r'.*{\s*$', line):
if (len(nesting_state.stack) == 1 or
isinstance(nesting_state.stack[-2], _ClassInfo) or
isinstance(nesting_state.stack[-2], _NamespaceInfo)):
check_params = True # just opened global/class/namespace block
# We allow non-const references in a few standard places, like functions
# called "swap()" or iostream operators like "<<" or ">>". Do not check
# those function parameters.
#
# We also accept & in static_assert, which looks like a function but
# it's actually a declaration expression.
whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
r'operator\s*[<>][<>]|'
r'static_assert|COMPILE_ASSERT'
r')\s*\(')
if Search(whitelisted_functions, line):
check_params = False
elif not Search(r'\S+\([^)]*$', line):
# Don't see a whitelisted function on this line. Actually we
# didn't see any function name on this line, so this is likely a
# multi-line parameter list. Try a bit harder to catch this case.
for i in xrange(2):
if (linenum > i and
Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
check_params = False
break
if check_params:
decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter):
error(filename, linenum, 'runtime/references', 2,
'Is this a non-const reference? '
'If so, make const or use a pointer: ' +
ReplaceAll(' *<', '<', parameter))
def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
match = Search(pattern, line)
if not match:
return False
# Exclude lines with sizeof, since sizeof looks like a cast.
sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
if sizeof_match:
return False
# operator++(int) and operator--(int)
if (line[0:match.start(1) - 1].endswith(' operator++') or
line[0:match.start(1) - 1].endswith(' operator--')):
return False
# A single unnamed argument for a function tends to look like old
# style cast. If we see those, don't issue warnings for deprecated
# casts, instead issue warnings for unnamed arguments where
# appropriate.
#
# These are things that we want warnings for, since the style guide
# explicitly require all parameters to be named:
# Function(int);
# Function(int) {
# ConstMember(int) const;
# ConstMember(int) const {
# ExceptionMember(int) throw (...);
# ExceptionMember(int) throw (...) {
# PureVirtual(int) = 0;
#
# These are functions of some sort, where the compiler would be fine
# if they had named parameters, but people often omit those
# identifiers to reduce clutter:
# (FunctionPointer)(int);
# (FunctionPointer)(int) = value;
# Function((function_pointer_arg)(int))
# <TemplateArgument(int)>;
# <(FunctionPointerTemplateArgument)(int)>;
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder):
# Looks like an unnamed parameter.
# Don't warn on any kind of template arguments.
if Match(r'^\s*>', remainder):
return False
# Don't warn on assignments to function pointers, but keep warnings for
# unnamed parameters to pure virtual functions. Note that this pattern
# will also pass on assignments of "0" to function pointers, but the
# preferred values for those would be "nullptr" or "NULL".
matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
if matched_zero and matched_zero.group(1) != '0':
return False
# Don't warn on function pointer declarations. For this we need
# to check what came before the "(type)" string.
if Match(r'.*\)\s*$', line[0:match.start(0)]):
return False
# Don't warn if the parameter is named with block comments, e.g.:
# Function(int /*unused_param*/);
if '/*' in raw_line:
return False
# Passed all filters, issue warning here.
error(filename, linenum, 'readability/function', 3,
'All parameters should be named in a function')
return True
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True
_HEADERS_CONTAINING_TEMPLATES = (
('<deque>', ('deque',)),
('<functional>', ('unary_function', 'binary_function',
'plus', 'minus', 'multiplies', 'divides', 'modulus',
'negate',
'equal_to', 'not_equal_to', 'greater', 'less',
'greater_equal', 'less_equal',
'logical_and', 'logical_or', 'logical_not',
'unary_negate', 'not1', 'binary_negate', 'not2',
'bind1st', 'bind2nd',
'pointer_to_unary_function',
'pointer_to_binary_function',
'ptr_fun',
'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
'mem_fun_ref_t',
'const_mem_fun_t', 'const_mem_fun1_t',
'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
'mem_fun_ref',
)),
('<limits>', ('numeric_limits',)),
('<list>', ('list',)),
('<map>', ('map', 'multimap',)),
('<memory>', ('allocator',)),
('<queue>', ('queue', 'priority_queue',)),
('<set>', ('set', 'multiset',)),
('<stack>', ('stack',)),
('<string>', ('char_traits', 'basic_string',)),
('<utility>', ('pair',)),
('<vector>', ('vector',)),
# gcc extensions.
# Note: std::hash is their hash, ::hash is our hash
('<hash_map>', ('hash_map', 'hash_multimap',)),
('<hash_set>', ('hash_set', 'hash_multiset',)),
('<slist>', ('slist',)),
)
_RE_PATTERN_STRING = re.compile(r'\bstring\b')
_re_pattern_algorithm_header = []
for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
'transform'):
# Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
# type::max().
_re_pattern_algorithm_header.append(
(re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
_template,
'<algorithm>'))
_re_pattern_templates = []
for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
for _template in _templates:
_re_pattern_templates.append(
(re.compile(r'(\<|\b)' + _template + r'\s*\<'),
_template + '<>',
_header))
def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file.
"""
if not filename_cc.endswith('.cc'):
return (False, '')
filename_cc = filename_cc[:-len('.cc')]
if filename_cc.endswith('_unittest'):
filename_cc = filename_cc[:-len('_unittest')]
elif filename_cc.endswith('_test'):
filename_cc = filename_cc[:-len('_test')]
filename_cc = filename_cc.replace('/public/', '/')
filename_cc = filename_cc.replace('/internal/', '/')
if not filename_h.endswith('.h'):
return (False, '')
filename_h = filename_h[:-len('.h')]
if filename_h.endswith('-inl'):
filename_h = filename_h[:-len('-inl')]
filename_h = filename_h.replace('/public/', '/')
filename_h = filename_h.replace('/internal/', '/')
files_belong_to_same_module = filename_cc.endswith(filename_h)
common_path = ''
if files_belong_to_same_module:
common_path = filename_cc[:-len(filename_h)]
return files_belong_to_same_module, common_path
def UpdateIncludeState(filename, include_state, io=codecs):
"""Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise.
"""
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
# The value formatting is cute, but not really used right now.
# What matters here is that the key is in include_state.
include_state.setdefault(include, '%s:%d' % (filename, linenum))
return True
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
io=codecs):
"""Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection.
"""
required = {} # A map of header name to linenumber and the template entity.
# Example of required: { '<functional>': (1219, 'less<>') }
for linenum in xrange(clean_lines.NumLines()):
line = clean_lines.elided[linenum]
if not line or line[0] == '#':
continue
# String is special -- it is a non-templatized type in STL.
matched = _RE_PATTERN_STRING.search(line)
if matched:
# Don't warn about strings in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required['<string>'] = (linenum, 'string')
for pattern, template, header in _re_pattern_algorithm_header:
if pattern.search(line):
required[header] = (linenum, template)
# The following function is just a speed up, no semantics are changed.
if not '<' in line: # Reduces the cpu time usage by skipping lines.
continue
for pattern, template, header in _re_pattern_templates:
if pattern.search(line):
required[header] = (linenum, template)
# The policy is that if you #include something in foo.h you don't need to
# include it again in foo.cc. Here, we will look at possible includes.
# Let's copy the include_state so it is only messed up within this function.
include_state = include_state.copy()
# Did we find the header for this file (if any) and succesfully load it?
header_found = False
# Use the absolute path so that matching works properly.
abs_filename = FileInfo(filename).FullName()
# For Emacs's flymake.
# If cpplint is invoked from Emacs's flymake, a temporary file is generated
# by flymake and that file name might end with '_flymake.cc'. In that case,
# restore original file name here so that the corresponding header file can be
# found.
# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
# instead of 'foo_flymake.h'
abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
# include_state is modified during iteration, so we iterate over a copy of
# the keys.
header_keys = include_state.keys()
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
if same_module and UpdateIncludeState(fullpath, include_state, io):
header_found = True
# If we can't find the header file for a .cc, assume it's because we don't
# know where to look. In that case we'll give up as we're not sure they
# didn't include it in the .h file.
# TODO(unknown): Do a better job of finding .h files so we are confident that
# not having the .h file means there isn't one.
if filename.endswith('.cc') and not header_found:
return
# All the lines have been processed, report the errors found.
for required_header_unstripped in required:
template = required[required_header_unstripped][1]
if required_header_unstripped.strip('<>"') not in include_state:
error(filename, required[required_header_unstripped][0],
'build/include_what_you_use', 4,
'Add #include ' + required_header_unstripped + ' for ' + template)
_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
"""Check that make_pair's template arguments are deduced.
G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4, # 4 = high confidence
'For C++11-compatibility, omit template arguments from make_pair'
' OR use pair directly OR if appropriate, construct a pair directly')
def ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions=[]):
"""Processes a single line in the file.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
clean_lines: An array of strings, each representing a line of the file,
with comments stripped.
line: Number of line being processed.
include_state: An _IncludeState instance in which the headers are inserted.
function_state: A _FunctionState instance which counts function lines, etc.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
raw_lines = clean_lines.raw_lines
ParseNolintSuppressions(filename, raw_lines[line], line, error)
nesting_state.Update(filename, clean_lines, line, error)
if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM:
return
CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
CheckLanguage(filename, clean_lines, line, file_extension, include_state,
nesting_state, error)
CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
CheckForNonStandardConstructs(filename, clean_lines, line,
nesting_state, error)
CheckVlogArguments(filename, clean_lines, line, error)
CheckCaffeAlternatives(filename, clean_lines, line, error)
CheckCaffeDataLayerSetUp(filename, clean_lines, line, error)
CheckCaffeRandom(filename, clean_lines, line, error)
CheckPosixThreading(filename, clean_lines, line, error)
CheckInvalidIncrement(filename, clean_lines, line, error)
CheckMakePairUsesDeduction(filename, clean_lines, line, error)
for check_fn in extra_check_functions:
check_fn(filename, clean_lines, line, error)
def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = _NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error)
def ProcessFile(filename, vlevel, extra_check_functions=[]):
"""Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
_SetVerboseLevel(vlevel)
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not opening the file with universal newline support
# (which codecs doesn't support anyway), so the resulting lines do
# contain trailing '\r' characters if we are reading a file that
# has CRLF endings.
# If after the split a trailing '\r' is present, it is removed
# below. If it is not expected to be present (i.e. os.linesep !=
# '\r\n' as in Windows), a warning is issued below if this file
# is processed.
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace').read().split('\n')
else:
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
carriage_return_found = False
# Remove trailing '\r'.
for linenum in range(len(lines)):
if lines[linenum].endswith('\r'):
lines[linenum] = lines[linenum].rstrip('\r')
carriage_return_found = True
except IOError:
sys.stderr.write(
"Skipping input '%s': Can't open for reading\n" % filename)
return
# Note, if no dot is found, this will give the entire filename as the ext.
file_extension = filename[filename.rfind('.') + 1:]
# When reading from stdin, the extension is unknown, so no cpplint tests
# should rely on the extension.
if filename != '-' and file_extension not in _valid_extensions:
sys.stderr.write('Ignoring %s; not a valid file name '
'(%s)\n' % (filename, ', '.join(_valid_extensions)))
else:
ProcessFileData(filename, file_extension, lines, Error,
extra_check_functions)
if carriage_return_found and os.linesep != '\r\n':
# Use 0 for linenum since outputting only one error for potentially
# several lines.
Error(filename, 0, 'whitespace/newline', 1,
'One or more unexpected \\r (^M) found;'
'better to use only a \\n')
sys.stderr.write('Done processing %s\n' % filename)
def PrintUsage(message):
"""Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message.
"""
sys.stderr.write(_USAGE)
if message:
sys.exit('\nFATAL ERROR: ' + message)
else:
sys.exit(1)
def PrintCategories():
"""Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter.
"""
sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
sys.exit(0)
def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
'linelength=',
'extensions='])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
filters = val
if not filters:
PrintCategories()
elif opt == '--counting':
if val not in ('total', 'toplevel', 'detailed'):
PrintUsage('Valid counting options are total, toplevel, and detailed')
counting_style = val
elif opt == '--root':
global _root
_root = val
elif opt == '--linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage('Line length must be digits.')
elif opt == '--extensions':
global _valid_extensions
try:
_valid_extensions = set(val.split(','))
except ValueError:
PrintUsage('Extensions must be comma seperated list.')
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames
def main():
filenames = ParseArguments(sys.argv[1:])
# Change stderr to write with replacement characters so we don't die
# if we try to print something containing non-ASCII characters.
sys.stderr = codecs.StreamReaderWriter(sys.stderr,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace')
_cpplint_state.ResetErrorCounts()
for filename in filenames:
ProcessFile(filename, _cpplint_state.verbose_level)
_cpplint_state.PrintErrorCounts()
sys.exit(_cpplint_state.error_count > 0)
if __name__ == '__main__':
main()
| 187,448 | 37.49846 | 93 | py |
ADaPTION | ADaPTION-master/scripts/download_model_binary.py | #!/usr/bin/env python
import os
import sys
import time
import yaml
import urllib
import hashlib
import argparse
required_keys = ['caffemodel', 'caffemodel_url', 'sha1']
def reporthook(count, block_size, total_size):
"""
From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/
"""
global start_time
if count == 0:
start_time = time.time()
return
duration = (time.time() - start_time) or 0.01
progress_size = int(count * block_size)
speed = int(progress_size / (1024 * duration))
percent = int(count * block_size * 100 / total_size)
sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" %
(percent, progress_size / (1024 * 1024), speed, duration))
sys.stdout.flush()
def parse_readme_frontmatter(dirname):
readme_filename = os.path.join(dirname, 'readme.md')
with open(readme_filename) as f:
lines = [line.strip() for line in f.readlines()]
top = lines.index('---')
bottom = lines.index('---', top + 1)
frontmatter = yaml.load('\n'.join(lines[top + 1:bottom]))
assert all(key in frontmatter for key in required_keys)
return dirname, frontmatter
def valid_dirname(dirname):
try:
return parse_readme_frontmatter(dirname)
except Exception as e:
print('ERROR: {}'.format(e))
raise argparse.ArgumentTypeError(
'Must be valid Caffe model directory with a correct readme.md')
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Download trained model binary.')
parser.add_argument('dirname', type=valid_dirname)
args = parser.parse_args()
# A tiny hack: the dirname validator also returns readme YAML frontmatter.
dirname = args.dirname[0]
frontmatter = args.dirname[1]
model_filename = os.path.join(dirname, frontmatter['caffemodel'])
# Closure-d function for checking SHA1.
def model_checks_out(filename=model_filename, sha1=frontmatter['sha1']):
with open(filename, 'rb') as f:
return hashlib.sha1(f.read()).hexdigest() == sha1
# Check if model exists.
if os.path.exists(model_filename) and model_checks_out():
print("Model already exists.")
sys.exit(0)
# Download and verify model.
urllib.urlretrieve(
frontmatter['caffemodel_url'], model_filename, reporthook)
if not model_checks_out():
print('ERROR: model did not download correctly! Run this again.')
sys.exit(1)
| 2,507 | 31.571429 | 78 | py |
ADaPTION | ADaPTION-master/frcnn/tools/compress_net.py | #!/usr/bin/env python
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Compress a Fast R-CNN network using truncated SVD."""
import _init_paths
import caffe
import argparse
import numpy as np
import os, sys
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Compress a Fast R-CNN network')
parser.add_argument('--def', dest='prototxt',
help='prototxt file defining the uncompressed network',
default=None, type=str)
parser.add_argument('--def-svd', dest='prototxt_svd',
help='prototxt file defining the SVD compressed network',
default=None, type=str)
parser.add_argument('--net', dest='caffemodel',
help='model to compress',
default=None, type=str)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
def compress_weights(W, l):
"""Compress the weight matrix W of an inner product (fully connected) layer
using truncated SVD.
Parameters:
W: N x M weights matrix
l: number of singular values to retain
Returns:
Ul, L: matrices such that W \approx Ul*L
"""
# numpy doesn't seem to have a fast truncated SVD algorithm...
# this could be faster
U, s, V = np.linalg.svd(W, full_matrices=False)
Ul = U[:, :l]
sl = s[:l]
Vl = V[:l, :]
L = np.dot(np.diag(sl), Vl)
return Ul, L
def main():
args = parse_args()
# prototxt = 'models/VGG16/test.prototxt'
# caffemodel = 'snapshots/vgg16_fast_rcnn_iter_40000.caffemodel'
net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST)
# prototxt_svd = 'models/VGG16/svd/test_fc6_fc7.prototxt'
# caffemodel = 'snapshots/vgg16_fast_rcnn_iter_40000.caffemodel'
net_svd = caffe.Net(args.prototxt_svd, args.caffemodel, caffe.TEST)
print('Uncompressed network {} : {}'.format(args.prototxt, args.caffemodel))
print('Compressed network prototxt {}'.format(args.prototxt_svd))
out = os.path.splitext(os.path.basename(args.caffemodel))[0] + '_svd'
out_dir = os.path.dirname(args.caffemodel)
# Compress fc6
if net_svd.params.has_key('fc6_L'):
l_fc6 = net_svd.params['fc6_L'][0].data.shape[0]
print(' fc6_L bottleneck size: {}'.format(l_fc6))
# uncompressed weights and biases
W_fc6 = net.params['fc6'][0].data
B_fc6 = net.params['fc6'][1].data
print(' compressing fc6...')
Ul_fc6, L_fc6 = compress_weights(W_fc6, l_fc6)
assert(len(net_svd.params['fc6_L']) == 1)
# install compressed matrix factors (and original biases)
net_svd.params['fc6_L'][0].data[...] = L_fc6
net_svd.params['fc6_U'][0].data[...] = Ul_fc6
net_svd.params['fc6_U'][1].data[...] = B_fc6
out += '_fc6_{}'.format(l_fc6)
# Compress fc7
if net_svd.params.has_key('fc7_L'):
l_fc7 = net_svd.params['fc7_L'][0].data.shape[0]
print ' fc7_L bottleneck size: {}'.format(l_fc7)
W_fc7 = net.params['fc7'][0].data
B_fc7 = net.params['fc7'][1].data
print(' compressing fc7...')
Ul_fc7, L_fc7 = compress_weights(W_fc7, l_fc7)
assert(len(net_svd.params['fc7_L']) == 1)
net_svd.params['fc7_L'][0].data[...] = L_fc7
net_svd.params['fc7_U'][0].data[...] = Ul_fc7
net_svd.params['fc7_U'][1].data[...] = B_fc7
out += '_fc7_{}'.format(l_fc7)
filename = '{}/{}.caffemodel'.format(out_dir, out)
net_svd.save(filename)
print 'Wrote svd model to: {:s}'.format(filename)
if __name__ == '__main__':
main()
| 3,918 | 30.103175 | 81 | py |
ADaPTION | ADaPTION-master/frcnn/tools/train_faster_rcnn_alt_opt.py | #!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a Faster R-CNN network using alternating optimization.
This tool implements the alternating optimization algorithm described in our
NIPS 2015 paper ("Faster R-CNN: Towards Real-time Object Detection with Region
Proposal Networks." Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun.)
"""
import _init_paths
from fast_rcnn.train import get_training_roidb, train_net
from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list, get_output_dir
from datasets.factory import get_imdb
from rpn.generate import imdb_proposals
import argparse
import pprint
import numpy as np
import sys
import os
import multiprocessing as mp
import cPickle
import shutil
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Faster R-CNN network')
parser.add_argument('--gpu', dest='gpu_id',
help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument('--net_name', dest='net_name',
help='network name (e.g., "ZF")',
default=None, type=str)
parser.add_argument('--weights', dest='pretrained_model',
help='initialize with pretrained model weights',
default=None, type=str)
parser.add_argument('--cfg', dest='cfg_file',
help='optional config file',
default=None, type=str)
parser.add_argument('--imdb', dest='imdb_name',
help='dataset to train on',
default='voc_2007_trainval', type=str)
parser.add_argument('--set', dest='set_cfgs',
help='set config keys', default=None,
nargs=argparse.REMAINDER)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
def get_roidb(imdb_name, rpn_file=None):
imdb = get_imdb(imdb_name)
print 'Loaded dataset `{:s}` for training'.format(imdb.name)
imdb.set_proposal_method(cfg.TRAIN.PROPOSAL_METHOD)
print 'Set proposal method: {:s}'.format(cfg.TRAIN.PROPOSAL_METHOD)
if rpn_file is not None:
imdb.config['rpn_file'] = rpn_file
roidb = get_training_roidb(imdb)
return roidb, imdb
def get_solvers(net_name):
# Faster R-CNN Alternating Optimization
n = 'faster_rcnn_alt_opt'
# Solver for each training stage
solvers = [[net_name, n, 'stage1_rpn_solver60k80k.pt'],
[net_name, n, 'stage1_fast_rcnn_solver30k40k.pt'],
[net_name, n, 'stage2_rpn_solver60k80k.pt'],
[net_name, n, 'stage2_fast_rcnn_solver30k40k.pt']]
solvers = [os.path.join(cfg.MODELS_DIR, *s) for s in solvers]
# Iterations for each training stage
max_iters = [80000, 40000, 80000, 40000]
# max_iters = [100, 100, 100, 100]
# max_iters = [40, 40, 40, 40]
# Test prototxt for the RPN
rpn_test_prototxt = os.path.join(
cfg.MODELS_DIR, net_name, n, 'rpn_test.pt')
return solvers, max_iters, rpn_test_prototxt
# ------------------------------------------------------------------------------
# Pycaffe doesn't reliably free GPU memory when instantiated nets are discarded
# (e.g. "del net" in Python code). To work around this issue, each training
# stage is executed in a separate process using multiprocessing.Process.
# ------------------------------------------------------------------------------
def _init_caffe(cfg):
"""Initialize pycaffe in a training process.
"""
import caffe
# fix the random seeds (numpy and caffe) for reproducibility
np.random.seed(cfg.RNG_SEED)
caffe.set_random_seed(cfg.RNG_SEED)
# set up caffe
caffe.set_mode_gpu()
caffe.set_device(cfg.GPU_ID)
def train_rpn(queue=None, imdb_name=None, init_model=None, solver=None,
max_iters=None, cfg=None):
"""Train a Region Proposal Network in a separate training process.
"""
# Not using any proposals, just ground-truth boxes
cfg.TRAIN.HAS_RPN = True
cfg.TRAIN.BBOX_REG = False # applies only to Fast R-CNN bbox regression
cfg.TRAIN.PROPOSAL_METHOD = 'gt'
cfg.TRAIN.IMS_PER_BATCH = 1
print 'Init model: {}'.format(init_model)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
roidb, imdb = get_roidb(imdb_name)
print 'roidb len: {}'.format(len(roidb))
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
model_paths = train_net(solver, roidb, output_dir,
pretrained_model=init_model,
max_iters=max_iters)
# Cleanup all but the final model
for i in model_paths[:-1]:
os.remove(i)
rpn_model_path = model_paths[-1]
# Send final model path through the multiprocessing queue
queue.put({'model_path': rpn_model_path})
def rpn_generate(queue=None, imdb_name=None, rpn_model_path=None, cfg=None,
rpn_test_prototxt=None):
"""Use a trained RPN to generate proposals.
"""
cfg.TEST.RPN_PRE_NMS_TOP_N = -1 # no pre NMS filtering
cfg.TEST.RPN_POST_NMS_TOP_N = 2000 # limit top boxes after NMS
print 'RPN model: {}'.format(rpn_model_path)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
# NOTE: the matlab implementation computes proposals on flipped images, too.
# We compute them on the image once and then flip the already computed
# proposals. This might cause a minor loss in mAP (less proposal jittering).
imdb = get_imdb(imdb_name)
print 'Loaded dataset `{:s}` for proposal generation'.format(imdb.name)
# Load RPN and configure output directory
rpn_net = caffe.Net(rpn_test_prototxt, rpn_model_path, caffe.TEST)
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
# Generate proposals on the imdb
rpn_proposals = imdb_proposals(rpn_net, imdb)
# Write proposals to disk and send the proposal file path through the
# multiprocessing queue
rpn_net_name = os.path.splitext(os.path.basename(rpn_model_path))[0]
rpn_proposals_path = os.path.join(
output_dir, rpn_net_name + '_proposals.pkl')
with open(rpn_proposals_path, 'wb') as f:
cPickle.dump(rpn_proposals, f, cPickle.HIGHEST_PROTOCOL)
print 'Wrote RPN proposals to {}'.format(rpn_proposals_path)
queue.put({'proposal_path': rpn_proposals_path})
def train_fast_rcnn(queue=None, imdb_name=None, init_model=None, solver=None,
max_iters=None, cfg=None, rpn_file=None):
"""Train a Fast R-CNN using proposals generated by an RPN.
"""
cfg.TRAIN.HAS_RPN = False # not generating prosals on-the-fly
cfg.TRAIN.PROPOSAL_METHOD = 'rpn' # use pre-computed RPN proposals instead
cfg.TRAIN.IMS_PER_BATCH = 2
print 'Init model: {}'.format(init_model)
print 'RPN proposals: {}'.format(rpn_file)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
roidb, imdb = get_roidb(imdb_name, rpn_file=rpn_file)
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
# Train Fast R-CNN
model_paths = train_net(solver, roidb, output_dir,
pretrained_model=init_model,
max_iters=max_iters)
# Cleanup all but the final model
for i in model_paths[:-1]:
os.remove(i)
fast_rcnn_model_path = model_paths[-1]
# Send Fast R-CNN model path over the multiprocessing queue
queue.put({'model_path': fast_rcnn_model_path})
if __name__ == '__main__':
args = parse_args()
print('Called with args:')
print(args)
if args.cfg_file is not None:
cfg_from_file(args.cfg_file)
if args.set_cfgs is not None:
cfg_from_list(args.set_cfgs)
cfg.GPU_ID = args.gpu_id
# --------------------------------------------------------------------------
# Pycaffe doesn't reliably free GPU memory when instantiated nets are
# discarded (e.g. "del net" in Python code). To work around this issue, each
# training stage is executed in a separate process using
# multiprocessing.Process.
# --------------------------------------------------------------------------
# queue for communicated results between processes
mp_queue = mp.Queue()
# solves, iters, etc. for each training stage
solvers, max_iters, rpn_test_prototxt = get_solvers(args.net_name)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 1 RPN, init from ImageNet model'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
cfg.TRAIN.SNAPSHOT_INFIX = 'stage1'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
init_model=args.pretrained_model,
solver=solvers[0],
max_iters=max_iters[0],
cfg=cfg)
p = mp.Process(target=train_rpn, kwargs=mp_kwargs)
p.start()
rpn_stage1_out = mp_queue.get()
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 1 RPN, generate proposals'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
rpn_model_path=str(rpn_stage1_out['model_path']),
cfg=cfg,
rpn_test_prototxt=rpn_test_prototxt)
p = mp.Process(target=rpn_generate, kwargs=mp_kwargs)
p.start()
rpn_stage1_out['proposal_path'] = mp_queue.get()['proposal_path']
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 1 Fast R-CNN using RPN proposals, init from ImageNet model'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
cfg.TRAIN.SNAPSHOT_INFIX = 'stage1'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
init_model=args.pretrained_model,
solver=solvers[1],
max_iters=max_iters[1],
cfg=cfg,
rpn_file=rpn_stage1_out['proposal_path'])
p = mp.Process(target=train_fast_rcnn, kwargs=mp_kwargs)
p.start()
fast_rcnn_stage1_out = mp_queue.get()
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 2 RPN, init from stage 1 Fast R-CNN model'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
cfg.TRAIN.SNAPSHOT_INFIX = 'stage2'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
init_model=str(fast_rcnn_stage1_out['model_path']),
solver=solvers[2],
max_iters=max_iters[2],
cfg=cfg)
p = mp.Process(target=train_rpn, kwargs=mp_kwargs)
p.start()
rpn_stage2_out = mp_queue.get()
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 2 RPN, generate proposals'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
rpn_model_path=str(rpn_stage2_out['model_path']),
cfg=cfg,
rpn_test_prototxt=rpn_test_prototxt)
p = mp.Process(target=rpn_generate, kwargs=mp_kwargs)
p.start()
rpn_stage2_out['proposal_path'] = mp_queue.get()['proposal_path']
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 2 Fast R-CNN, init from stage 2 RPN R-CNN model'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
cfg.TRAIN.SNAPSHOT_INFIX = 'stage2'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
init_model=str(rpn_stage2_out['model_path']),
solver=solvers[3],
max_iters=max_iters[3],
cfg=cfg,
rpn_file=rpn_stage2_out['proposal_path'])
p = mp.Process(target=train_fast_rcnn, kwargs=mp_kwargs)
p.start()
fast_rcnn_stage2_out = mp_queue.get()
p.join()
# Create final model (just a copy of the last stage)
final_path = os.path.join(
os.path.dirname(fast_rcnn_stage2_out['model_path']),
args.net_name + '_faster_rcnn_final.caffemodel')
print 'cp {} -> {}'.format(
fast_rcnn_stage2_out['model_path'], final_path)
shutil.copy(fast_rcnn_stage2_out['model_path'], final_path)
print 'Final model: {}'.format(final_path)
| 12,767 | 36.116279 | 80 | py |
ADaPTION | ADaPTION-master/frcnn/tools/test_net.py | #!/usr/bin/env python
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Test a Fast R-CNN network on an image database."""
import _init_paths
from fast_rcnn.test import test_net
from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list
from datasets.factory import get_imdb
import caffe
import argparse
import pprint
import time, os, sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use',
default=0, type=int)
parser.add_argument('--def', dest='prototxt',
help='prototxt file defining the network',
default=None, type=str)
parser.add_argument('--net', dest='caffemodel',
help='model to test',
default=None, type=str)
parser.add_argument('--cfg', dest='cfg_file',
help='optional config file', default=None, type=str)
parser.add_argument('--wait', dest='wait',
help='wait until net file exists',
default=True, type=bool)
parser.add_argument('--imdb', dest='imdb_name',
help='dataset to test',
default='voc_2007_test', type=str)
parser.add_argument('--comp', dest='comp_mode', help='competition mode',
action='store_true')
parser.add_argument('--set', dest='set_cfgs',
help='set config keys', default=None,
nargs=argparse.REMAINDER)
parser.add_argument('--vis', dest='vis', help='visualize detections',
action='store_true')
parser.add_argument('--num_dets', dest='max_per_image',
help='max number of detections per image',
default=100, type=int)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
print('Called with args:')
print(args)
if args.cfg_file is not None:
cfg_from_file(args.cfg_file)
if args.set_cfgs is not None:
cfg_from_list(args.set_cfgs)
cfg.GPU_ID = args.gpu_id
print('Using config:')
pprint.pprint(cfg)
while not os.path.exists(args.caffemodel) and args.wait:
print('Waiting for {} to exist...'.format(args.caffemodel))
time.sleep(10)
caffe.set_mode_gpu()
caffe.set_device(args.gpu_id)
net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST)
net.name = os.path.splitext(os.path.basename(args.caffemodel))[0]
imdb = get_imdb(args.imdb_name)
imdb.competition_mode(args.comp_mode)
if not cfg.TEST.HAS_RPN:
imdb.set_proposal_method(cfg.TEST.PROPOSAL_METHOD)
test_net(net, imdb, max_per_image=args.max_per_image, vis=args.vis)
| 3,165 | 33.791209 | 77 | py |
ADaPTION | ADaPTION-master/frcnn/tools/_init_paths.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Set up paths for Fast R-CNN."""
import os.path as osp
import sys
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
this_dir = osp.dirname(__file__)
# Add caffe to PYTHONPATH
# caffe_path = osp.join(this_dir, '..', 'caffe-fast-rcnn', 'python')
caffe_path = osp.join(this_dir, '../..', 'python')
add_path(caffe_path)
# Add lib to PYTHONPATH
lib_path = osp.join(this_dir, '..', 'lib')
add_path(lib_path)
| 690 | 24.592593 | 68 | py |
ADaPTION | ADaPTION-master/frcnn/tools/demo.py | #!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""
Demo script showing detections in sample images.
See README.md for installation instructions before running.
"""
import _init_paths
from fast_rcnn.config import cfg
from fast_rcnn.test import im_detect
from fast_rcnn.nms_wrapper import nms
from utils.timer import Timer
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import caffe
import os
import sys
import cv2
import argparse
CLASSES = ('__background__',
'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'diningtable', 'dog', 'horse',
'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'tvmonitor')
NETS = {'vgg16': ('VGG16',
'VGG16_faster_rcnn_final.caffemodel'),
'zf': ('ZF',
'ZF_faster_rcnn_final.caffemodel')}
def vis_detections(im, class_name, dets, thresh=0.5):
"""Draw detected bounding boxes."""
inds = np.where(dets[:, -1] >= thresh)[0]
if len(inds) == 0:
return
im = im[:, :, (2, 1, 0)]
fig, ax = plt.subplots(figsize=(12, 12))
ax.imshow(im, aspect='equal')
for i in inds:
bbox = dets[i, :4]
score = dets[i, -1]
ax.add_patch(
plt.Rectangle((bbox[0], bbox[1]),
bbox[2] - bbox[0],
bbox[3] - bbox[1], fill=False,
edgecolor='red', linewidth=3.5)
)
ax.text(bbox[0], bbox[1] - 2,
'{:s} {:.3f}'.format(class_name, score),
bbox=dict(facecolor='blue', alpha=0.5),
fontsize=14, color='white')
ax.set_title(('{} detections with '
'p({} | box) >= {:.1f}').format(class_name, class_name,
thresh),
fontsize=14)
plt.axis('off')
plt.tight_layout()
plt.draw()
def demo(net, image_name):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image
im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name)
im = cv2.imread(im_file)
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores, boxes = im_detect(net, im)
timer.toc()
print ('Detection took {:.3f}s for '
'{:d} object proposals').format(timer.total_time, boxes.shape[0])
# Visualize detections for each class
CONF_THRESH = 0.8
NMS_THRESH = 0.3
for cls_ind, cls in enumerate(CLASSES[1:]):
cls_ind += 1 # because we skipped background
cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)]
cls_scores = scores[:, cls_ind]
dets = np.hstack((cls_boxes,
cls_scores[:, np.newaxis])).astype(np.float32)
keep = nms(dets, NMS_THRESH)
dets = dets[keep, :]
vis_detections(im, cls, dets, thresh=CONF_THRESH)
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument('--cpu', dest='cpu_mode',
help='Use CPU mode (overrides --gpu)',
action='store_true')
parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]',
choices=NETS.keys(), default='vgg16')
args = parser.parse_args()
return args
if __name__ == '__main__':
cfg.TEST.HAS_RPN = True # Use RPN for proposals
args = parse_args()
prototxt = os.path.join(cfg.MODELS_DIR, NETS[args.demo_net][0],
'faster_rcnn_alt_opt', 'faster_rcnn_test.pt')
caffemodel = os.path.join(cfg.DATA_DIR, 'faster_rcnn_models',
NETS[args.demo_net][1])
if not os.path.isfile(caffemodel):
raise IOError(('{:s} not found.\nDid you run ./data/script/'
'fetch_faster_rcnn_models.sh?').format(caffemodel))
if args.cpu_mode:
caffe.set_mode_cpu()
else:
caffe.set_mode_gpu()
caffe.set_device(args.gpu_id)
cfg.GPU_ID = args.gpu_id
print caffe.TEST
net = caffe.Net(prototxt, caffemodel, caffe.TEST)
print '\n\nLoaded network {:s}'.format(caffemodel)
# Warmup on a dummy image
im = 128 * np.ones((300, 500, 3), dtype=np.uint8)
for i in xrange(2):
_, _ = im_detect(net, im)
im_names = ['000456.jpg', '000542.jpg', '001150.jpg',
'001763.jpg', '004545.jpg']
for im_name in im_names:
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Demo for data/demo/{}'.format(im_name)
demo(net, im_name)
plt.show()
| 5,067 | 31.075949 | 80 | py |
ADaPTION | ADaPTION-master/frcnn/tools/lp_train_faster_rcnn_alt_opt.py | #!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a Faster R-CNN network using alternating optimization.
This tool implements the alternating optimization algorithm described in our
NIPS 2015 paper ("Faster R-CNN: Towards Real-time Object Detection with Region
Proposal Networks." Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun.)
"""
import _init_paths
from fast_rcnn.train import get_training_roidb, train_net
from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list, get_output_dir
from datasets.factory import get_imdb
from rpn.generate import imdb_proposals
import argparse
import pprint
import numpy as np
import sys
import os
import multiprocessing as mp
import cPickle
import shutil
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Faster R-CNN network')
parser.add_argument('--gpu', dest='gpu_id',
help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument('--net_name', dest='net_name',
help='network name (e.g., "ZF")',
default=None, type=str)
parser.add_argument('--weights', dest='pretrained_model',
help='initialize with pretrained model weights',
default=None, type=str)
parser.add_argument('--cfg', dest='cfg_file',
help='optional config file',
default=None, type=str)
parser.add_argument('--imdb', dest='imdb_name',
help='dataset to train on',
default='voc_2007_trainval', type=str)
parser.add_argument('--set', dest='set_cfgs',
help='set config keys', default=None,
nargs=argparse.REMAINDER)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
def get_roidb(imdb_name, rpn_file=None):
imdb = get_imdb(imdb_name)
print 'Loaded dataset `{:s}` for training'.format(imdb.name)
imdb.set_proposal_method(cfg.TRAIN.PROPOSAL_METHOD)
print 'Set proposal method: {:s}'.format(cfg.TRAIN.PROPOSAL_METHOD)
if rpn_file is not None:
imdb.config['rpn_file'] = rpn_file
roidb = get_training_roidb(imdb)
return roidb, imdb
def get_solvers(net_name):
# Faster R-CNN Alternating Optimization
n = 'faster_rcnn_alt_opt'
# Solver for each training stage
solvers = [[net_name, n, 'stage1_rpn_solver60k80k.pt'],
[net_name, n, 'stage1_fast_rcnn_solver30k40k.pt'],
[net_name, n, 'stage2_rpn_solver60k80k.pt'],
[net_name, n, 'stage2_fast_rcnn_solver30k40k.pt']]
solvers = [os.path.join(cfg.MODELS_DIR, *s) for s in solvers]
# Iterations for each training stage
max_iters = [160000, 80000, 160000, 80000]
# max_iters = [100, 100, 100, 100]
# max_iters = [40, 40, 40, 40]
# Test prototxt for the RPN
rpn_test_prototxt = os.path.join(
cfg.MODELS_DIR, net_name, n, 'lp_rpn_test.pt')
return solvers, max_iters, rpn_test_prototxt
# ------------------------------------------------------------------------------
# Pycaffe doesn't reliably free GPU memory when instantiated nets are discarded
# (e.g. "del net" in Python code). To work around this issue, each training
# stage is executed in a separate process using multiprocessing.Process.
# ------------------------------------------------------------------------------
def _init_caffe(cfg):
"""Initialize pycaffe in a training process.
"""
import caffe
# fix the random seeds (numpy and caffe) for reproducibility
np.random.seed(cfg.RNG_SEED)
caffe.set_random_seed(cfg.RNG_SEED)
# set up caffe
caffe.set_mode_gpu()
caffe.set_device(cfg.GPU_ID)
def train_rpn(queue=None, imdb_name=None, init_model=None, solver=None,
max_iters=None, cfg=None):
"""Train a Region Proposal Network in a separate training process.
"""
# Not using any proposals, just ground-truth boxes
cfg.TRAIN.HAS_RPN = True
cfg.TRAIN.BBOX_REG = False # applies only to Fast R-CNN bbox regression
cfg.TRAIN.PROPOSAL_METHOD = 'gt'
cfg.TRAIN.IMS_PER_BATCH = 1
print 'Init model: {}'.format(init_model)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
roidb, imdb = get_roidb(imdb_name)
print 'roidb len: {}'.format(len(roidb))
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
model_paths = train_net(solver, roidb, output_dir,
pretrained_model=init_model,
max_iters=max_iters)
# Cleanup all but the final model
for i in model_paths[:-1]:
os.remove(i)
rpn_model_path = model_paths[-1]
# Send final model path through the multiprocessing queue
queue.put({'model_path': rpn_model_path})
def rpn_generate(queue=None, imdb_name=None, rpn_model_path=None, cfg=None,
rpn_test_prototxt=None):
"""Use a trained RPN to generate proposals.
"""
cfg.TEST.RPN_PRE_NMS_TOP_N = -1 # no pre NMS filtering
cfg.TEST.RPN_POST_NMS_TOP_N = 2000 # limit top boxes after NMS
print 'RPN model: {}'.format(rpn_model_path)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
# NOTE: the matlab implementation computes proposals on flipped images, too.
# We compute them on the image once and then flip the already computed
# proposals. This might cause a minor loss in mAP (less proposal jittering).
imdb = get_imdb(imdb_name)
print 'Loaded dataset `{:s}` for proposal generation'.format(imdb.name)
# Load RPN and configure output directory
rpn_net = caffe.Net(rpn_test_prototxt, rpn_model_path, caffe.TEST)
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
# Generate proposals on the imdb
rpn_proposals = imdb_proposals(rpn_net, imdb)
# Write proposals to disk and send the proposal file path through the
# multiprocessing queue
rpn_net_name = os.path.splitext(os.path.basename(rpn_model_path))[0]
rpn_proposals_path = os.path.join(
output_dir, rpn_net_name + '_proposals.pkl')
with open(rpn_proposals_path, 'wb') as f:
cPickle.dump(rpn_proposals, f, cPickle.HIGHEST_PROTOCOL)
print 'Wrote RPN proposals to {}'.format(rpn_proposals_path)
queue.put({'proposal_path': rpn_proposals_path})
def train_fast_rcnn(queue=None, imdb_name=None, init_model=None, solver=None,
max_iters=None, cfg=None, rpn_file=None):
"""Train a Fast R-CNN using proposals generated by an RPN.
"""
cfg.TRAIN.HAS_RPN = False # not generating prosals on-the-fly
cfg.TRAIN.PROPOSAL_METHOD = 'rpn' # use pre-computed RPN proposals instead
cfg.TRAIN.IMS_PER_BATCH = 2
print 'Init model: {}'.format(init_model)
print 'RPN proposals: {}'.format(rpn_file)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
roidb, imdb = get_roidb(imdb_name, rpn_file=rpn_file)
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
# Train Fast R-CNN
model_paths = train_net(solver, roidb, output_dir,
pretrained_model=init_model,
max_iters=max_iters)
# Cleanup all but the final model
for i in model_paths[:-1]:
os.remove(i)
fast_rcnn_model_path = model_paths[-1]
# Send Fast R-CNN model path over the multiprocessing queue
queue.put({'model_path': fast_rcnn_model_path})
if __name__ == '__main__':
args = parse_args()
print('Called with args:')
print(args)
if args.cfg_file is not None:
cfg_from_file(args.cfg_file)
if args.set_cfgs is not None:
cfg_from_list(args.set_cfgs)
cfg.GPU_ID = args.gpu_id
# --------------------------------------------------------------------------
# Pycaffe doesn't reliably free GPU memory when instantiated nets are
# discarded (e.g. "del net" in Python code). To work around this issue, each
# training stage is executed in a separate process using
# multiprocessing.Process.
# --------------------------------------------------------------------------
# queue for communicated results between processes
mp_queue = mp.Queue()
# solves, iters, etc. for each training stage
solvers, max_iters, rpn_test_prototxt = get_solvers(args.net_name)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 1 RPN, init from ImageNet model'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
cfg.TRAIN.SNAPSHOT_INFIX = 'stage1'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
init_model=args.pretrained_model,
solver=solvers[0],
max_iters=max_iters[0],
cfg=cfg)
p = mp.Process(target=train_rpn, kwargs=mp_kwargs)
p.start()
rpn_stage1_out = mp_queue.get()
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 1 RPN, generate proposals'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
rpn_model_path=str(rpn_stage1_out['model_path']),
cfg=cfg,
rpn_test_prototxt=rpn_test_prototxt)
p = mp.Process(target=rpn_generate, kwargs=mp_kwargs)
p.start()
rpn_stage1_out['proposal_path'] = mp_queue.get()['proposal_path']
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 1 Fast R-CNN using RPN proposals, init from ImageNet model'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
cfg.TRAIN.SNAPSHOT_INFIX = 'stage1'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
init_model=args.pretrained_model,
solver=solvers[1],
max_iters=max_iters[1],
cfg=cfg,
rpn_file=rpn_stage1_out['proposal_path'])
p = mp.Process(target=train_fast_rcnn, kwargs=mp_kwargs)
p.start()
fast_rcnn_stage1_out = mp_queue.get()
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 2 RPN, init from stage 1 Fast R-CNN model'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
cfg.TRAIN.SNAPSHOT_INFIX = 'stage2'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
init_model=str(fast_rcnn_stage1_out['model_path']),
solver=solvers[2],
max_iters=max_iters[2],
cfg=cfg)
p = mp.Process(target=train_rpn, kwargs=mp_kwargs)
p.start()
rpn_stage2_out = mp_queue.get()
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 2 RPN, generate proposals'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
rpn_model_path=str(rpn_stage2_out['model_path']),
cfg=cfg,
rpn_test_prototxt=rpn_test_prototxt)
p = mp.Process(target=rpn_generate, kwargs=mp_kwargs)
p.start()
rpn_stage2_out['proposal_path'] = mp_queue.get()['proposal_path']
p.join()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Stage 2 Fast R-CNN, init from stage 2 RPN R-CNN model'
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
cfg.TRAIN.SNAPSHOT_INFIX = 'stage2'
mp_kwargs = dict(
queue=mp_queue,
imdb_name=args.imdb_name,
init_model=str(rpn_stage2_out['model_path']),
solver=solvers[3],
max_iters=max_iters[3],
cfg=cfg,
rpn_file=rpn_stage2_out['proposal_path'])
p = mp.Process(target=train_fast_rcnn, kwargs=mp_kwargs)
p.start()
fast_rcnn_stage2_out = mp_queue.get()
p.join()
# Create final model (just a copy of the last stage)
final_path = os.path.join(
os.path.dirname(fast_rcnn_stage2_out['model_path']),
args.net_name + '_faster_rcnn_final.caffemodel')
print 'cp {} -> {}'.format(
fast_rcnn_stage2_out['model_path'], final_path)
shutil.copy(fast_rcnn_stage2_out['model_path'], final_path)
print 'Final model: {}'.format(final_path)
| 12,772 | 36.130814 | 80 | py |
ADaPTION | ADaPTION-master/frcnn/tools/train_svms.py | #!/usr/bin/env python
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""
Train post-hoc SVMs using the algorithm and hyper-parameters from
traditional R-CNN.
"""
import _init_paths
from fast_rcnn.config import cfg, cfg_from_file
from datasets.factory import get_imdb
from fast_rcnn.test import im_detect
from utils.timer import Timer
import caffe
import argparse
import pprint
import numpy as np
import numpy.random as npr
import cv2
from sklearn import svm
import os, sys
class SVMTrainer(object):
"""
Trains post-hoc detection SVMs for all classes using the algorithm
and hyper-parameters of traditional R-CNN.
"""
def __init__(self, net, imdb):
self.imdb = imdb
self.net = net
self.layer = 'fc7'
self.hard_thresh = -1.0001
self.neg_iou_thresh = 0.3
dim = net.params['cls_score'][0].data.shape[1]
scale = self._get_feature_scale()
print('Feature dim: {}'.format(dim))
print('Feature scale: {:.3f}'.format(scale))
self.trainers = [SVMClassTrainer(cls, dim, feature_scale=scale)
for cls in imdb.classes]
def _get_feature_scale(self, num_images=100):
TARGET_NORM = 20.0 # Magic value from traditional R-CNN
_t = Timer()
roidb = self.imdb.roidb
total_norm = 0.0
count = 0.0
inds = npr.choice(xrange(self.imdb.num_images), size=num_images,
replace=False)
for i_, i in enumerate(inds):
im = cv2.imread(self.imdb.image_path_at(i))
if roidb[i]['flipped']:
im = im[:, ::-1, :]
_t.tic()
scores, boxes = im_detect(self.net, im, roidb[i]['boxes'])
_t.toc()
feat = self.net.blobs[self.layer].data
total_norm += np.sqrt((feat ** 2).sum(axis=1)).sum()
count += feat.shape[0]
print('{}/{}: avg feature norm: {:.3f}'.format(i_ + 1, num_images,
total_norm / count))
return TARGET_NORM * 1.0 / (total_norm / count)
def _get_pos_counts(self):
counts = np.zeros((len(self.imdb.classes)), dtype=np.int)
roidb = self.imdb.roidb
for i in xrange(len(roidb)):
for j in xrange(1, self.imdb.num_classes):
I = np.where(roidb[i]['gt_classes'] == j)[0]
counts[j] += len(I)
for j in xrange(1, self.imdb.num_classes):
print('class {:s} has {:d} positives'.
format(self.imdb.classes[j], counts[j]))
return counts
def get_pos_examples(self):
counts = self._get_pos_counts()
for i in xrange(len(counts)):
self.trainers[i].alloc_pos(counts[i])
_t = Timer()
roidb = self.imdb.roidb
num_images = len(roidb)
# num_images = 100
for i in xrange(num_images):
im = cv2.imread(self.imdb.image_path_at(i))
if roidb[i]['flipped']:
im = im[:, ::-1, :]
gt_inds = np.where(roidb[i]['gt_classes'] > 0)[0]
gt_boxes = roidb[i]['boxes'][gt_inds]
_t.tic()
scores, boxes = im_detect(self.net, im, gt_boxes)
_t.toc()
feat = self.net.blobs[self.layer].data
for j in xrange(1, self.imdb.num_classes):
cls_inds = np.where(roidb[i]['gt_classes'][gt_inds] == j)[0]
if len(cls_inds) > 0:
cls_feat = feat[cls_inds, :]
self.trainers[j].append_pos(cls_feat)
print 'get_pos_examples: {:d}/{:d} {:.3f}s' \
.format(i + 1, len(roidb), _t.average_time)
def initialize_net(self):
# Start all SVM parameters at zero
self.net.params['cls_score'][0].data[...] = 0
self.net.params['cls_score'][1].data[...] = 0
# Initialize SVMs in a smart way. Not doing this because its such
# a good initialization that we might not learn something close to
# the SVM solution.
# # subtract background weights and biases for the foreground classes
# w_bg = self.net.params['cls_score'][0].data[0, :]
# b_bg = self.net.params['cls_score'][1].data[0]
# self.net.params['cls_score'][0].data[1:, :] -= w_bg
# self.net.params['cls_score'][1].data[1:] -= b_bg
# # set the background weights and biases to 0 (where they shall remain)
# self.net.params['cls_score'][0].data[0, :] = 0
# self.net.params['cls_score'][1].data[0] = 0
def update_net(self, cls_ind, w, b):
self.net.params['cls_score'][0].data[cls_ind, :] = w
self.net.params['cls_score'][1].data[cls_ind] = b
def train_with_hard_negatives(self):
_t = Timer()
roidb = self.imdb.roidb
num_images = len(roidb)
# num_images = 100
for i in xrange(num_images):
im = cv2.imread(self.imdb.image_path_at(i))
if roidb[i]['flipped']:
im = im[:, ::-1, :]
_t.tic()
scores, boxes = im_detect(self.net, im, roidb[i]['boxes'])
_t.toc()
feat = self.net.blobs[self.layer].data
for j in xrange(1, self.imdb.num_classes):
hard_inds = \
np.where((scores[:, j] > self.hard_thresh) &
(roidb[i]['gt_overlaps'][:, j].toarray().ravel() <
self.neg_iou_thresh))[0]
if len(hard_inds) > 0:
hard_feat = feat[hard_inds, :].copy()
new_w_b = \
self.trainers[j].append_neg_and_retrain(feat=hard_feat)
if new_w_b is not None:
self.update_net(j, new_w_b[0], new_w_b[1])
print(('train_with_hard_negatives: '
'{:d}/{:d} {:.3f}s').format(i + 1, len(roidb),
_t.average_time))
def train(self):
# Initialize SVMs using
# a. w_i = fc8_w_i - fc8_w_0
# b. b_i = fc8_b_i - fc8_b_0
# c. Install SVMs into net
self.initialize_net()
# Pass over roidb to count num positives for each class
# a. Pre-allocate arrays for positive feature vectors
# Pass over roidb, computing features for positives only
self.get_pos_examples()
# Pass over roidb
# a. Compute cls_score with forward pass
# b. For each class
# i. Select hard negatives
# ii. Add them to cache
# c. For each class
# i. If SVM retrain criteria met, update SVM
# ii. Install new SVM into net
self.train_with_hard_negatives()
# One final SVM retraining for each class
# Install SVMs into net
for j in xrange(1, self.imdb.num_classes):
new_w_b = self.trainers[j].append_neg_and_retrain(force=True)
self.update_net(j, new_w_b[0], new_w_b[1])
class SVMClassTrainer(object):
"""Manages post-hoc SVM training for a single object class."""
def __init__(self, cls, dim, feature_scale=1.0,
C=0.001, B=10.0, pos_weight=2.0):
self.pos = np.zeros((0, dim), dtype=np.float32)
self.neg = np.zeros((0, dim), dtype=np.float32)
self.B = B
self.C = C
self.cls = cls
self.pos_weight = pos_weight
self.dim = dim
self.feature_scale = feature_scale
self.svm = svm.LinearSVC(C=C, class_weight={1: 2, -1: 1},
intercept_scaling=B, verbose=1,
penalty='l2', loss='l1',
random_state=cfg.RNG_SEED, dual=True)
self.pos_cur = 0
self.num_neg_added = 0
self.retrain_limit = 2000
self.evict_thresh = -1.1
self.loss_history = []
def alloc_pos(self, count):
self.pos_cur = 0
self.pos = np.zeros((count, self.dim), dtype=np.float32)
def append_pos(self, feat):
num = feat.shape[0]
self.pos[self.pos_cur:self.pos_cur + num, :] = feat
self.pos_cur += num
def train(self):
print('>>> Updating {} detector <<<'.format(self.cls))
num_pos = self.pos.shape[0]
num_neg = self.neg.shape[0]
print('Cache holds {} pos examples and {} neg examples'.
format(num_pos, num_neg))
X = np.vstack((self.pos, self.neg)) * self.feature_scale
y = np.hstack((np.ones(num_pos),
-np.ones(num_neg)))
self.svm.fit(X, y)
w = self.svm.coef_
b = self.svm.intercept_[0]
scores = self.svm.decision_function(X)
pos_scores = scores[:num_pos]
neg_scores = scores[num_pos:]
pos_loss = (self.C * self.pos_weight *
np.maximum(0, 1 - pos_scores).sum())
neg_loss = self.C * np.maximum(0, 1 + neg_scores).sum()
reg_loss = 0.5 * np.dot(w.ravel(), w.ravel()) + 0.5 * b ** 2
tot_loss = pos_loss + neg_loss + reg_loss
self.loss_history.append((tot_loss, pos_loss, neg_loss, reg_loss))
for i, losses in enumerate(self.loss_history):
print((' {:d}: obj val: {:.3f} = {:.3f} '
'(pos) + {:.3f} (neg) + {:.3f} (reg)').format(i, *losses))
# Sanity check
scores_ret = (
X * 1.0 / self.feature_scale).dot(w.T * self.feature_scale) + b
assert np.allclose(scores, scores_ret[:, 0], atol=1e-5), \
"Scores from returned model don't match decision function"
return ((w * self.feature_scale, b), pos_scores, neg_scores)
def append_neg_and_retrain(self, feat=None, force=False):
if feat is not None:
num = feat.shape[0]
self.neg = np.vstack((self.neg, feat))
self.num_neg_added += num
if self.num_neg_added > self.retrain_limit or force:
self.num_neg_added = 0
new_w_b, pos_scores, neg_scores = self.train()
# scores = np.dot(self.neg, new_w_b[0].T) + new_w_b[1]
# easy_inds = np.where(neg_scores < self.evict_thresh)[0]
not_easy_inds = np.where(neg_scores >= self.evict_thresh)[0]
if len(not_easy_inds) > 0:
self.neg = self.neg[not_easy_inds, :]
# self.neg = np.delete(self.neg, easy_inds)
print(' Pruning easy negatives')
print(' Cache holds {} pos examples and {} neg examples'.
format(self.pos.shape[0], self.neg.shape[0]))
print(' {} pos support vectors'.format((pos_scores <= 1).sum()))
print(' {} neg support vectors'.format((neg_scores >= -1).sum()))
return new_w_b
else:
return None
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train SVMs (old skool)')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument('--def', dest='prototxt',
help='prototxt file defining the network',
default=None, type=str)
parser.add_argument('--net', dest='caffemodel',
help='model to test',
default=None, type=str)
parser.add_argument('--cfg', dest='cfg_file',
help='optional config file', default=None, type=str)
parser.add_argument('--imdb', dest='imdb_name',
help='dataset to train on',
default='voc_2007_trainval', type=str)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
if __name__ == '__main__':
# Must turn this off to prevent issues when digging into the net blobs to
# pull out features (tricky!)
cfg.DEDUP_BOXES = 0
# Must turn this on because we use the test im_detect() method to harvest
# hard negatives
cfg.TEST.SVM = True
args = parse_args()
print('Called with args:')
print(args)
if args.cfg_file is not None:
cfg_from_file(args.cfg_file)
print('Using config:')
pprint.pprint(cfg)
# fix the random seed for reproducibility
np.random.seed(cfg.RNG_SEED)
# set up caffe
caffe.set_mode_gpu()
if args.gpu_id is not None:
caffe.set_device(args.gpu_id)
net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST)
net.name = os.path.splitext(os.path.basename(args.caffemodel))[0]
out = os.path.splitext(os.path.basename(args.caffemodel))[0] + '_svm'
out_dir = os.path.dirname(args.caffemodel)
imdb = get_imdb(args.imdb_name)
print 'Loaded dataset `{:s}` for training'.format(imdb.name)
# enhance roidb to contain flipped examples
if cfg.TRAIN.USE_FLIPPED:
print 'Appending horizontally-flipped training examples...'
imdb.append_flipped_images()
print 'done'
SVMTrainer(net, imdb).train()
filename = '{}/{}.caffemodel'.format(out_dir, out)
net.save(filename)
print 'Wrote svm model to: {:s}'.format(filename)
| 13,480 | 37.081921 | 80 | py |
ADaPTION | ADaPTION-master/frcnn/tools/rpn_generate.py | #!/usr/bin/env python
# --------------------------------------------------------
# Fast/er/ R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Generate RPN proposals."""
import _init_paths
import numpy as np
from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list, get_output_dir
from datasets.factory import get_imdb
from rpn.generate import imdb_proposals
import cPickle
import caffe
import argparse
import pprint
import time, os, sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use',
default=0, type=int)
parser.add_argument('--def', dest='prototxt',
help='prototxt file defining the network',
default=None, type=str)
parser.add_argument('--net', dest='caffemodel',
help='model to test',
default=None, type=str)
parser.add_argument('--cfg', dest='cfg_file',
help='optional config file', default=None, type=str)
parser.add_argument('--wait', dest='wait',
help='wait until net file exists',
default=True, type=bool)
parser.add_argument('--imdb', dest='imdb_name',
help='dataset to test',
default='voc_2007_test', type=str)
parser.add_argument('--set', dest='set_cfgs',
help='set config keys', default=None,
nargs=argparse.REMAINDER)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
print('Called with args:')
print(args)
if args.cfg_file is not None:
cfg_from_file(args.cfg_file)
if args.set_cfgs is not None:
cfg_from_list(args.set_cfgs)
cfg.GPU_ID = args.gpu_id
# RPN test settings
cfg.TEST.RPN_PRE_NMS_TOP_N = -1
cfg.TEST.RPN_POST_NMS_TOP_N = 2000
print('Using config:')
pprint.pprint(cfg)
while not os.path.exists(args.caffemodel) and args.wait:
print('Waiting for {} to exist...'.format(args.caffemodel))
time.sleep(10)
caffe.set_mode_gpu()
caffe.set_device(args.gpu_id)
net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST)
net.name = os.path.splitext(os.path.basename(args.caffemodel))[0]
imdb = get_imdb(args.imdb_name)
imdb_boxes = imdb_proposals(net, imdb)
output_dir = get_output_dir(imdb, net)
rpn_file = os.path.join(output_dir, net.name + '_rpn_proposals.pkl')
with open(rpn_file, 'wb') as f:
cPickle.dump(imdb_boxes, f, cPickle.HIGHEST_PROTOCOL)
print 'Wrote RPN proposals to {}'.format(rpn_file)
| 2,994 | 31.554348 | 78 | py |
ADaPTION | ADaPTION-master/frcnn/tools/train_net.py | #!/usr/bin/env python
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a Fast R-CNN network on a region of interest database."""
import _init_paths
from fast_rcnn.train import get_training_roidb, train_net
from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list, get_output_dir
from datasets.factory import get_imdb
import datasets.imdb
import caffe
import argparse
import pprint
import numpy as np
import sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id',
help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument('--solver', dest='solver',
help='solver prototxt',
default=None, type=str)
parser.add_argument('--iters', dest='max_iters',
help='number of iterations to train',
default=40000, type=int)
parser.add_argument('--weights', dest='pretrained_model',
help='initialize with pretrained model weights',
default=None, type=str)
parser.add_argument('--cfg', dest='cfg_file',
help='optional config file',
default=None, type=str)
parser.add_argument('--imdb', dest='imdb_name',
help='dataset to train on',
default='voc_2007_trainval', type=str)
parser.add_argument('--rand', dest='randomize',
help='randomize (do not use a fixed seed)',
action='store_true')
parser.add_argument('--set', dest='set_cfgs',
help='set config keys', default=None,
nargs=argparse.REMAINDER)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
def combined_roidb(imdb_names):
def get_roidb(imdb_name):
imdb = get_imdb(imdb_name)
print 'Loaded dataset `{:s}` for training'.format(imdb.name)
imdb.set_proposal_method(cfg.TRAIN.PROPOSAL_METHOD)
print 'Set proposal method: {:s}'.format(cfg.TRAIN.PROPOSAL_METHOD)
roidb = get_training_roidb(imdb)
return roidb
roidbs = [get_roidb(s) for s in imdb_names.split('+')]
roidb = roidbs[0]
if len(roidbs) > 1:
for r in roidbs[1:]:
roidb.extend(r)
imdb = datasets.imdb.imdb(imdb_names)
else:
imdb = get_imdb(imdb_names)
return imdb, roidb
if __name__ == '__main__':
args = parse_args()
print('Called with args:')
print(args)
if args.cfg_file is not None:
cfg_from_file(args.cfg_file)
if args.set_cfgs is not None:
cfg_from_list(args.set_cfgs)
cfg.GPU_ID = args.gpu_id
print('Using config:')
pprint.pprint(cfg)
if not args.randomize:
# fix the random seeds (numpy and caffe) for reproducibility
np.random.seed(cfg.RNG_SEED)
caffe.set_random_seed(cfg.RNG_SEED)
# set up caffe
caffe.set_mode_gpu()
caffe.set_device(args.gpu_id)
imdb, roidb = combined_roidb(args.imdb_name)
print '{:d} roidb entries'.format(len(roidb))
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
train_net(args.solver, roidb, output_dir,
pretrained_model=args.pretrained_model,
max_iters=args.max_iters)
| 3,747 | 32.168142 | 78 | py |
ADaPTION | ADaPTION-master/frcnn/lib/roi_data_layer/layer.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""The data layer used during training to train a Fast R-CNN network.
RoIDataLayer implements a Caffe Python layer.
"""
import caffe
from fast_rcnn.config import cfg
from roi_data_layer.minibatch import get_minibatch
import numpy as np
import yaml
from multiprocessing import Process, Queue
class RoIDataLayer(caffe.Layer):
"""Fast R-CNN data layer used for training."""
def _shuffle_roidb_inds(self):
"""Randomly permute the training roidb."""
if cfg.TRAIN.ASPECT_GROUPING:
widths = np.array([r['width'] for r in self._roidb])
heights = np.array([r['height'] for r in self._roidb])
horz = (widths >= heights)
vert = np.logical_not(horz)
horz_inds = np.where(horz)[0]
vert_inds = np.where(vert)[0]
inds = np.hstack((
np.random.permutation(horz_inds),
np.random.permutation(vert_inds)))
inds = np.reshape(inds, (-1, 2))
row_perm = np.random.permutation(np.arange(inds.shape[0]))
inds = np.reshape(inds[row_perm, :], (-1,))
self._perm = inds
else:
self._perm = np.random.permutation(np.arange(len(self._roidb)))
self._cur = 0
def _get_next_minibatch_inds(self):
"""Return the roidb indices for the next minibatch."""
if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]
self._cur += cfg.TRAIN.IMS_PER_BATCH
return db_inds
def _get_next_minibatch(self):
"""Return the blobs to be used for the next minibatch.
If cfg.TRAIN.USE_PREFETCH is True, then blobs will be computed in a
separate process and made available through self._blob_queue.
"""
if cfg.TRAIN.USE_PREFETCH:
return self._blob_queue.get()
else:
db_inds = self._get_next_minibatch_inds()
minibatch_db = [self._roidb[i] for i in db_inds]
return get_minibatch(minibatch_db, self._num_classes)
def set_roidb(self, roidb):
"""Set the roidb to be used by this layer during training."""
self._roidb = roidb
self._shuffle_roidb_inds()
if cfg.TRAIN.USE_PREFETCH:
self._blob_queue = Queue(10)
self._prefetch_process = BlobFetcher(self._blob_queue,
self._roidb,
self._num_classes)
self._prefetch_process.start()
# Terminate the child process when the parent exists
def cleanup():
print 'Terminating BlobFetcher'
self._prefetch_process.terminate()
self._prefetch_process.join()
import atexit
atexit.register(cleanup)
def setup(self, bottom, top):
"""Setup the RoIDataLayer."""
# parse the layer parameter string, which must be valid YAML
layer_params = yaml.load(self.param_str)
self._num_classes = layer_params['num_classes']
self._name_to_top_map = {}
# data blob: holds a batch of N images, each with 3 channels
idx = 0
top[idx].reshape(cfg.TRAIN.IMS_PER_BATCH, 3,
max(cfg.TRAIN.SCALES), cfg.TRAIN.MAX_SIZE)
self._name_to_top_map['data'] = idx
idx += 1
if cfg.TRAIN.HAS_RPN:
top[idx].reshape(1, 3)
self._name_to_top_map['im_info'] = idx
idx += 1
top[idx].reshape(1, 4)
self._name_to_top_map['gt_boxes'] = idx
idx += 1
else: # not using RPN
# rois blob: holds R regions of interest, each is a 5-tuple
# (n, x1, y1, x2, y2) specifying an image batch index n and a
# rectangle (x1, y1, x2, y2)
top[idx].reshape(1, 5)
self._name_to_top_map['rois'] = idx
idx += 1
# labels blob: R categorical labels in [0, ..., K] for K foreground
# classes plus background
top[idx].reshape(1)
self._name_to_top_map['labels'] = idx
idx += 1
if cfg.TRAIN.BBOX_REG:
# bbox_targets blob: R bounding-box regression targets with 4
# targets per class
top[idx].reshape(1, self._num_classes * 4)
self._name_to_top_map['bbox_targets'] = idx
idx += 1
# bbox_inside_weights blob: At most 4 targets per roi are active;
# thisbinary vector sepcifies the subset of active targets
top[idx].reshape(1, self._num_classes * 4)
self._name_to_top_map['bbox_inside_weights'] = idx
idx += 1
top[idx].reshape(1, self._num_classes * 4)
self._name_to_top_map['bbox_outside_weights'] = idx
idx += 1
print 'RoiDataLayer: name_to_top:', self._name_to_top_map
assert len(top) == len(self._name_to_top_map)
def forward(self, bottom, top):
"""Get blobs and copy them into this layer's top blob vector."""
blobs = self._get_next_minibatch()
for blob_name, blob in blobs.iteritems():
top_ind = self._name_to_top_map[blob_name]
# Reshape net's input blobs
top[top_ind].reshape(*(blob.shape))
# Copy data into net's input blobs
top[top_ind].data[...] = blob.astype(np.float32, copy=False)
def backward(self, top, propagate_down, bottom):
"""This layer does not propagate gradients."""
pass
def reshape(self, bottom, top):
"""Reshaping happens during the call to forward."""
pass
class BlobFetcher(Process):
"""Experimental class for prefetching blobs in a separate process."""
def __init__(self, queue, roidb, num_classes):
super(BlobFetcher, self).__init__()
self._queue = queue
self._roidb = roidb
self._num_classes = num_classes
self._perm = None
self._cur = 0
self._shuffle_roidb_inds()
# fix the random seed for reproducibility
np.random.seed(cfg.RNG_SEED)
def _shuffle_roidb_inds(self):
"""Randomly permute the training roidb."""
# TODO(rbg): remove duplicated code
self._perm = np.random.permutation(np.arange(len(self._roidb)))
self._cur = 0
def _get_next_minibatch_inds(self):
"""Return the roidb indices for the next minibatch."""
# TODO(rbg): remove duplicated code
if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]
self._cur += cfg.TRAIN.IMS_PER_BATCH
return db_inds
def run(self):
print 'BlobFetcher started'
while True:
db_inds = self._get_next_minibatch_inds()
minibatch_db = [self._roidb[i] for i in db_inds]
blobs = get_minibatch(minibatch_db, self._num_classes)
self._queue.put(blobs)
| 7,449 | 36.817259 | 81 | py |
ADaPTION | ADaPTION-master/frcnn/lib/roi_data_layer/minibatch.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Compute minibatch blobs for training a Fast R-CNN network."""
import numpy as np
import numpy.random as npr
import cv2
from fast_rcnn.config import cfg
from utils.blob import prep_im_for_blob, im_list_to_blob
def get_minibatch(roidb, num_classes):
"""Given a roidb, construct a minibatch sampled from it."""
num_images = len(roidb)
# Sample random scales to use for each image in this batch
random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),
size=num_images)
assert(cfg.TRAIN.BATCH_SIZE % num_images == 0), \
'num_images ({}) must divide BATCH_SIZE ({})'. \
format(num_images, cfg.TRAIN.BATCH_SIZE)
rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images
fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
# Get the input image blob, formatted for caffe
im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)
blobs = {'data': im_blob}
if cfg.TRAIN.HAS_RPN:
assert len(im_scales) == 1, "Single batch only"
assert len(roidb) == 1, "Single batch only"
# gt boxes: (x1, y1, x2, y2, cls)
gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]
gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)
gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :] * im_scales[0]
gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]
blobs['gt_boxes'] = gt_boxes
blobs['im_info'] = np.array(
[[im_blob.shape[2], im_blob.shape[3], im_scales[0]]],
dtype=np.float32)
else: # not using RPN
# Now, build the region of interest and label blobs
rois_blob = np.zeros((0, 5), dtype=np.float32)
labels_blob = np.zeros((0), dtype=np.float32)
bbox_targets_blob = np.zeros((0, 4 * num_classes), dtype=np.float32)
bbox_inside_blob = np.zeros(bbox_targets_blob.shape, dtype=np.float32)
# all_overlaps = []
for im_i in xrange(num_images):
labels, overlaps, im_rois, bbox_targets, bbox_inside_weights \
= _sample_rois(roidb[im_i], fg_rois_per_image, rois_per_image,
num_classes)
# Add to RoIs blob
rois = _project_im_rois(im_rois, im_scales[im_i])
batch_ind = im_i * np.ones((rois.shape[0], 1))
rois_blob_this_image = np.hstack((batch_ind, rois))
rois_blob = np.vstack((rois_blob, rois_blob_this_image))
# Add to labels, bbox targets, and bbox loss blobs
labels_blob = np.hstack((labels_blob, labels))
bbox_targets_blob = np.vstack((bbox_targets_blob, bbox_targets))
bbox_inside_blob = np.vstack((bbox_inside_blob, bbox_inside_weights))
# all_overlaps = np.hstack((all_overlaps, overlaps))
# For debug visualizations
# _vis_minibatch(im_blob, rois_blob, labels_blob, all_overlaps)
blobs['rois'] = rois_blob
blobs['labels'] = labels_blob
if cfg.TRAIN.BBOX_REG:
blobs['bbox_targets'] = bbox_targets_blob
blobs['bbox_inside_weights'] = bbox_inside_blob
blobs['bbox_outside_weights'] = \
np.array(bbox_inside_blob > 0).astype(np.float32)
return blobs
def _sample_rois(roidb, fg_rois_per_image, rois_per_image, num_classes):
"""Generate a random sample of RoIs comprising foreground and background
examples.
"""
# label = class RoI has max overlap with
labels = roidb['max_classes']
overlaps = roidb['max_overlaps']
rois = roidb['boxes']
# Select foreground RoIs as those with >= FG_THRESH overlap
fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0]
# Guard against the case when an image has fewer than fg_rois_per_image
# foreground RoIs
fg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_inds.size)
# Sample foreground regions without replacement
if fg_inds.size > 0:
fg_inds = npr.choice(
fg_inds, size=fg_rois_per_this_image, replace=False)
# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) &
(overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]
# Compute number of background RoIs to take from this image (guarding
# against there being fewer than desired)
bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image
bg_rois_per_this_image = np.minimum(bg_rois_per_this_image,
bg_inds.size)
# Sample foreground regions without replacement
if bg_inds.size > 0:
bg_inds = npr.choice(
bg_inds, size=bg_rois_per_this_image, replace=False)
# The indices that we're selecting (both fg and bg)
keep_inds = np.append(fg_inds, bg_inds)
# Select sampled values from various arrays:
labels = labels[keep_inds]
# Clamp labels for the background RoIs to 0
labels[fg_rois_per_this_image:] = 0
overlaps = overlaps[keep_inds]
rois = rois[keep_inds]
bbox_targets, bbox_inside_weights = _get_bbox_regression_labels(
roidb['bbox_targets'][keep_inds, :], num_classes)
return labels, overlaps, rois, bbox_targets, bbox_inside_weights
def _get_image_blob(roidb, scale_inds):
"""Builds an input blob from the images in the roidb at the specified
scales.
"""
num_images = len(roidb)
processed_ims = []
im_scales = []
for i in xrange(num_images):
im = cv2.imread(roidb[i]['image'])
if roidb[i]['flipped']:
im = im[:, ::-1, :]
target_size = cfg.TRAIN.SCALES[scale_inds[i]]
im, im_scale = prep_im_for_blob(im, cfg.PIXEL_MEANS, target_size,
cfg.TRAIN.MAX_SIZE)
im_scales.append(im_scale)
processed_ims.append(im)
# Create a blob to hold the input images
blob = im_list_to_blob(processed_ims)
return blob, im_scales
def _project_im_rois(im_rois, im_scale_factor):
"""Project image RoIs into the rescaled training image."""
rois = im_rois * im_scale_factor
return rois
def _get_bbox_regression_labels(bbox_target_data, num_classes):
"""Bounding-box regression targets are stored in a compact form in the
roidb.
This function expands those targets into the 4-of-4*K representation used
by the network (i.e. only one class has non-zero targets). The loss weights
are similarly expanded.
Returns:
bbox_target_data (ndarray): N x 4K blob of regression targets
bbox_inside_weights (ndarray): N x 4K blob of loss weights
"""
clss = bbox_target_data[:, 0]
bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)
bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)
inds = np.where(clss > 0)[0]
for ind in inds:
cls = clss[ind]
start = 4 * cls
end = start + 4
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
return bbox_targets, bbox_inside_weights
def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
"""Visualize a mini-batch for debugging."""
import matplotlib.pyplot as plt
for i in xrange(rois_blob.shape[0]):
rois = rois_blob[i, :]
im_ind = rois[0]
roi = rois[1:]
im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
im += cfg.PIXEL_MEANS
im = im[:, :, (2, 1, 0)]
im = im.astype(np.uint8)
cls = labels_blob[i]
plt.imshow(im)
print 'class: ', cls, ' overlap: ', overlaps[i]
plt.gca().add_patch(
plt.Rectangle((roi[0], roi[1]), roi[2] - roi[0],
roi[3] - roi[1], fill=False,
edgecolor='r', linewidth=3)
)
plt.show()
| 8,169 | 39.85 | 81 | py |
ADaPTION | ADaPTION-master/frcnn/lib/fast_rcnn/test.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Test a Fast R-CNN network on an imdb (image database)."""
from fast_rcnn.config import cfg, get_output_dir
from fast_rcnn.bbox_transform import clip_boxes, bbox_transform_inv
import argparse
from utils.timer import Timer
import numpy as np
import cv2
import caffe
from fast_rcnn.nms_wrapper import nms
import cPickle
from utils.blob import im_list_to_blob
import os
def _get_image_blob(im):
"""Converts an image into a network input.
Arguments:
im (ndarray): a color image in BGR order
Returns:
blob (ndarray): a data blob holding an image pyramid
im_scale_factors (list): list of image scales (relative to im) used
in the image pyramid
"""
im_orig = im.astype(np.float32, copy=True)
im_orig -= cfg.PIXEL_MEANS
im_shape = im_orig.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
processed_ims = []
im_scale_factors = []
for target_size in cfg.TEST.SCALES:
im_scale = float(target_size) / float(im_size_min)
# Prevent the biggest axis from being more than MAX_SIZE
if np.round(im_scale * im_size_max) > cfg.TEST.MAX_SIZE:
im_scale = float(cfg.TEST.MAX_SIZE) / float(im_size_max)
im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale,
interpolation=cv2.INTER_LINEAR)
im_scale_factors.append(im_scale)
processed_ims.append(im)
# Create a blob to hold the input images
blob = im_list_to_blob(processed_ims)
return blob, np.array(im_scale_factors)
def _get_rois_blob(im_rois, im_scale_factors):
"""Converts RoIs into network inputs.
Arguments:
im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
im_scale_factors (list): scale factors as returned by _get_image_blob
Returns:
blob (ndarray): R x 5 matrix of RoIs in the image pyramid
"""
rois, levels = _project_im_rois(im_rois, im_scale_factors)
rois_blob = np.hstack((levels, rois))
return rois_blob.astype(np.float32, copy=False)
def _project_im_rois(im_rois, scales):
"""Project image RoIs into the image pyramid built by _get_image_blob.
Arguments:
im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
scales (list): scale factors as returned by _get_image_blob
Returns:
rois (ndarray): R x 4 matrix of projected RoI coordinates
levels (list): image pyramid levels used by each projected RoI
"""
im_rois = im_rois.astype(np.float, copy=False)
if len(scales) > 1:
widths = im_rois[:, 2] - im_rois[:, 0] + 1
heights = im_rois[:, 3] - im_rois[:, 1] + 1
areas = widths * heights
scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2)
diff_areas = np.abs(scaled_areas - 224 * 224)
levels = diff_areas.argmin(axis=1)[:, np.newaxis]
else:
levels = np.zeros((im_rois.shape[0], 1), dtype=np.int)
rois = im_rois * scales[levels]
return rois, levels
def _get_blobs(im, rois):
"""Convert an image and RoIs within that image into network inputs."""
blobs = {'data': None, 'rois': None}
blobs['data'], im_scale_factors = _get_image_blob(im)
if not cfg.TEST.HAS_RPN:
blobs['rois'] = _get_rois_blob(rois, im_scale_factors)
return blobs, im_scale_factors
def im_detect(net, im, boxes=None):
"""Detect object classes in an image given object proposals.
Arguments:
net (caffe.Net): Fast R-CNN network to use
im (ndarray): color image to test (in BGR order)
boxes (ndarray): R x 4 array of object proposals or None (for RPN)
Returns:
scores (ndarray): R x K array of object class scores (K includes
background as object category 0)
boxes (ndarray): R x (4*K) array of predicted bounding boxes
"""
blobs, im_scales = _get_blobs(im, boxes)
# When mapping from image ROIs to feature map ROIs, there's some aliasing
# (some distinct image ROIs get mapped to the same feature ROI).
# Here, we identify duplicate feature ROIs, so we only compute features
# on the unique subset.
if cfg.DEDUP_BOXES > 0 and not cfg.TEST.HAS_RPN:
v = np.array([1, 1e3, 1e6, 1e9, 1e12])
hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v)
_, index, inv_index = np.unique(hashes, return_index=True,
return_inverse=True)
blobs['rois'] = blobs['rois'][index, :]
boxes = boxes[index, :]
if cfg.TEST.HAS_RPN:
im_blob = blobs['data']
blobs['im_info'] = np.array(
[[im_blob.shape[2], im_blob.shape[3], im_scales[0]]],
dtype=np.float32)
# reshape network inputs
net.blobs['data'].reshape(*(blobs['data'].shape))
if cfg.TEST.HAS_RPN:
net.blobs['im_info'].reshape(*(blobs['im_info'].shape))
else:
net.blobs['rois'].reshape(*(blobs['rois'].shape))
# do forward
forward_kwargs = {'data': blobs['data'].astype(np.float32, copy=False)}
if cfg.TEST.HAS_RPN:
forward_kwargs['im_info'] = blobs['im_info'].astype(np.float32, copy=False)
else:
forward_kwargs['rois'] = blobs['rois'].astype(np.float32, copy=False)
blobs_out = net.forward(**forward_kwargs)
if cfg.TEST.HAS_RPN:
assert len(im_scales) == 1, "Only single-image batch implemented"
rois = net.blobs['rois'].data.copy()
# unscale back to raw image space
boxes = rois[:, 1:5] / im_scales[0]
if cfg.TEST.SVM:
# use the raw scores before softmax under the assumption they
# were trained as linear SVMs
scores = net.blobs['cls_score'].data
else:
# use softmax estimated probabilities
scores = blobs_out['cls_prob']
if cfg.TEST.BBOX_REG:
# Apply bounding-box regression deltas
box_deltas = blobs_out['bbox_pred']
pred_boxes = bbox_transform_inv(boxes, box_deltas)
pred_boxes = clip_boxes(pred_boxes, im.shape)
else:
# Simply repeat the boxes, once for each class
pred_boxes = np.tile(boxes, (1, scores.shape[1]))
if cfg.DEDUP_BOXES > 0 and not cfg.TEST.HAS_RPN:
# Map scores and predictions back to the original set of boxes
scores = scores[inv_index, :]
pred_boxes = pred_boxes[inv_index, :]
return scores, pred_boxes
def vis_detections(im, class_name, dets, thresh=0.3):
"""Visual debugging of detections."""
import matplotlib.pyplot as plt
im = im[:, :, (2, 1, 0)]
for i in xrange(np.minimum(10, dets.shape[0])):
bbox = dets[i, :4]
score = dets[i, -1]
if score > thresh:
plt.cla()
plt.imshow(im)
plt.gca().add_patch(
plt.Rectangle((bbox[0], bbox[1]),
bbox[2] - bbox[0],
bbox[3] - bbox[1], fill=False,
edgecolor='g', linewidth=3)
)
plt.title('{} {:.3f}'.format(class_name, score))
plt.show()
def apply_nms(all_boxes, thresh):
"""Apply non-maximum suppression to all predicted boxes output by the
test_net method.
"""
num_classes = len(all_boxes)
num_images = len(all_boxes[0])
nms_boxes = [[[] for _ in xrange(num_images)]
for _ in xrange(num_classes)]
for cls_ind in xrange(num_classes):
for im_ind in xrange(num_images):
dets = all_boxes[cls_ind][im_ind]
if dets == []:
continue
# CPU NMS is much faster than GPU NMS when the number of boxes
# is relative small (e.g., < 10k)
# TODO(rbg): autotune NMS dispatch
keep = nms(dets, thresh, force_cpu=True)
if len(keep) == 0:
continue
nms_boxes[cls_ind][im_ind] = dets[keep, :].copy()
return nms_boxes
def test_net(net, imdb, max_per_image=100, thresh=0.05, vis=False):
"""Test a Fast R-CNN network on an image database."""
num_images = len(imdb.image_index)
# all detections are collected into:
# all_boxes[cls][image] = N x 5 array of detections in
# (x1, y1, x2, y2, score)
all_boxes = [[[] for _ in xrange(num_images)]
for _ in xrange(imdb.num_classes)]
output_dir = get_output_dir(imdb, net)
# timers
_t = {'im_detect': Timer(), 'misc': Timer()}
if not cfg.TEST.HAS_RPN:
roidb = imdb.roidb
for i in xrange(num_images):
# filter out any ground truth boxes
if cfg.TEST.HAS_RPN:
box_proposals = None
else:
# The roidb may contain ground-truth rois (for example, if the roidb
# comes from the training or val split). We only want to evaluate
# detection on the *non*-ground-truth rois. We select those the rois
# that have the gt_classes field set to 0, which means there's no
# ground truth.
box_proposals = roidb[i]['boxes'][roidb[i]['gt_classes'] == 0]
im = cv2.imread(imdb.image_path_at(i))
_t['im_detect'].tic()
scores, boxes = im_detect(net, im, box_proposals)
_t['im_detect'].toc()
_t['misc'].tic()
# skip j = 0, because it's the background class
for j in xrange(1, imdb.num_classes):
inds = np.where(scores[:, j] > thresh)[0]
cls_scores = scores[inds, j]
cls_boxes = boxes[inds, j * 4:(j + 1) * 4]
cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \
.astype(np.float32, copy=False)
keep = nms(cls_dets, cfg.TEST.NMS)
cls_dets = cls_dets[keep, :]
if vis:
vis_detections(im, imdb.classes[j], cls_dets)
all_boxes[j][i] = cls_dets
# Limit to max_per_image detections *over all classes*
if max_per_image > 0:
image_scores = np.hstack([all_boxes[j][i][:, -1]
for j in xrange(1, imdb.num_classes)])
if len(image_scores) > max_per_image:
image_thresh = np.sort(image_scores)[-max_per_image]
for j in xrange(1, imdb.num_classes):
keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0]
all_boxes[j][i] = all_boxes[j][i][keep, :]
_t['misc'].toc()
print 'im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \
.format(i + 1, num_images, _t['im_detect'].average_time,
_t['misc'].average_time)
det_file = os.path.join(output_dir, 'detections.pkl')
with open(det_file, 'wb') as f:
cPickle.dump(all_boxes, f, cPickle.HIGHEST_PROTOCOL)
print 'Evaluating detections'
imdb.evaluate_detections(all_boxes, output_dir)
| 11,126 | 35.601974 | 83 | py |
ADaPTION | ADaPTION-master/frcnn/lib/fast_rcnn/config.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Fast R-CNN config system.
This file specifies default config options for Fast R-CNN. You should not
change values in this file. Instead, you should write a config file (in yaml)
and use cfg_from_file(yaml_file) to load it and override the default options.
Most tools in $ROOT/tools take a --cfg option to specify an override file.
- See tools/{train,test}_net.py for example code that uses cfg_from_file()
- See experiments/cfgs/*.yml for example YAML config override files
"""
import os
import os.path as osp
import numpy as np
# `pip install easydict` if you don't have it
from easydict import EasyDict as edict
__C = edict()
# Consumers can get config by:
# from fast_rcnn_config import cfg
cfg = __C
#
# Training options
#
__C.TRAIN = edict()
# Scales to use during training (can list multiple scales)
# Each scale is the pixel size of an image's shortest side
__C.TRAIN.SCALES = (600,)
# Max pixel size of the longest side of a scaled input image
__C.TRAIN.MAX_SIZE = 1000
# Images to use per minibatch
__C.TRAIN.IMS_PER_BATCH = 2
# Minibatch size (number of regions of interest [ROIs])
__C.TRAIN.BATCH_SIZE = 128
# Fraction of minibatch that is labeled foreground (i.e. class > 0)
__C.TRAIN.FG_FRACTION = 0.25
# Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH)
__C.TRAIN.FG_THRESH = 0.5
# Overlap threshold for a ROI to be considered background (class = 0 if
# overlap in [LO, HI))
__C.TRAIN.BG_THRESH_HI = 0.5
__C.TRAIN.BG_THRESH_LO = 0.1
# Use horizontally-flipped images during training?
__C.TRAIN.USE_FLIPPED = True
# Train bounding-box regressors
__C.TRAIN.BBOX_REG = True
# Overlap required between a ROI and ground-truth box in order for that ROI to
# be used as a bounding-box regression training example
__C.TRAIN.BBOX_THRESH = 0.5
# Iterations between snapshots
__C.TRAIN.SNAPSHOT_ITERS = 10000
# solver.prototxt specifies the snapshot path prefix, this adds an optional
# infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel
__C.TRAIN.SNAPSHOT_INFIX = ''
# Use a prefetch thread in roi_data_layer.layer
# So far I haven't found this useful; likely more engineering work is required
__C.TRAIN.USE_PREFETCH = False
# Normalize the targets (subtract empirical mean, divide by empirical stddev)
__C.TRAIN.BBOX_NORMALIZE_TARGETS = True
# Deprecated (inside weights)
__C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
# Normalize the targets using "precomputed" (or made up) means and stdevs
# (BBOX_NORMALIZE_TARGETS must also be True)
__C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = False
__C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0)
__C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2)
# Train using these proposals
__C.TRAIN.PROPOSAL_METHOD = 'selective_search'
# Make minibatches from images that have similar aspect ratios (i.e. both
# tall and thin or both short and wide) in order to avoid wasting computation
# on zero-padding.
__C.TRAIN.ASPECT_GROUPING = True
# Use RPN to detect objects
__C.TRAIN.HAS_RPN = False
# IOU >= thresh: positive example
__C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7
# IOU < thresh: negative example
__C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3
# If an anchor statisfied by positive and negative conditions set to negative
__C.TRAIN.RPN_CLOBBER_POSITIVES = False
# Max number of foreground examples
__C.TRAIN.RPN_FG_FRACTION = 0.5
# Total number of examples
__C.TRAIN.RPN_BATCHSIZE = 256
# NMS threshold used on RPN proposals
__C.TRAIN.RPN_NMS_THRESH = 0.7
# Number of top scoring boxes to keep before apply NMS to RPN proposals
__C.TRAIN.RPN_PRE_NMS_TOP_N = 12000
# Number of top scoring boxes to keep after applying NMS to RPN proposals
__C.TRAIN.RPN_POST_NMS_TOP_N = 2000
# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)
__C.TRAIN.RPN_MIN_SIZE = 16
# Deprecated (outside weights)
__C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
# Give the positive RPN examples weight of p * 1 / {num positives}
# and give negatives a weight of (1 - p)
# Set to -1.0 to use uniform example weighting
__C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0
#
# Testing options
#
__C.TEST = edict()
# Scales to use during testing (can list multiple scales)
# Each scale is the pixel size of an image's shortest side
__C.TEST.SCALES = (600,)
# Max pixel size of the longest side of a scaled input image
__C.TEST.MAX_SIZE = 1000
# Overlap threshold used for non-maximum suppression (suppress boxes with
# IoU >= this threshold)
__C.TEST.NMS = 0.3
# Experimental: treat the (K+1) units in the cls_score layer as linear
# predictors (trained, eg, with one-vs-rest SVMs).
__C.TEST.SVM = False
# Test using bounding-box regressors
__C.TEST.BBOX_REG = True
# Propose boxes
__C.TEST.HAS_RPN = False
# Test using these proposals
__C.TEST.PROPOSAL_METHOD = 'selective_search'
## NMS threshold used on RPN proposals
__C.TEST.RPN_NMS_THRESH = 0.7
## Number of top scoring boxes to keep before apply NMS to RPN proposals
__C.TEST.RPN_PRE_NMS_TOP_N = 6000
## Number of top scoring boxes to keep after applying NMS to RPN proposals
__C.TEST.RPN_POST_NMS_TOP_N = 300
# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)
__C.TEST.RPN_MIN_SIZE = 16
#
# MISC
#
# The mapping from image coordinates to feature map coordinates might cause
# some boxes that are distinct in image space to become identical in feature
# coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor
# for identifying duplicate boxes.
# 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16
__C.DEDUP_BOXES = 1./16.
# Pixel mean values (BGR order) as a (1, 1, 3) array
# We use the same pixel mean for all networks even though it's not exactly what
# they were trained with
__C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]])
# For reproducibility
__C.RNG_SEED = 3
# A small number that's used many times
__C.EPS = 1e-14
# Root directory of project
__C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..'))
# Data directory
__C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data'))
# Model directory
__C.MODELS_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'models', 'pascal_voc'))
# Name (or path to) the matlab executable
__C.MATLAB = 'matlab'
# Place outputs under an experiments directory
__C.EXP_DIR = 'default'
# Use GPU implementation of non-maximum suppression
__C.USE_GPU_NMS = True
# Default GPU device id
__C.GPU_ID = 0
def get_output_dir(imdb, net=None):
"""Return the directory where experimental artifacts are placed.
If the directory does not exist, it is created.
A canonical path is built using the name from an imdb and a network
(if not None).
"""
outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))
if net is not None:
outdir = osp.join(outdir, net.name)
if not os.path.exists(outdir):
os.makedirs(outdir)
return outdir
def _merge_a_into_b(a, b):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
if type(a) is not edict:
return
for k, v in a.iteritems():
# a must specify keys that are in b
if not b.has_key(k):
raise KeyError('{} is not a valid config key'.format(k))
# the types must match, too
old_type = type(b[k])
if old_type is not type(v):
if isinstance(b[k], np.ndarray):
v = np.array(v, dtype=b[k].dtype)
else:
raise ValueError(('Type mismatch ({} vs. {}) '
'for config key: {}').format(type(b[k]),
type(v), k))
# recursively merge dicts
if type(v) is edict:
try:
_merge_a_into_b(a[k], b[k])
except:
print('Error under config key: {}'.format(k))
raise
else:
b[k] = v
def cfg_from_file(filename):
"""Load a config file and merge it into the default options."""
import yaml
with open(filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
_merge_a_into_b(yaml_cfg, __C)
def cfg_from_list(cfg_list):
"""Set config keys via list (e.g., from command line)."""
from ast import literal_eval
assert len(cfg_list) % 2 == 0
for k, v in zip(cfg_list[0::2], cfg_list[1::2]):
key_list = k.split('.')
d = __C
for subkey in key_list[:-1]:
assert d.has_key(subkey)
d = d[subkey]
subkey = key_list[-1]
assert d.has_key(subkey)
try:
value = literal_eval(v)
except:
# handle the case when v is a string literal
value = v
assert type(value) == type(d[subkey]), \
'type {} does not match original type {}'.format(
type(value), type(d[subkey]))
d[subkey] = value
| 9,213 | 31.216783 | 91 | py |
ADaPTION | ADaPTION-master/frcnn/lib/fast_rcnn/train.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a Fast R-CNN network."""
import caffe
from fast_rcnn.config import cfg
import roi_data_layer.roidb as rdl_roidb
from utils.timer import Timer
import numpy as np
import os
from caffe.proto import caffe_pb2
import google.protobuf as pb2
class SolverWrapper(object):
"""A simple wrapper around Caffe's solver.
This wrapper gives us control over he snapshotting process, which we
use to unnormalize the learned bounding-box regression weights.
"""
def __init__(self, solver_prototxt, roidb, output_dir,
pretrained_model=None):
"""Initialize the SolverWrapper."""
self.output_dir = output_dir
if (cfg.TRAIN.HAS_RPN and cfg.TRAIN.BBOX_REG and
cfg.TRAIN.BBOX_NORMALIZE_TARGETS):
# RPN can only use precomputed normalization because there are no
# fixed statistics to compute a priori
assert cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED
if cfg.TRAIN.BBOX_REG:
print 'Computing bounding-box regression targets...'
self.bbox_means, self.bbox_stds = \
rdl_roidb.add_bbox_regression_targets(roidb)
print 'done'
self.solver = caffe.SGDSolver(solver_prototxt)
if pretrained_model is not None:
print ('Loading pretrained model '
'weights from {:s}').format(pretrained_model)
self.solver.net.copy_from(pretrained_model)
self.solver_param = caffe_pb2.SolverParameter()
with open(solver_prototxt, 'rt') as f:
pb2.text_format.Merge(f.read(), self.solver_param)
self.solver.net.layers[0].set_roidb(roidb)
def snapshot(self):
"""Take a snapshot of the network after unnormalizing the learned
bounding-box regression weights. This enables easy use at test-time.
"""
net = self.solver.net
scale_bbox_params = (cfg.TRAIN.BBOX_REG and
cfg.TRAIN.BBOX_NORMALIZE_TARGETS and
net.params.has_key('bbox_pred'))
if scale_bbox_params:
# save original values
orig_0 = net.params['bbox_pred'][0].data.copy()
orig_1 = net.params['bbox_pred'][1].data.copy()
# scale and shift with bbox reg unnormalization; then save snapshot
net.params['bbox_pred'][0].data[...] = \
(net.params['bbox_pred'][0].data *
self.bbox_stds[:, np.newaxis])
net.params['bbox_pred'][1].data[...] = \
(net.params['bbox_pred'][1].data *
self.bbox_stds + self.bbox_means)
infix = ('_' + cfg.TRAIN.SNAPSHOT_INFIX
if cfg.TRAIN.SNAPSHOT_INFIX != '' else '')
filename = (self.solver_param.snapshot_prefix + infix +
'_iter_{:d}'.format(self.solver.iter) + '.caffemodel')
filename = os.path.join(self.output_dir, filename)
net.save(str(filename))
print 'Wrote snapshot to: {:s}'.format(filename)
if scale_bbox_params:
# restore net to original state
net.params['bbox_pred'][0].data[...] = orig_0
net.params['bbox_pred'][1].data[...] = orig_1
return filename
def train_model(self, max_iters):
"""Network training loop."""
last_snapshot_iter = -1
timer = Timer()
model_paths = []
while self.solver.iter < max_iters:
# Make one SGD update
timer.tic()
self.solver.step(1)
timer.toc()
if self.solver.iter % (10 * self.solver_param.display) == 0:
print 'speed: {:.3f}s / iter'.format(timer.average_time)
if self.solver.iter % cfg.TRAIN.SNAPSHOT_ITERS == 0:
last_snapshot_iter = self.solver.iter
model_paths.append(self.snapshot())
if last_snapshot_iter != self.solver.iter:
model_paths.append(self.snapshot())
return model_paths
def get_training_roidb(imdb):
"""Returns a roidb (Region of Interest database) for use in training."""
if cfg.TRAIN.USE_FLIPPED:
print 'Appending horizontally-flipped training examples...'
imdb.append_flipped_images()
print 'done'
print 'Preparing training data...'
rdl_roidb.prepare_roidb(imdb)
print 'done'
return imdb.roidb
def filter_roidb(roidb):
"""Remove roidb entries that have no usable RoIs."""
def is_valid(entry):
# Valid images have:
# (1) At least one foreground RoI OR
# (2) At least one background RoI
overlaps = entry['max_overlaps']
# find boxes with sufficient overlap
fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0]
# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) &
(overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]
# image is only valid if such boxes exist
valid = len(fg_inds) > 0 or len(bg_inds) > 0
return valid
num = len(roidb)
filtered_roidb = [entry for entry in roidb if is_valid(entry)]
num_after = len(filtered_roidb)
print 'Filtered {} roidb entries: {} -> {}'.format(num - num_after,
num, num_after)
return filtered_roidb
def train_net(solver_prototxt, roidb, output_dir,
pretrained_model=None, max_iters=40000):
"""Train a Fast R-CNN network."""
roidb = filter_roidb(roidb)
sw = SolverWrapper(solver_prototxt, roidb, output_dir,
pretrained_model=pretrained_model)
print 'Solving...'
model_paths = sw.train_model(max_iters)
print 'done solving'
return model_paths
| 6,076 | 36.282209 | 79 | py |
ADaPTION | ADaPTION-master/frcnn/lib/rpn/proposal_layer.py | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import caffe
import numpy as np
import yaml
from fast_rcnn.config import cfg
from generate_anchors import generate_anchors
from fast_rcnn.bbox_transform import bbox_transform_inv, clip_boxes
from fast_rcnn.nms_wrapper import nms
DEBUG = True
class ProposalLayer(caffe.Layer):
"""
Outputs object detection proposals by applying estimated bounding-box
transformations to a set of regular boxes (called "anchors").
"""
def setup(self, bottom, top):
# parse the layer parameter string, which must be valid YAML
layer_params = yaml.load(self.param_str)
# layer_params = 'feat_stride' 16 # yaml.load(self.param_str_)
self._feat_stride = layer_params['feat_stride']
anchor_scales = layer_params.get('scales', (8, 16, 32))
self._anchors = generate_anchors(scales=np.array(anchor_scales))
self._num_anchors = self._anchors.shape[0]
if DEBUG:
print 'feat_stride: {}'.format(self._feat_stride)
print 'anchors:'
print self._anchors
print 'Phase: {}'.format(self.phase)
# rois blob: holds R regions of interest, each is a 5-tuple
# (n, x1, y1, x2, y2) specifying an image batch index n and a
# rectangle (x1, y1, x2, y2)
top[0].reshape(1, 5)
# scores blob: holds scores for R regions of interest
if len(top) > 1:
top[1].reshape(1, 1, 1, 1)
def forward(self, bottom, top):
# Algorithm:
#
# for each (H, W) location i
# generate A anchor boxes centered on cell i
# apply predicted bbox deltas at cell i to each of the A anchors
# clip predicted boxes to image
# remove predicted boxes with either height or width < threshold
# sort all (proposal, score) pairs by score from highest to lowest
# take top pre_nms_topN proposals before NMS
# apply NMS with threshold 0.7 to remaining proposals
# take after_nms_topN proposals after NMS
# return the top proposals (-> RoIs top, scores top)
assert bottom[0].data.shape[0] == 1, \
'Only single item batches are supported'
# Not sure, when and where it was changed, but train and test phase is indicated
# by boolean varibale. To let RPN work, boolean has to converted into real string
if self.phase:
phase = 'TEST'
else:
phase = 'TRAIN'
cfg_key = phase # either 'TRAIN' or 'TEST'
pre_nms_topN = cfg[cfg_key].RPN_PRE_NMS_TOP_N
post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N
nms_thresh = cfg[cfg_key].RPN_NMS_THRESH
min_size = cfg[cfg_key].RPN_MIN_SIZE
# the first set of _num_anchors channels are bg probs
# the second set are the fg probs, which we want
scores = bottom[0].data[:, self._num_anchors:, :, :]
bbox_deltas = bottom[1].data
im_info = bottom[2].data[0, :]
if DEBUG:
print 'im_size: ({}, {})'.format(im_info[0], im_info[1])
print 'scale: {}'.format(im_info[2])
# 1. Generate proposals from bbox deltas and shifted anchors
height, width = scores.shape[-2:]
if DEBUG:
print 'score map size: {}'.format(scores.shape)
# Enumerate all shifts
shift_x = np.arange(0, width) * self._feat_stride
shift_y = np.arange(0, height) * self._feat_stride
shift_x, shift_y = np.meshgrid(shift_x, shift_y)
shifts = np.vstack((shift_x.ravel(), shift_y.ravel(),
shift_x.ravel(), shift_y.ravel())).transpose()
# Enumerate all shifted anchors:
#
# add A anchors (1, A, 4) to
# cell K shifts (K, 1, 4) to get
# shift anchors (K, A, 4)
# reshape to (K*A, 4) shifted anchors
A = self._num_anchors
K = shifts.shape[0]
anchors = self._anchors.reshape((1, A, 4)) + \
shifts.reshape((1, K, 4)).transpose((1, 0, 2))
anchors = anchors.reshape((K * A, 4))
# Transpose and reshape predicted bbox transformations to get them
# into the same order as the anchors:
#
# bbox deltas will be (1, 4 * A, H, W) format
# transpose to (1, H, W, 4 * A)
# reshape to (1 * H * W * A, 4) where rows are ordered by (h, w, a)
# in slowest to fastest order
bbox_deltas = bbox_deltas.transpose((0, 2, 3, 1)).reshape((-1, 4))
# Same story for the scores:
#
# scores are (1, A, H, W) format
# transpose to (1, H, W, A)
# reshape to (1 * H * W * A, 1) where rows are ordered by (h, w, a)
scores = scores.transpose((0, 2, 3, 1)).reshape((-1, 1))
# Convert anchors into proposals via bbox transformations
proposals = bbox_transform_inv(anchors, bbox_deltas)
# 2. clip predicted boxes to image
proposals = clip_boxes(proposals, im_info[:2])
# 3. remove predicted boxes with either height or width < threshold
# (NOTE: convert min_size to input image scale stored in im_info[2])
keep = _filter_boxes(proposals, min_size * im_info[2])
proposals = proposals[keep, :]
scores = scores[keep]
# 4. sort all (proposal, score) pairs by score from highest to lowest
# 5. take top pre_nms_topN (e.g. 6000)
order = scores.ravel().argsort()[::-1]
if pre_nms_topN > 0:
order = order[:pre_nms_topN]
proposals = proposals[order, :]
scores = scores[order]
# 6. apply nms (e.g. threshold = 0.7)
# 7. take after_nms_topN (e.g. 300)
# 8. return the top proposals (-> RoIs top)
keep = nms(np.hstack((proposals, scores)), nms_thresh)
if post_nms_topN > 0:
keep = keep[:post_nms_topN]
proposals = proposals[keep, :]
scores = scores[keep]
# Output rois blob
# Our RPN implementation only supports a single input image, so all
# batch inds are 0
batch_inds = np.zeros((proposals.shape[0], 1), dtype=np.float32)
blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False)))
top[0].reshape(*(blob.shape))
top[0].data[...] = blob
# [Optional] output scores blob
if len(top) > 1:
top[1].reshape(*(scores.shape))
top[1].data[...] = scores
def backward(self, top, propagate_down, bottom):
"""This layer does not propagate gradients."""
pass
def reshape(self, bottom, top):
"""Reshaping happens during the call to forward."""
pass
def _filter_boxes(boxes, min_size):
"""Remove all boxes with any side smaller than min_size."""
ws = boxes[:, 2] - boxes[:, 0] + 1
hs = boxes[:, 3] - boxes[:, 1] + 1
keep = np.where((ws >= min_size) & (hs >= min_size))[0]
return keep
| 7,171 | 37.352941 | 89 | py |
ADaPTION | ADaPTION-master/frcnn/lib/rpn/proposal_target_layer.py | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import caffe
import yaml
import numpy as np
import numpy.random as npr
from fast_rcnn.config import cfg
from fast_rcnn.bbox_transform import bbox_transform
from utils.cython_bbox import bbox_overlaps
DEBUG = True
class ProposalTargetLayer(caffe.Layer):
"""
Assign object detection proposals to ground-truth targets. Produces proposal
classification labels and bounding-box regression targets.
"""
def setup(self, bottom, top):
layer_params = yaml.load(self.param_str_)
self._num_classes = layer_params['num_classes']
# sampled rois (0, x1, y1, x2, y2)
top[0].reshape(1, 5)
# labels
top[1].reshape(1, 1)
# bbox_targets
top[2].reshape(1, self._num_classes * 4)
# bbox_inside_weights
top[3].reshape(1, self._num_classes * 4)
# bbox_outside_weights
top[4].reshape(1, self._num_classes * 4)
def forward(self, bottom, top):
# Proposal ROIs (0, x1, y1, x2, y2) coming from RPN
# (i.e., rpn.proposal_layer.ProposalLayer), or any other source
all_rois = bottom[0].data
# GT boxes (x1, y1, x2, y2, label)
# TODO(rbg): it's annoying that sometimes I have extra info before
# and other times after box coordinates -- normalize to one format
gt_boxes = bottom[1].data
# Include ground-truth boxes in the set of candidate rois
zeros = np.zeros((gt_boxes.shape[0], 1), dtype=gt_boxes.dtype)
all_rois = np.vstack(
(all_rois, np.hstack((zeros, gt_boxes[:, :-1])))
)
# Sanity check: single batch only
assert np.all(all_rois[:, 0] == 0), \
'Only single item batches are supported'
num_images = 1
rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images
fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
# Sample rois with classification labels and bounding box regression
# targets
labels, rois, bbox_targets, bbox_inside_weights = _sample_rois(
all_rois, gt_boxes, fg_rois_per_image,
rois_per_image, self._num_classes)
if DEBUG:
print 'num fg: {}'.format((labels > 0).sum())
print 'num bg: {}'.format((labels == 0).sum())
self._count += 1
self._fg_num += (labels > 0).sum()
self._bg_num += (labels == 0).sum()
print 'num fg avg: {}'.format(self._fg_num / self._count)
print 'num bg avg: {}'.format(self._bg_num / self._count)
print 'ratio: {:.3f}'.format(float(self._fg_num) / float(self._bg_num))
# sampled rois
top[0].reshape(*rois.shape)
top[0].data[...] = rois
# classification labels
top[1].reshape(*labels.shape)
top[1].data[...] = labels
# bbox_targets
top[2].reshape(*bbox_targets.shape)
top[2].data[...] = bbox_targets
# bbox_inside_weights
top[3].reshape(*bbox_inside_weights.shape)
top[3].data[...] = bbox_inside_weights
# bbox_outside_weights
top[4].reshape(*bbox_inside_weights.shape)
top[4].data[...] = np.array(bbox_inside_weights > 0).astype(np.float32)
def backward(self, top, propagate_down, bottom):
"""This layer does not propagate gradients."""
pass
def reshape(self, bottom, top):
"""Reshaping happens during the call to forward."""
pass
def _get_bbox_regression_labels(bbox_target_data, num_classes):
"""Bounding-box regression targets (bbox_target_data) are stored in a
compact form N x (class, tx, ty, tw, th)
This function expands those targets into the 4-of-4*K representation used
by the network (i.e. only one class has non-zero targets).
Returns:
bbox_target (ndarray): N x 4K blob of regression targets
bbox_inside_weights (ndarray): N x 4K blob of loss weights
"""
clss = bbox_target_data[:, 0]
bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)
bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)
inds = np.where(clss > 0)[0]
for ind in inds:
cls = clss[ind]
start = 4 * cls
end = start + 4
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
return bbox_targets, bbox_inside_weights
def _compute_targets(ex_rois, gt_rois, labels):
"""Compute bounding-box regression targets for an image."""
assert ex_rois.shape[0] == gt_rois.shape[0]
assert ex_rois.shape[1] == 4
assert gt_rois.shape[1] == 4
targets = bbox_transform(ex_rois, gt_rois)
if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED:
# Optionally normalize targets by a precomputed mean and stdev
targets = ((targets - np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS))
/ np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS))
return np.hstack(
(labels[:, np.newaxis], targets)).astype(np.float32, copy=False)
def _sample_rois(all_rois, gt_boxes, fg_rois_per_image, rois_per_image, num_classes):
"""Generate a random sample of RoIs comprising foreground and background
examples.
"""
# overlaps: (rois x gt_boxes)
overlaps = bbox_overlaps(
np.ascontiguousarray(all_rois[:, 1:5], dtype=np.float),
np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float))
gt_assignment = overlaps.argmax(axis=1)
max_overlaps = overlaps.max(axis=1)
labels = gt_boxes[gt_assignment, 4]
# Select foreground RoIs as those with >= FG_THRESH overlap
fg_inds = np.where(max_overlaps >= cfg.TRAIN.FG_THRESH)[0]
# Guard against the case when an image has fewer than fg_rois_per_image
# foreground RoIs
fg_rois_per_this_image = min(fg_rois_per_image, fg_inds.size)
# Sample foreground regions without replacement
if fg_inds.size > 0:
fg_inds = npr.choice(fg_inds, size=fg_rois_per_this_image, replace=False)
# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = np.where((max_overlaps < cfg.TRAIN.BG_THRESH_HI) &
(max_overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]
# Compute number of background RoIs to take from this image (guarding
# against there being fewer than desired)
bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image
bg_rois_per_this_image = min(bg_rois_per_this_image, bg_inds.size)
# Sample background regions without replacement
if bg_inds.size > 0:
bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False)
# The indices that we're selecting (both fg and bg)
keep_inds = np.append(fg_inds, bg_inds)
# Select sampled values from various arrays:
labels = labels[keep_inds]
# Clamp labels for the background RoIs to 0
labels[fg_rois_per_this_image:] = 0
rois = all_rois[keep_inds]
bbox_target_data = _compute_targets(
rois[:, 1:5], gt_boxes[gt_assignment[keep_inds], :4], labels)
bbox_targets, bbox_inside_weights = \
_get_bbox_regression_labels(bbox_target_data, num_classes)
return labels, rois, bbox_targets, bbox_inside_weights
| 7,494 | 37.634021 | 85 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.