-
Notifications
You must be signed in to change notification settings - Fork 552
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feature] Add autoanchor
for YOLO series
#654
Open
yechenzhi
wants to merge
20
commits into
open-mmlab:dev
Choose a base branch
from
yechenzhi:ycz/antoanchor
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
1f0e631
base code for autoanchor(with bug)
yechenzhi b2e3838
del anchor generator
yechenzhi 43dcb9b
del configs
yechenzhi 7348c6c
del local configs
yechenzhi d464820
del change
yechenzhi ecf7a42
add logs
yechenzhi a386238
adapt autoanchor to ema
yechenzhi 450dbe4
fix format
yechenzhi d0f5cba
fix format
yechenzhi 9069340
fix ema logic
yechenzhi 2c41f7d
fix format
yechenzhi f13c038
fix assert
yechenzhi b082292
del local change
yechenzhi cb11b90
add note
yechenzhi 69c1002
add default autoanchor
yechenzhi f4d65b9
fix default
yechenzhi 873f957
add note to assure priority
yechenzhi 94d43c0
del offline autoanchors
yechenzhi fecf166
add comment and modify train.py
yechenzhi e0cd9ae
del local changes
yechenzhi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,11 @@ | ||
# Copyright (c) OpenMMLab. All rights reserved. | ||
from .ppyoloe_param_scheduler_hook import PPYOLOEParamSchedulerHook | ||
from .switch_to_deploy_hook import SwitchToDeployHook | ||
from .yolo_auto_anchor_hook import YOLOAutoAnchorHook | ||
from .yolov5_param_scheduler_hook import YOLOv5ParamSchedulerHook | ||
from .yolox_mode_switch_hook import YOLOXModeSwitchHook | ||
|
||
__all__ = [ | ||
'YOLOv5ParamSchedulerHook', 'YOLOXModeSwitchHook', 'SwitchToDeployHook', | ||
'PPYOLOEParamSchedulerHook' | ||
'PPYOLOEParamSchedulerHook', 'YOLOAutoAnchorHook' | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
# Copyright (c) OpenMMLab. All rights reserved. | ||
import torch | ||
from mmengine.dist import broadcast, get_dist_info | ||
from mmengine.hooks import Hook | ||
from mmengine.logging import MMLogger | ||
from mmengine.model import is_model_wrapper | ||
from mmengine.runner import Runner | ||
|
||
from mmyolo.registry import HOOKS, TASK_UTILS | ||
|
||
|
||
@HOOKS.register_module() | ||
class YOLOAutoAnchorHook(Hook): | ||
|
||
priority = 48 | ||
|
||
# YOLOAutoAnchorHook takes priority over EMAHook. | ||
|
||
def __init__(self, optimizer): | ||
yechenzhi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
self.optimizer = optimizer | ||
print('YOLOAutoAnchorHook should take priority over EMAHook, ' | ||
'the default priority of EMAHook is 49, so the priority of ' | ||
'YOLOAutoAnchorHook is 48') | ||
|
||
def before_run(self, runner) -> None: | ||
|
||
model = runner.model | ||
if is_model_wrapper(model): | ||
model = model.module | ||
|
||
device = next(model.parameters()).device | ||
anchors = torch.tensor( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这个地方应该用 model 内部属性比较好,而不是用配置。而且要写的鲁棒点 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 直接用model.bbox_head.prior_generator.base_sizes 这样可以嘛? |
||
model.bbox_head.prior_generator.base_sizes, device=device) | ||
model.register_buffer('anchors', anchors) | ||
|
||
def before_train(self, runner: Runner) -> None: | ||
|
||
if runner.iter > 0: | ||
return | ||
model = runner.model | ||
if is_model_wrapper(model): | ||
model = model.module | ||
print('begin reloading optimized anchors') | ||
|
||
rank, _ = get_dist_info() | ||
|
||
weights = model.state_dict() | ||
anchors_tensor = weights['anchors'] | ||
if rank == 0 and not runner._has_loaded: | ||
runner_dataset = runner.train_dataloader.dataset | ||
yechenzhi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.optimizer.update( | ||
dataset=runner_dataset, | ||
device=runner_dataset[0]['inputs'].device, | ||
input_shape=runner.cfg['img_scale'], | ||
logger=MMLogger.get_current_instance()) | ||
|
||
optimizer = TASK_UTILS.build(self.optimizer) | ||
anchors = optimizer.optimize() | ||
device = next(model.parameters()).device | ||
anchors_tensor = torch.tensor(anchors, device=device) | ||
|
||
broadcast(anchors_tensor) | ||
weights['anchors'] = anchors_tensor | ||
model.load_state_dict(weights) | ||
|
||
self.reinitialize(runner, model) | ||
|
||
def before_val(self, runner: Runner) -> None: | ||
|
||
model = runner.model | ||
if is_model_wrapper(model): | ||
model = model.module | ||
print('begin reloading optimized anchors') | ||
self.reinitialize(runner, model) | ||
|
||
def before_test(self, runner: Runner) -> None: | ||
|
||
model = runner.model | ||
if is_model_wrapper(model): | ||
model = model.module | ||
print('begin reloading optimized anchors') | ||
self.reinitialize(runner, model) | ||
|
||
def reinitialize(self, runner: Runner, model) -> None: | ||
anchors_tensor = model.state_dict()['anchors'] | ||
base_sizes = anchors_tensor.tolist() | ||
device = anchors_tensor.device | ||
prior_generator = runner.cfg.model.bbox_head.prior_generator | ||
prior_generator.update(base_sizes=base_sizes) | ||
|
||
model.bbox_head.prior_generator = TASK_UTILS.build(prior_generator) | ||
|
||
priors_base_sizes = torch.tensor( | ||
base_sizes, dtype=torch.float, device=device) | ||
featmap_strides = torch.tensor( | ||
model.bbox_head.featmap_strides, dtype=torch.float, | ||
device=device)[:, None, None] | ||
model.bbox_head.priors_base_sizes = priors_base_sizes / featmap_strides |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,13 @@ | ||
# Copyright (c) OpenMMLab. All rights reserved. | ||
from .anchor_optimizers import (YOLODEAnchorOptimizer, | ||
YOLOKMeansAnchorOptimizer, | ||
YOLOV5KMeansAnchorOptimizer) | ||
from .collect_env import collect_env | ||
from .misc import is_metainfo_lower, switch_to_deploy | ||
from .setup_env import register_all_modules | ||
|
||
__all__ = [ | ||
'register_all_modules', 'collect_env', 'switch_to_deploy', | ||
'is_metainfo_lower' | ||
'is_metainfo_lower', 'YOLOKMeansAnchorOptimizer', | ||
'YOLOV5KMeansAnchorOptimizer', 'YOLODEAnchorOptimizer' | ||
] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
既然有这个要求,那么在这个hook初始化时候一定要记得打印下,说明这个hook优先级必须高于 emahook,提供更多信息