Skip to content

Commit

Permalink
upgrade to black 22.3
Browse files Browse the repository at this point in the history
Summary: Pull Request resolved: facebookresearch#4268

Reviewed By: zhanghang1989

Differential Revision: D36633678

fbshipit-source-id: 3e25a38eaed1a58c2c03469b36c8cece9de05735
  • Loading branch information
wat3rBro authored and facebook-github-bot committed May 24, 2022
1 parent cc87e7e commit 45b3fce
Show file tree
Hide file tree
Showing 29 changed files with 71 additions and 72 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
run: |
python -m pip install --upgrade pip
python -m pip install flake8==3.8.1 isort==4.3.21
python -m pip install black==21.4b2
python -m pip install black==22.3.0
flake8 --version
- name: Lint
run: |
Expand Down
2 changes: 1 addition & 1 deletion detectron2/data/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,5 +552,5 @@ def trivial_batch_collator(batch):


def worker_init_reset_seed(worker_id):
initial_seed = torch.initial_seed() % 2 ** 31
initial_seed = torch.initial_seed() % 2**31
seed_all_rng(initial_seed + worker_id)
2 changes: 1 addition & 1 deletion detectron2/data/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def _serialize(data):
self._addr = np.asarray([len(x) for x in self._lst], dtype=np.int64)
self._addr = np.cumsum(self._addr)
self._lst = np.concatenate(self._lst)
logger.info("Serialized dataset takes {:.2f} MiB".format(len(self._lst) / 1024 ** 2))
logger.info("Serialized dataset takes {:.2f} MiB".format(len(self._lst) / 1024**2))

