Skip to content

Commit

Permalink
Integrate offset into grid (#7262)
Browse files Browse the repository at this point in the history
Eliminate 1 op during training and inference.
  • Loading branch information
glenn-jocher committed Apr 3, 2022
1 parent 8bc839e commit ea72b84
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions models/yolo.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ def forward(self, x):

y = x[i].sigmoid()
if self.inplace:
y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i] # xy
y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
xy = (xy * 2 + (self.grid[i] - 0.5)) * self.stride[i] # xy
xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
y = torch.cat((xy, wh, conf), 4)
z.append(y.view(bs, -1, self.no))
Expand All @@ -82,7 +82,7 @@ def _make_grid(self, nx=20, ny=20, i=0):
yv, xv = torch.meshgrid(torch.arange(ny, device=d), torch.arange(nx, device=d), indexing='ij')
else:
yv, xv = torch.meshgrid(torch.arange(ny, device=d), torch.arange(nx, device=d))
grid = torch.stack((xv, yv), 2).expand(shape).float()
grid = torch.stack((xv, yv), 2).expand(shape).float() - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape).float()
return grid, anchor_grid

Expand Down

0 comments on commit ea72b84

Please sign in to comment.