Skip to content

Commit

Permalink
linting code
Browse files Browse the repository at this point in the history
  • Loading branch information
KaiyangZhou committed May 5, 2020
1 parent 2a9f44a commit 5ce4318
Show file tree
Hide file tree
Showing 33 changed files with 97 additions and 65 deletions.
18 changes: 16 additions & 2 deletions .flake8
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
[flake8]
ignore = E261, E501, W293
ignore =
# At least two spaces before inline comment
E261,
# Line lengths are recommended to be no greater than 79 characters
E501,
# Missing whitespace around arithmetic operator
E226,
# Blank line contains whitespace
W293,
# Do not use bare 'except'
E722,
# Line break after binary operator
W504,
# isort found an import in the wrong position
I001
max-line-length = 79
exclude = __init__.py, build
exclude = __init__.py, build, torchreid/metrics/rank_cylib/
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
# You can specify multiple suffix as a list of string:
#
source_suffix = ['.rst', '.md']
#source_suffix = '.rst'
# source_suffix = '.rst'
source_parsers = {'.md': 'recommonmark.parser.CommonMarkParser'}

# The master toctree document.
Expand Down
10 changes: 9 additions & 1 deletion linter.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
echo "Running isort"
isort -y -sp .
echo "Done"

yapf -i -r -vv . -e build
echo "Running yapf"
yapf -i -r -vv -e build .
echo "Done"

echo "Running flake8"
flake8 .
echo "Done"
3 changes: 0 additions & 3 deletions projects/DML/dml.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
from __future__ import division, print_function, absolute_import
import time
import datetime
import torch
from torch.nn import functional as F

from torchreid import metrics
from torchreid.utils import open_all_layers, open_specified_layers
from torchreid.engine import Engine
from torchreid.losses import TripletLoss, CrossEntropyLoss
Expand Down
5 changes: 2 additions & 3 deletions projects/DML/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import sys
import copy
import time
Expand All @@ -15,8 +14,8 @@

from dml import ImageDMLEngine
from default_config import (
imagedata_kwargs, optimizer_kwargs, videodata_kwargs, engine_run_kwargs,
get_default_config, lr_scheduler_kwargs
imagedata_kwargs, optimizer_kwargs, engine_run_kwargs, get_default_config,
lr_scheduler_kwargs
)


Expand Down
18 changes: 18 additions & 0 deletions projects/OSNet_AIN/osnet_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,24 @@
##########
# Basic layers
##########
class IBN(nn.Module):
"""Instance + Batch Normalization."""

def __init__(self, num_channels):
super(IBN, self).__init__()
half1 = int(num_channels / 2)
self.half = half1
half2 = num_channels - half1
self.IN = nn.InstanceNorm2d(half1, affine=NORM_AFFINE)
self.BN = nn.BatchNorm2d(half2, affine=NORM_AFFINE)

def forward(self, x):
split = torch.split(x, self.half, 1)
out1 = self.IN(split[0].contiguous())
out2 = self.BN(split[1].contiguous())
return torch.cat((out1, out2), 1)


class ConvLayer(nn.Module):
"""Convolution layer (conv + bn + relu)."""

Expand Down
7 changes: 1 addition & 6 deletions projects/OSNet_AIN/softmax_nas.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
from __future__ import division, print_function, absolute_import
import time
import datetime

from torchreid import metrics
from torchreid.utils import (
AverageMeter, open_all_layers, open_specified_layers
)
from torchreid.engine import Engine
from torchreid.losses import CrossEntropyLoss