def __len__(self):
if self._serialize:
Expand Down
2 changes: 1 addition & 1 deletion detectron2/engine/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def default_argument_parser(epilog=None):
# PyTorch still may leave orphan processes in multi-gpu training.
# Therefore we use a deterministic way to obtain port,
# so that users are aware of orphan processes by seeing the port occupied.
port = 2 ** 15 + 2 ** 14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2 ** 14
port = 2**15 + 2**14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2**14
parser.add_argument(
"--dist-url",
default="tcp://127.0.0.1:{}".format(port),
Expand Down
16 changes: 8 additions & 8 deletions detectron2/evaluation/coco_evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,14 +472,14 @@ def _evaluate_box_proposals(dataset_predictions, coco_api, thresholds=None, area
"512-inf": 7,
}
area_ranges = [
[0 ** 2, 1e5 ** 2], # all
[0 ** 2, 32 ** 2], # small
[32 ** 2, 96 ** 2], # medium
[96 ** 2, 1e5 ** 2], # large
[96 ** 2, 128 ** 2], # 96-128
[128 ** 2, 256 ** 2], # 128-256
[256 ** 2, 512 ** 2], # 256-512
[512 ** 2, 1e5 ** 2],
[0**2, 1e5**2], # all
[0**2, 32**2], # small
[32**2, 96**2], # medium
[96**2, 1e5**2], # large
[96**2, 128**2], # 96-128
[128**2, 256**2], # 128-256
[256**2, 512**2], # 256-512
[512**2, 1e5**2],
] # 512-inf
assert area in areas, "Unknown area range: {}".format(area)
area_range = area_ranges[areas[area]]
Expand Down
16 changes: 8 additions & 8 deletions detectron2/evaluation/lvis_evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,14 +238,14 @@ def _evaluate_box_proposals(dataset_predictions, lvis_api, thresholds=None, area
"512-inf": 7,
}
area_ranges = [
[0 ** 2, 1e5 ** 2], # all
[0 ** 2, 32 ** 2], # small
[32 ** 2, 96 ** 2], # medium
[96 ** 2, 1e5 ** 2], # large
[96 ** 2, 128 ** 2], # 96-128
[128 ** 2, 256 ** 2], # 128-256
[256 ** 2, 512 ** 2], # 256-512
[512 ** 2, 1e5 ** 2],
[0**2, 1e5**2], # all
[0**2, 32**2], # small
[32**2, 96**2], # medium
[96**2, 1e5**2], # large
[96**2, 128**2], # 96-128
[128**2, 256**2], # 128-256
[256**2, 512**2], # 256-512
[512**2, 1e5**2],
] # 512-inf
assert area in areas, "Unknown area range: {}".format(area)
area_range = area_ranges[areas[area]]
Expand Down
7 changes: 3 additions & 4 deletions detectron2/export/c10.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import math
from typing import Dict

import torch
import torch.nn.functional as F

Expand Down Expand Up @@ -164,12 +163,12 @@ def _set_tensor_mode(self, v):


class Caffe2RPN(Caffe2Compatible, rpn.RPN):

@classmethod
def from_config(cls, cfg, input_shape: Dict[str, ShapeSpec]):
ret = super(Caffe2Compatible, cls).from_config(cfg, input_shape)
assert tuple(cfg.MODEL.RPN.BBOX_REG_WEIGHTS) == (1., 1., 1., 1.) or \
tuple(cfg.MODEL.RPN.BBOX_REG_WEIGHTS) == (1., 1., 1., 1., 1.)
assert tuple(cfg.MODEL.RPN.BBOX_REG_WEIGHTS) == (1.0, 1.0, 1.0, 1.0) or tuple(
cfg.MODEL.RPN.BBOX_REG_WEIGHTS
) == (1.0, 1.0, 1.0, 1.0, 1.0)
return ret

def _generate_proposals(
Expand Down
2 changes: 1 addition & 1 deletion detectron2/layers/losses.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def ciou_loss(
h_pred = y2 - y1
w_gt = x2g - x1g
h_gt = y2g - y1g
v = (4 / (math.pi ** 2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2)
v = (4 / (math.pi**2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2)
with torch.no_grad():
alpha = v / (1 - iou + v + eps)

Expand Down
2 changes: 1 addition & 1 deletion detectron2/layers/mask_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
BYTES_PER_FLOAT = 4
# TODO: This memory limit may be too much or too little. It would be better to
# determine it based on available resources.
GPU_MEM_LIMIT = 1024 ** 3 # 1 GB memory limit
GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit


def _do_paste_mask(masks, boxes, img_h: int, img_w: int, skip_empty: bool = True):
Expand Down
4 changes: 2 additions & 2 deletions detectron2/modeling/anchor_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ def generate_cell_anchors(self, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.

anchors = []
for size in sizes:
area = size ** 2.0
area = size**2.0
for aspect_ratio in aspect_ratios:
# s * s = w * h
# a = h / w
Expand Down Expand Up @@ -349,7 +349,7 @@ def generate_cell_anchors(
"""
anchors = []
for size in sizes:
area = size ** 2.0
area = size**2.0
for aspect_ratio in aspect_ratios:
# s * s = w * h
# a = h / w
Expand Down
2 changes: 1 addition & 1 deletion detectron2/solver/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def build_lr_scheduler(
"These values will be ignored."
)
sched = MultiStepParamScheduler(
values=[cfg.SOLVER.GAMMA ** k for k in range(len(steps) + 1)],
values=[cfg.SOLVER.GAMMA**k for k in range(len(steps) + 1)],
milestones=steps,
num_updates=cfg.SOLVER.MAX_ITER,
)
Expand Down
2 changes: 1 addition & 1 deletion detectron2/utils/comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def shared_random_seed():
All workers must call this function, otherwise it will deadlock.
"""
ints = np.random.randint(2 ** 31)
ints = np.random.randint(2**31)
all_ints = all_gather(ints)
return all_ints[0]

Expand Down
2 changes: 1 addition & 1 deletion detectron2/utils/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ def put_histogram(self, hist_name, hist_tensor, bins=1000):
max=ht_max,
num=len(hist_tensor),
sum=float(hist_tensor.sum()),
sum_squares=float(torch.sum(hist_tensor ** 2)),
sum_squares=float(torch.sum(hist_tensor**2)),
bucket_limits=hist_edges[1:].tolist(),
bucket_counts=hist_counts.tolist(),
global_step=self._iter,
Expand Down
4 changes: 2 additions & 2 deletions dev/linter.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
cd "$(dirname "${BASH_SOURCE[0]}")/.."

{
black --version | grep -E "21\." > /dev/null
black --version | grep -E "22\." > /dev/null
} || {
echo "Linter requires 'black==21.*' !"
echo "Linter requires 'black==22.*' !"
exit 1
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ def computeOks(self, imgId, catId):
z = np.zeros(k)
dx = np.max((z, x0 - xd), axis=0) + np.max((z, xd - x1), axis=0)
dy = np.max((z, y0 - yd), axis=0) + np.max((z, yd - y1), axis=0)
e = (dx ** 2 + dy ** 2) / vars / (gt["area"] + np.spacing(1)) / 2
e = (dx**2 + dy**2) / vars / (gt["area"] + np.spacing(1)) / 2
if k1 > 0:
e = e[vg > 0]
ious[i, j] = np.sum(np.exp(-e)) / e.shape[0]
Expand Down Expand Up @@ -767,7 +767,7 @@ def computeOgps(self, imgId, catId):
)
# Compute gps
ogps_values = np.exp(
-(dists_between_matches ** 2) / (2 * (dist_norm_coeffs ** 2))
-(dists_between_matches**2) / (2 * (dist_norm_coeffs**2))
)
#
ogps = np.mean(ogps_values) if len(ogps_values) > 0 else 0.0
Expand Down Expand Up @@ -1265,10 +1265,10 @@ def setDetParams(self):
self.recThrs = np.linspace(0.0, 1.00, int(np.round((1.00 - 0.0) / 0.01)) + 1, endpoint=True)
self.maxDets = [1, 10, 100]
self.areaRng = [
[0 ** 2, 1e5 ** 2],
[0 ** 2, 32 ** 2],
[32 ** 2, 96 ** 2],
[96 ** 2, 1e5 ** 2],
[0**2, 1e5**2],
[0**2, 32**2],
[32**2, 96**2],
[96**2, 1e5**2],
]
self.areaRngLbl = ["all", "small", "medium", "large"]
self.useCats = 1
Expand All @@ -1280,7 +1280,7 @@ def setKpParams(self):
self.iouThrs = np.linspace(0.5, 0.95, np.round((0.95 - 0.5) / 0.05) + 1, endpoint=True)
self.recThrs = np.linspace(0.0, 1.00, np.round((1.00 - 0.0) / 0.01) + 1, endpoint=True)
self.maxDets = [20]
self.areaRng = [[0 ** 2, 1e5 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]
self.areaRng = [[0**2, 1e5**2], [32**2, 96**2], [96**2, 1e5**2]]
self.areaRngLbl = ["all", "medium", "large"]
self.useCats = 1

Expand All @@ -1290,7 +1290,7 @@ def setUvParams(self):
self.iouThrs = np.linspace(0.5, 0.95, int(np.round((0.95 - 0.5) / 0.05)) + 1, endpoint=True)
self.recThrs = np.linspace(0.0, 1.00, int(np.round((1.00 - 0.0) / 0.01)) + 1, endpoint=True)
self.maxDets = [20]
self.areaRng = [[0 ** 2, 1e5 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]
self.areaRng = [[0**2, 1e5**2], [32**2, 96**2], [96**2, 1e5**2]]
self.areaRngLbl = ["all", "medium", "large"]
self.useCats = 1

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def evaluate(self):
[keyvertices_2[name] for name in keyvertex_names_1],
]
Current_Mean_Distances = 0.255
gps = (-(geodists ** 2) / (2 * (Current_Mean_Distances ** 2))).exp()
gps = (-(geodists**2) / (2 * (Current_Mean_Distances**2))).exp()
avg_errors.append(geodists.mean().item())
avg_gps.append(gps.mean().item())

Expand Down
6 changes: 3 additions & 3 deletions projects/DensePose/densepose/modeling/hrfpn.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def __init__(
in_channels=in_channels[i],
out_channels=in_channels[i],
kernel_size=4,
stride=2 ** i,
stride=2**i,
padding=0,
output_padding=0,
bias=False,
Expand All @@ -105,7 +105,7 @@ def __init__(
for i in range(self.n_out_features):
self.reduction_pooling_conv.append(
nn.Sequential(
nn.Conv2d(sum(in_channels), out_channels, kernel_size=2 ** i, stride=2 ** i),
nn.Conv2d(sum(in_channels), out_channels, kernel_size=2**i, stride=2**i),
nn.BatchNorm2d(out_channels, momentum=0.1),
nn.ReLU(inplace=True),
)
Expand Down Expand Up @@ -148,7 +148,7 @@ def forward(self, inputs):
outs.append(self.reduction_pooling_conv[i](out))
for i in range(len(outs)): # Make shapes consistent
outs[-1 - i] = outs[-1 - i][
:, :, : outs[-1].shape[2] * 2 ** i, : outs[-1].shape[3] * 2 ** i
:, :, : outs[-1].shape[2] * 2**i, : outs[-1].shape[3] * 2**i
]
outputs = []
for i in range(len(outs)):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,17 +188,17 @@ def forward(
# compute $\sigma_i^2$
sigma2 = F.softplus(sigma_u) + self.sigma_lower_bound
# compute \|r_i\|^2
r_sqnorm2 = kappa_u_est ** 2 + kappa_v_est ** 2
r_sqnorm2 = kappa_u_est**2 + kappa_v_est**2
delta_u = u - target_u
delta_v = v - target_v
# compute \|delta_i\|^2
delta_sqnorm = delta_u ** 2 + delta_v ** 2
delta_sqnorm = delta_u**2 + delta_v**2
delta_u_r_u = delta_u * kappa_u_est
delta_v_r_v = delta_v * kappa_v_est
# compute the scalar product <delta_i, r_i>
delta_r = delta_u_r_u + delta_v_r_v
# compute squared scalar product <delta_i, r_i>^2
delta_r_sqnorm = delta_r ** 2
delta_r_sqnorm = delta_r**2
denom2 = sigma2 * (sigma2 + r_sqnorm2)
loss = 0.5 * (
self.log2pi + torch.log(denom2) + delta_sqnorm / sigma2 - delta_r_sqnorm / denom2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,11 +193,11 @@ def rotate_box_inverse(rot_tfm, rotated_box):
invrot_box = rot_tfm.inverse().apply_box(rotated_box)
h, w = rotated_box[:, 3] - rotated_box[:, 1], rotated_box[:, 2] - rotated_box[:, 0]
ih, iw = invrot_box[:, 3] - invrot_box[:, 1], invrot_box[:, 2] - invrot_box[:, 0]
assert 2 * rot_tfm.abs_sin ** 2 != 1, "45 degrees angle can't be inverted"
assert 2 * rot_tfm.abs_sin**2 != 1, "45 degrees angle can't be inverted"
# 2. Inverse the corresponding computation in the rotation transform
# to get the original height/width of the rotated boxes
orig_h = (h * rot_tfm.abs_cos - w * rot_tfm.abs_sin) / (1 - 2 * rot_tfm.abs_sin ** 2)
orig_w = (w * rot_tfm.abs_cos - h * rot_tfm.abs_sin) / (1 - 2 * rot_tfm.abs_sin ** 2)
orig_h = (h * rot_tfm.abs_cos - w * rot_tfm.abs_sin) / (1 - 2 * rot_tfm.abs_sin**2)
orig_w = (w * rot_tfm.abs_cos - h * rot_tfm.abs_sin) / (1 - 2 * rot_tfm.abs_sin**2)
# 3. Resize the inverse-rotated bboxes to their original size
invrot_box[:, 0] += (iw - orig_w) / 2
invrot_box[:, 1] += (ih - orig_h) / 2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def get_xyz_vertex_embedding(mesh_name: str, device: torch.device):
embed_map = mesh.vertices.sum(dim=1)
embed_map -= embed_map.min()
embed_map /= embed_map.max()
embed_map = embed_map ** 2
embed_map = embed_map**2
return embed_map


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(
x = np.arange(0, size, 1, float)
y = x[:, np.newaxis]
x0, y0 = 3 * sigma + 1, 3 * sigma + 1
self.g = np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))
self.g = np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma**2))

def __call__(self, panoptic, segments_info):
"""Generates the training target.
Expand Down
4 changes: 2 additions & 2 deletions projects/PointRend/point_rend/mask_head.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def _init_point_head(self, cfg, input_shape):
# An optimization to skip unused subdivision steps: if after subdivision, all pixels on
# the mask will be selected and recomputed anyway, we should just double our init_resolution
while (
4 * self.mask_point_subdivision_init_resolution ** 2
4 * self.mask_point_subdivision_init_resolution**2
<= self.mask_point_subdivision_num_points
):
self.mask_point_subdivision_init_resolution *= 2
Expand Down Expand Up @@ -404,7 +404,7 @@ def forward(self, features, instances):
if self.training:
proposal_boxes = [x.proposal_boxes for x in instances]
parameters = self.parameter_head(self._roi_pooler(features, proposal_boxes))
losses = {"loss_l2": self.regularizer * (parameters ** 2).mean()}
losses = {"loss_l2": self.regularizer * (parameters**2).mean()}

point_coords, point_labels = self._uniform_sample_train_points(instances)
point_fine_grained_features = self._point_pooler(features, proposal_boxes, point_coords)
Expand Down
12 changes: 6 additions & 6 deletions projects/TensorMask/tensormask/arch.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ def losses(
if self.mask_on:
loss_mask = 0
for lvl in range(self.num_levels):
cur_level_factor = 2 ** lvl if self.bipyramid_on else 1
cur_level_factor = 2**lvl if self.bipyramid_on else 1
for anc in range(self.num_anchors):
cur_gt_mask_inds = gt_mask_inds[lvl][anc]
if cur_gt_mask_inds is None:
Expand All @@ -477,7 +477,7 @@ def losses(
cur_mask_size = self.mask_sizes[anc] * cur_level_factor
# TODO maybe there are numerical issues when mask sizes are large
cur_size_divider = torch.tensor(
self.mask_loss_weight / (cur_mask_size ** 2),
self.mask_loss_weight / (cur_mask_size**2),
dtype=torch.float32,
device=self.device,
)
Expand Down Expand Up @@ -591,7 +591,7 @@ def get_ground_truth(self, anchors, unit_lengths, indexes, targets):
for lvl in range(self.num_levels):
ids_lvl = matched_indexes[:, 0] == lvl
if torch.any(ids_lvl):
cur_level_factor = 2 ** lvl if self.bipyramid_on else 1
cur_level_factor = 2**lvl if self.bipyramid_on else 1
for anc in range(self.num_anchors):
ids_lvl_anchor = ids_lvl & (matched_indexes[:, 4] == anc)
if torch.any(ids_lvl_anchor):
Expand Down Expand Up @@ -734,7 +734,7 @@ def inference_single_image(
result_anchors = top_anchors[keep]
# Get masks and do sigmoid
for lvl, _, h, w, anc in result_indexes.tolist():
cur_size = self.mask_sizes[anc] * (2 ** lvl if self.bipyramid_on else 1)
cur_size = self.mask_sizes[anc] * (2**lvl if self.bipyramid_on else 1)
result_masks.append(
torch.sigmoid(pred_masks[lvl][anc][:, h, w].view(1, cur_size, cur_size))
)
Expand Down Expand Up @@ -831,7 +831,7 @@ def __init__(self, cfg, num_levels, num_anchors, mask_sizes, input_shape: List[S
if self.bipyramid_on:
for lvl in range(num_levels):
cur_mask_module = "align2nat_%02d" % lvl
lambda_val = 2 ** lvl
lambda_val = 2**lvl
setattr(self, cur_mask_module, SwapAlign2Nat(lambda_val))
# Also the fusing layer, stay at the same channel size
mask_fuse = [
Expand Down Expand Up @@ -885,7 +885,7 @@ def forward(self, features):
H, W = mask_feat_high_res.shape[-2:]
mask_feats_up = []
for lvl, mask_feat in enumerate(mask_feats):
lambda_val = 2.0 ** lvl
lambda_val = 2.0**lvl
mask_feat_up = mask_feat
if lvl > 0:
mask_feat_up = F.interpolate(
Expand Down
Loading

0 comments on commit 45b3fce

Please sign in to comment.