Skip to content

Commit ebf54d5

Browse files
rentainhentianhe ren
and
ntianhe ren
authored
Refine format and linter check (IDEA-Research#41)
* refine format * refine linter and flake8 * refine linter check to skip submodule Co-authored-by: ntianhe ren <[email protected]>
1 parent 9c2f6a1 commit ebf54d5

File tree

15 files changed

+150
-136
lines changed

15 files changed

+150
-136
lines changed

.flake8

+4-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ ignore = W503, E203, E221, C901, C408, E741, C407, B017
66
max-line-length = 100
77
max-complexity = 18
88
select = B,C,E,F,W,T4,B9
9-
exclude = build
9+
exclude = build, detectron2
1010
per-file-ignores =
1111
**/__init__.py:F401,F403,E402
1212
**/configs/**.py:F401,E402
@@ -15,4 +15,6 @@ per-file-ignores =
1515
tests/config/**.py:F401,E402
1616
tests/**.py: E402
1717
tools/**.py: E402
18-
projects/**/configs/**.py:F401
18+
projects/**/configs/**.py:F401
19+
detectron2/**.py: F401,F403,E402,F811,W391
20+
detectron2/projects/**.py: F401,F403,E402,F811,W391

configs/common/coco_schedule.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,12 @@ def default_coco_scheduler(epochs=50, decay_epochs=40, warmup_epochs=0):
4444
commonly referred to in papers, where every 1x has the total length of 1440k
4545
training images (~12 COCO epochs). LR is decayed twice at the end of training
4646
following the strategy defined in "Rethinking ImageNet Pretraining", Sec 4.
47-
47+
4848
Args:
4949
epochs (int): total training epochs.
5050
decay_epochs (int): lr decay steps.
5151
warmup_epochs (int): warmup epochs.
52-
52+
5353
Returns:
5454
DictConfig: configs that define the multiplier for LR during training
5555
"""
@@ -79,4 +79,4 @@ def default_coco_scheduler(epochs=50, decay_epochs=40, warmup_epochs=0):
7979

8080
# default scheduler for detr
8181
lr_multiplier_50ep = default_coco_scheduler(50, 40, 0)
82-
lr_multiplier_12ep = default_coco_scheduler(12, 11, 0)
82+
lr_multiplier_12ep = default_coco_scheduler(12, 11, 0)

configs/common/train.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
params=dict(
1616
max_norm=0.1,
1717
norm_type=2,
18-
)
18+
),
1919
), # options for Gradient Clipping
2020
fast_dev_run=dict(enabled=False), # options for Fast Checking
2121
checkpointer=dict(period=5000, max_to_keep=100), # options for PeriodicCheckpointer

detrex/modeling/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,5 @@
2424
make_stage,
2525
BottleneckBlock,
2626
BasicBlock,
27-
TimmBackbone
28-
)
27+
TimmBackbone,
28+
)

detrex/modeling/backbone/resnet.py

+27-30
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,7 @@ def __init__(
208208
# Add it as an option when we need to use this code to train a backbone.
209209

210210
def forward(self, x):
211-
"""Forward function of `BottleneckBlock`.
212-
"""
211+
"""Forward function of `BottleneckBlock`."""
213212
out = self.conv1(x)
214213
out = F.relu_(out)
215214

@@ -230,8 +229,8 @@ def forward(self, x):
230229

231230
class DeformBottleneckBlock(CNNBlockBase):
232231
"""
233-
Similar to :class:`BottleneckBlock`, but with
234-
paper `Deformable Convolutional Networks
232+
Similar to :class:`BottleneckBlock`, but with
233+
paper `Deformable Convolutional Networks
235234
<https://arxiv.org/pdf/1703.06211.pdf>`_ in the 3x3 convolution.
236235
"""
237236

@@ -320,8 +319,7 @@ def __init__(
320319
nn.init.constant_(self.conv2_offset.bias, 0)
321320

322321
def forward(self, x):
323-
"""Forward function of `DeformBottleneckBlock`.
324-
"""
322+
"""Forward function of `DeformBottleneckBlock`."""
325323
out = self.conv1(x)
326324
out = F.relu_(out)
327325

@@ -373,8 +371,7 @@ def __init__(self, in_channels=3, out_channels=64, norm="BN"):
373371
weight_init.c2_msra_fill(self.conv1)
374372

375373
def forward(self, x):
376-
"""Forward function of `BasicStem`.
377-
"""
374+
"""Forward function of `BasicStem`."""
378375
x = self.conv1(x)
379376
x = F.relu_(x)
380377
x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)
@@ -383,7 +380,7 @@ def forward(self, x):
383380

384381
class ResNet(Backbone):
385382
"""
386-
Implement paper `Deep Residual Learning for Image Recognition
383+
Implement paper `Deep Residual Learning for Image Recognition
387384
<https://arxiv.org/pdf/1512.03385.pdf>`_.
388385
389386
Args:
@@ -458,7 +455,7 @@ def forward(self, x):
458455
"""
459456
Args:
460457
x: Tensor of shape (N,C,H,W). H, W must be a multiple of ``self.size_divisibility``.
461-
458+
462459
Returns:
463460
dict[str->Tensor]: names and the corresponding features
464461
"""
@@ -492,14 +489,14 @@ def freeze(self, freeze_at=0):
492489
Freeze the first several stages of the ResNet. Commonly used in
493490
fine-tuning.
494491
Layers that produce the same feature map spatial size are defined as one
495-
"stage" by paper `Feature Pyramid Networks for Object Detection
492+
"stage" by paper `Feature Pyramid Networks for Object Detection
496493
<https://arxiv.org/pdf/1612.03144.pdf>`_.
497-
494+
498495
Args:
499496
freeze_at (int): number of stages to freeze.
500497
`1` means freezing the stem. `2` means freezing the stem and
501498
one residual stage, etc.
502-
499+
503500
Returns:
504501
nn.Module: this ResNet itself
505502
"""
@@ -515,10 +512,10 @@ def freeze(self, freeze_at=0):
515512
def make_stage(block_class, num_blocks, *, in_channels, out_channels, **kwargs):
516513
"""
517514
Create a list of blocks of the same type that forms one ResNet stage.
518-
515+
519516
Args:
520-
block_class (type): a subclass of ``detectron2.layers.CNNBlockBase`` that's
521-
used to create all blocks in this stage. A module of this type
517+
block_class (type): a subclass of ``detectron2.layers.CNNBlockBase`` that's
518+
used to create all blocks in this stage. A module of this type
522519
must not change spatial resolution of inputs unless its stride != 1.
523520
num_blocks (int): number of blocks in this stage
524521
in_channels (int): input channels of the entire stage.
@@ -528,10 +525,10 @@ def make_stage(block_class, num_blocks, *, in_channels, out_channels, **kwargs):
528525
argument is a list of values to be passed to each block in the
529526
stage. Otherwise, the same argument is passed to every block
530527
in the stage.
531-
528+
532529
Returns:
533530
list[detectron2.layers.CNNBlockBase]: a list of block module.
534-
531+
535532
Examples:
536533
::
537534
stage = ResNet.make_stage(
@@ -540,10 +537,10 @@ def make_stage(block_class, num_blocks, *, in_channels, out_channels, **kwargs):
540537
stride_per_block=[2, 1, 1],
541538
dilations_per_block=[1, 1, 2]
542539
)
543-
540+
544541
Usually, layers that produce the same feature map spatial size are defined as one
545542
"stage" (in paper `Feature Pyramid Networks for Object Detection
546-
<https://arxiv.org/pdf/1612.03144.pdf>`_).
543+
<https://arxiv.org/pdf/1612.03144.pdf>`_).
547544
Under such definition, ``stride_per_block[1:]`` should all be 1.
548545
"""
549546
blocks = []
@@ -573,7 +570,7 @@ def make_default_stages(depth, block_class=None, **kwargs):
573570
Created list of ResNet stages from pre-defined depth (one of 18, 34, 50, 101, 152).
574571
If it doesn't create the ResNet variant you need, please use :meth:`make_stage`
575572
instead for fine-grained customization.
576-
573+
577574
Args:
578575
depth (int): depth of ResNet
579576
block_class (type): the CNN block class. Has to accept
@@ -583,7 +580,7 @@ def make_default_stages(depth, block_class=None, **kwargs):
583580
kwargs:
584581
other arguments to pass to `make_stage`. Should not contain
585582
stride and channels, as they are predefined for each depth.
586-
583+
587584
Returns:
588585
list[list[detectron2.layers.CNNBlockBase]]: modules in all stages; see arguments of
589586
:class:`ResNet`.
@@ -640,11 +637,11 @@ def make_stage(
640637
deform_num_groups: int = 1,
641638
):
642639
"""
643-
Modified from `detectron2.modeling.backbone.build_resnet_backbone
640+
Modified from `detectron2.modeling.backbone.build_resnet_backbone
644641
<https://github.com/facebookresearch/detectron2/blob/717ab9f0aeca216a2f800e43d705766251ba3a55/detectron2/modeling/backbone/resnet.py#L614>`_
645642
646643
Create a list of blocks of the same type that forms one ResNet stage.
647-
644+
648645
Args:
649646
depth (int): The depth of ResNet. Default: 50.
650647
norm (str or callable): Normalization for all conv layers.
@@ -656,10 +653,10 @@ def make_stage(
656653
Default: 64.
657654
in_channels (int): Output feature channels of the `Stem` Block. Needs
658655
to be set to 64 for R18 and R34. Default: 64.
659-
out_channels (int): Output width of res2. Scaling this parameters
656+
out_channels (int): Output width of res2. Scaling this parameters
660657
will scale the width of all 1x1 convs in ResNet. Default: 256.
661-
stride_in_1x1 (bool): Place the stride 2 conv on the 1x1 filter.
662-
Use True only for the original MSRA ResNet;
658+
stride_in_1x1 (bool): Place the stride 2 conv on the 1x1 filter.
659+
Use True only for the original MSRA ResNet;
663660
use False for C2 and Torch models. Default: False.
664661
res5_dilation (int): Apply dilation in stage "res5". Default: 1.
665662
deform_on_per_stage (List[bool]): Apply Deformable Convolution in stages.
@@ -669,10 +666,10 @@ def make_stage(
669666
(DeformableV2, https://arxiv.org/abs/1811.11168); Use False for DeformableV1.
670667
Default: False.
671668
deform_num_groups (int): Number of groups in deformable conv. Default: 1.
672-
669+
673670
Returns:
674671
list[detectron2.layers.CNNBlockBase]: a list of block module.
675-
672+
676673
Examples:
677674
::
678675
from detrex.modeling.backbone import make_stage, ResNet, BasicStem
@@ -737,4 +734,4 @@ def make_stage(
737734
bottleneck_channels *= 2
738735
stages.append(blocks)
739736

740-
return stages
737+
return stages

dev/linter.sh

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ fi
2020
set -v
2121

2222
echo "Running autoflake ..."
23-
autoflake --remove-unused-variables --in-place --recursive .
23+
autoflake --remove-unused-variables --in-place --recursive . --exclude=detectron2
2424

2525
echo "Running isort ..."
2626
isort -y -sp . --atomic
2727

2828
echo "Running black ..."
29-
black -l 100 .
29+
black -l 100 . --exclude=detectron2
3030

3131
echo "Running flake8 ..."
3232
if [ -x "$(command -v flake8)" ]; then

projects/dab_detr/configs/dab_detr_r101_50ep.py

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
lr_multiplier,
66
model,
77
)
8+
89
# modify training config
910
train.init_checkpoint = "path/to/R-101.pkl"
1011
train.output_dir = "./output/dab_detr_r101_50ep"

projects/dab_detr/configs/models/dab_detr_r50_dc5.py

-1
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,3 @@
1515
out_features=["res2", "res3", "res4", "res5"],
1616
freeze_at=1,
1717
)
18-

projects/dab_detr/modeling/dab_detr.py

-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,6 @@ def __init__(
7777
if self.iter_update:
7878
self.transformer.decoder.bbox_embed = self.bbox_embed
7979

80-
8180
# normalizer for input raw images
8281
self.device = device
8382
pixel_mean = torch.Tensor(pixel_mean).to(self.device).view(3, 1, 1)

projects/dn_detr/configs/models/dn_detr_r50.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@
3434
freeze_at=1,
3535
),
3636
position_embedding=L(PositionEmbeddingSine)(
37-
num_pos_feats=128,
38-
temperature=20,
37+
num_pos_feats=128,
38+
temperature=20,
3939
normalize=True,
4040
),
41-
in_features = ["res5"], # use last level feature as DAB-DETR
41+
in_features=["res5"], # use last level feature as DAB-DETR
4242
transformer=L(DNDetrTransformer)(
4343
encoder=L(DNDetrTransformerEncoder)(
4444
transformer_layers=L(BaseTransformerLayer)(

projects/dn_detr/modeling/dn_criterion.py

+36-23
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,14 @@
1616
import torch
1717

1818
from detrex.modeling import SetCriterion
19-
from detrex.utils import (
20-
get_world_size,
21-
is_dist_avail_and_initialized,
22-
)
19+
from detrex.utils import get_world_size, is_dist_avail_and_initialized
20+
2321

2422
class DNCriterion(SetCriterion):
25-
"""This class computes the loss for DN-DETR.
26-
"""
23+
"""This class computes the loss for DN-DETR."""
24+
2725
def forward(self, outputs, targets, dn_metas=None):
28-
losses=super(DNCriterion, self).forward(outputs, targets)
26+
losses = super(DNCriterion, self).forward(outputs, targets)
2927

3028
num_boxes = sum(len(t["labels"]) for t in targets)
3129
num_boxes = torch.as_tensor(
@@ -50,15 +48,20 @@ def calculate_dn_loss(self, dn_metas, targets, aux_num, num_boxes):
5048
"""
5149
losses = {}
5250
if dn_metas and "output_known_lbs_bboxes" in dn_metas:
53-
output_known_lbs_bboxes,dn_num,single_padding= dn_metas['output_known_lbs_bboxes'], \
54-
dn_metas['dn_num'], dn_metas['single_padding']
51+
output_known_lbs_bboxes, dn_num, single_padding = (
52+
dn_metas["output_known_lbs_bboxes"],
53+
dn_metas["dn_num"],
54+
dn_metas["single_padding"],
55+
)
5556
dn_idx = []
5657
for i in range(len(targets)):
57-
if len(targets[i]['labels']) > 0:
58-
t = torch.arange(0, len(targets[i]['labels'])).long().cuda()
58+
if len(targets[i]["labels"]) > 0:
59+
t = torch.arange(0, len(targets[i]["labels"])).long().cuda()
5960
t = t.unsqueeze(0).repeat(dn_num, 1)
6061
tgt_idx = t.flatten()
61-
output_idx = (torch.tensor(range(dn_num)) * single_padding).long().cuda().unsqueeze(1) + t
62+
output_idx = (
63+
torch.tensor(range(dn_num)) * single_padding
64+
).long().cuda().unsqueeze(1) + t
6265
output_idx = output_idx.flatten()
6366
else:
6467
output_idx = tgt_idx = torch.tensor([]).long().cuda()
@@ -67,12 +70,15 @@ def calculate_dn_loss(self, dn_metas, targets, aux_num, num_boxes):
6770
l_dict = {}
6871
for loss in self.losses:
6972
kwargs = {}
70-
if 'labels' in loss:
71-
kwargs = {'log': False}
72-
l_dict.update(self.get_loss(loss, output_known_lbs_bboxes, targets, dn_idx, num_boxes * dn_num,
73-
**kwargs))
73+
if "labels" in loss:
74+
kwargs = {"log": False}
75+
l_dict.update(
76+
self.get_loss(
77+
loss, output_known_lbs_bboxes, targets, dn_idx, num_boxes * dn_num, **kwargs
78+
)
79+
)
7480

75-
l_dict = {k + f'_dn': v for k, v in l_dict.items()}
81+
l_dict = {k + f"_dn": v for k, v in l_dict.items()}
7682
losses.update(l_dict)
7783
else:
7884
losses["loss_bbox_dn"] = torch.as_tensor(0.0).to("cuda")
@@ -83,13 +89,21 @@ def calculate_dn_loss(self, dn_metas, targets, aux_num, num_boxes):
8389
# dn aux loss
8490
l_dict = {}
8591
if dn_metas and "output_known_lbs_bboxes" in dn_metas:
86-
output_known_lbs_bboxes_aux=output_known_lbs_bboxes['aux_outputs'][i]
92+
output_known_lbs_bboxes_aux = output_known_lbs_bboxes["aux_outputs"][i]
8793
for loss in self.losses:
8894
kwargs = {}
89-
if 'labels' in loss:
90-
kwargs = {'log': False}
91-
l_dict.update(self.get_loss(loss, output_known_lbs_bboxes_aux, targets, dn_idx, num_boxes * dn_num,
92-
**kwargs))
95+
if "labels" in loss:
96+
kwargs = {"log": False}
97+
l_dict.update(
98+
self.get_loss(
99+
loss,
100+
output_known_lbs_bboxes_aux,
101+
targets,
102+
dn_idx,
103+
num_boxes * dn_num,
104+
**kwargs,
105+
)
106+
)
93107
l_dict = {k + f"_dn_{i}": v for k, v in l_dict.items()}
94108
else:
95109
l_dict["loss_bbox_dn"] = torch.as_tensor(0.0).to("cuda")
@@ -98,4 +112,3 @@ def calculate_dn_loss(self, dn_metas, targets, aux_num, num_boxes):
98112
l_dict = {k + f"_{i}": v for k, v in l_dict.items()}
99113
losses.update(l_dict)
100114
return losses
101-

0 commit comments

Comments
 (0)