Expand Down Expand Up @@ -58,7 +53,7 @@ def forward_backward(self, data):
lmda = self.init_lmda
else:
lmda = self.init_lmda * self.lmda_decay_rate**(
epoch // self.lmda_decay_step
self.epoch // self.lmda_decay_step
)
if lmda < self.min_lmda:
lmda = self.min_lmda
Expand Down
1 change: 0 additions & 1 deletion scripts/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import sys
import time
import os.path as osp
Expand Down
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ def get_requirements(filename='requirements.txt'):
setup(
name='torchreid',
version=find_version(),
description=
'A library for deep learning person re-identification in PyTorch',
description='A library for deep learning person re-ID in PyTorch',
author='Kaiyang Zhou',
license='MIT',
long_description=readme(),
Expand Down
2 changes: 1 addition & 1 deletion torchreid/data/datamanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def num_train_cams(self):
"""Returns the number of training cameras."""
return self._num_train_cams

def return_query_and_gallery_by_name(self, name):
def fetch_qg(self, name):
"""Returns query and gallery of a test dataset, each containing
tuples of (img_path(s), pid, camid).
Expand Down
6 changes: 3 additions & 3 deletions torchreid/data/datasets/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,9 @@ def __repr__(self):
' gallery | {:5d} | {:7d} | {:9d}\n' \
' ----------------------------------------\n' \
' items: images/tracklets for image/video dataset\n'.format(
num_train_pids, len(self.train), num_train_cams,
num_query_pids, len(self.query), num_query_cams,
num_gallery_pids, len(self.gallery), num_gallery_cams
num_train_pids, len(self.train), num_train_cams,
num_query_pids, len(self.query), num_query_cams,
num_gallery_pids, len(self.gallery), num_gallery_cams
)

return msg
Expand Down
6 changes: 2 additions & 4 deletions torchreid/data/datasets/image/cuhk03.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,8 @@ def _extract_img(image_type):
img_paths = _process_images(
camp[pid, :], campid, pid, imgs_dir
)
assert len(img_paths
) > 0, 'campid{}-pid{} has no images'.format(
campid, pid
)
assert len(img_paths) > 0, \
'campid{}-pid{} has no images'.format(campid, pid)
meta_data.append((campid + 1, pid + 1, img_paths))
print(
'- done camera pair {} with {} identities'.format(
Expand Down
3 changes: 2 additions & 1 deletion torchreid/data/datasets/image/dukemtmcreid.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ def process_dir(self, dir_path, relabel=False):
pid, camid = map(int, pattern.search(img_path).groups())
assert 1 <= camid <= 8
camid -= 1 # index starts from 0
if relabel: pid = pid2label[pid]
if relabel:
pid = pid2label[pid]
data.append((img_path, pid, camid))

return data
2 changes: 1 addition & 1 deletion torchreid/data/datasets/image/ilids.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class iLIDS(ImageDataset):
Dataset statistics:
- identities: 119.
- images: 476.
- images: 476.
- cameras: 8 (not explicitly provided).
"""
dataset_dir = 'ilids'
Expand Down
2 changes: 1 addition & 1 deletion torchreid/data/datasets/image/msmt17.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from ..dataset import ImageDataset

##### Log #####
# Log
# 22.01.2019
# - add v2
# - v1 and v2 differ in dir names
Expand Down
6 changes: 2 additions & 4 deletions torchreid/data/datasets/image/viper.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,8 @@ def prepare_split(self):
np.random.shuffle(order)
train_idxs = order[:num_train_pids]
test_idxs = order[num_train_pids:]
assert not bool(
set(train_idxs)
& set(test_idxs)
), 'Error: train and test overlap'
assert not bool(set(train_idxs) & set(test_idxs)), \
'Error: train and test overlap'

train = []
for pid, idx in enumerate(train_idxs):
Expand Down
3 changes: 2 additions & 1 deletion torchreid/data/datasets/video/mars.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ def process_data(
if pid == -1:
continue # junk images are just ignored
assert 1 <= camid <= 6
if relabel: pid = pid2label[pid]
if relabel:
pid = pid2label[pid]
camid -= 1 # index starts from 0
img_names = names[start_index - 1:end_index]

Expand Down
13 changes: 10 additions & 3 deletions torchreid/data/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
from collections import deque
import torch
from PIL import Image
from torchvision.transforms import *
from torchvision.transforms import (
Resize, Compose, ToTensor, Normalize, ColorJitter, RandomHorizontalFlip
)


class Random2DTranslation(object):
Expand Down Expand Up @@ -279,8 +281,13 @@ def build_transforms(
transform_tr += [RandomHorizontalFlip()]

if 'random_crop' in transforms:
print('+ random crop (enlarge to {}x{} and ' \
'crop {}x{})'.format(int(round(height*1.125)), int(round(width*1.125)), height, width))
print(
'+ random crop (enlarge to {}x{} and '
'crop {}x{})'.format(
int(round(height * 1.125)), int(round(width * 1.125)), height,
width
)
)
transform_tr += [Random2DTranslation(height, width)]

if 'random_patch' in transforms:
Expand Down
3 changes: 1 addition & 2 deletions torchreid/engine/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,8 +428,7 @@ def _feature_extraction(data_loader):
if visrank:
visualize_ranked_results(
distmat,
self.datamanager.
return_query_and_gallery_by_name(dataset_name),
self.datamanager.fetch_qg(dataset_name),
self.datamanager.data_type,
width=self.datamanager.width,
height=self.datamanager.height,
Expand Down
2 changes: 0 additions & 2 deletions torchreid/engine/image/softmax.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from __future__ import division, print_function, absolute_import
import time
import datetime

from torchreid import metrics
from torchreid.losses import CrossEntropyLoss
Expand Down
2 changes: 0 additions & 2 deletions torchreid/engine/image/triplet.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from __future__ import division, print_function, absolute_import
import time
import datetime

from torchreid import metrics
from torchreid.losses import TripletLoss, CrossEntropyLoss
Expand Down
4 changes: 2 additions & 2 deletions torchreid/engine/video/triplet.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ class VideoTripletEngine(ImageTripletEngine, VideoSoftmaxEngine):
Default is "avg" (average). Choices are ["avg", "max"].
Examples::
import torch
import torchreid
# Each batch contains batch_size*seq_len images
# Each identity is sampled with num_instances tracklets
# Each identity is sampled with num_instances tracklets
datamanager = torchreid.data.VideoDataManager(
root='path/to/reid-data',
sources='mars',
Expand Down
5 changes: 3 additions & 2 deletions torchreid/metrics/distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ def euclidean_squared_distance(input1, input2):
torch.Tensor: distance matrix.
"""
m, n = input1.size(0), input2.size(0)
distmat = torch.pow(input1, 2).sum(dim=1, keepdim=True).expand(m, n) + \
torch.pow(input2, 2).sum(dim=1, keepdim=True).expand(n, m).t()
mat1 = torch.pow(input1, 2).sum(dim=1, keepdim=True).expand(m, n)
mat2 = torch.pow(input2, 2).sum(dim=1, keepdim=True).expand(n, m).t()
distmat = mat1 + mat2
distmat.addmm_(1, -2, input1, input2.t())
return distmat

Expand Down
3 changes: 2 additions & 1 deletion torchreid/models/hacnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,8 @@ def transform_theta(self, theta_i, region_idx):
theta = torch.zeros(theta_i.size(0), 2, 3)
theta[:, :, :2] = scale_factors
theta[:, :, -1] = theta_i
if self.use_gpu: theta = theta.cuda()
if self.use_gpu:
theta = theta.cuda()
return theta

def forward(self, x):
Expand Down
6 changes: 3 additions & 3 deletions torchreid/models/inceptionresnetv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,9 @@ def forward(self, x):
return out


##################### Model Definition #########################


# ----------------
# Model Definition
# ----------------
class InceptionResNetV2(nn.Module):
"""Inception-ResNet-V2.
Expand Down
2 changes: 1 addition & 1 deletion torchreid/models/mlfn.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def init_pretrained_weights(model, model_url):
def mlfn(num_classes, loss='softmax', pretrained=True, **kwargs):
model = MLFN(num_classes, loss, **kwargs)
if pretrained:
#init_pretrained_weights(model, model_urls['imagenet'])
# init_pretrained_weights(model, model_urls['imagenet'])
import warnings
warnings.warn(
'The imagenet pretrained weights need to be manually downloaded from {}'
Expand Down
4 changes: 2 additions & 2 deletions torchreid/models/mobilenetv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def mobilenetv2_x1_0(num_classes, loss, pretrained=True, **kwargs):
**kwargs
)
if pretrained:
#init_pretrained_weights(model, model_urls['mobilenetv2_x1_0'])
# init_pretrained_weights(model, model_urls['mobilenetv2_x1_0'])
import warnings
warnings.warn(
'The imagenet pretrained weights need to be manually downloaded from {}'
Expand All @@ -265,7 +265,7 @@ def mobilenetv2_x1_4(num_classes, loss, pretrained=True, **kwargs):
**kwargs
)
if pretrained:
#init_pretrained_weights(model, model_urls['mobilenetv2_x1_4'])
# init_pretrained_weights(model, model_urls['mobilenetv2_x1_4'])
import warnings
warnings.warn(
'The imagenet pretrained weights need to be manually downloaded from {}'
Expand Down
2 changes: 1 addition & 1 deletion torchreid/models/nasnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
pretrained_settings = {
'nasnetamobile': {
'imagenet': {
#'url': 'https://github.com/veronikayurchuk/pretrained-models.pytorch/releases/download/v1.0/nasnetmobile-7e03cead.pth.tar',
# 'url': 'https://github.com/veronikayurchuk/pretrained-models.pytorch/releases/download/v1.0/nasnetmobile-7e03cead.pth.tar',
'url':
'http://data.lip6.fr/cadene/pretrainedmodels/nasnetamobile-7e03cead.pth',
'input_space': 'RGB',
Expand Down
8 changes: 5 additions & 3 deletions torchreid/models/shufflenet.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ def __init__(
assert stride in [1, 2], 'Warning: stride must be either 1 or 2'
self.stride = stride
mid_channels = out_channels // 4
if stride == 2: out_channels -= in_channels
if stride == 2:
out_channels -= in_channels
# group conv is not applied to first conv1x1 at stage 2
num_groups_conv1x1 = num_groups if group_conv1x1 else 1
self.conv1 = nn.Conv2d(
Expand All @@ -71,7 +72,8 @@ def __init__(
mid_channels, out_channels, 1, groups=num_groups, bias=False
)
self.bn3 = nn.BatchNorm2d(out_channels)
if stride == 2: self.shortcut = nn.AvgPool2d(3, stride=2, padding=1)
if stride == 2:
self.shortcut = nn.AvgPool2d(3, stride=2, padding=1)

def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
Expand Down Expand Up @@ -187,7 +189,7 @@ def init_pretrained_weights(model, model_url):
def shufflenet(num_classes, loss='softmax', pretrained=True, **kwargs):
model = ShuffleNet(num_classes, loss, **kwargs)
if pretrained:
#init_pretrained_weights(model, model_urls['imagenet'])
# init_pretrained_weights(model, model_urls['imagenet'])
import warnings
warnings.warn(
'The imagenet pretrained weights need to be manually downloaded from {}'
Expand Down
1 change: 0 additions & 1 deletion torchreid/models/squeezenet.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from torch.utils import model_zoo as model_zoo

__all__ = ['squeezenet1_0', 'squeezenet1_1', 'squeezenet1_0_fc512']

Expand Down
Loading

0 comments on commit 5ce4318

Please sign in to comment.