forked from open-mmlab/mmsegmentation
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
32c9ba8
commit 8c9aaac
Showing
10 changed files
with
214 additions
and
120 deletions.
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 |
---|---|---|
@@ -0,0 +1,80 @@ | ||
# model settings | ||
_base_ = [ | ||
'../_base_/datasets/cityscapes10classes.py', '../_base_/default_runtime.py', | ||
] | ||
|
||
# optimizer | ||
optimizer = dict(type='Adam', lr=0.001, weight_decay=1e-5) | ||
optim_wrapper = dict(type='OptimWrapper', optimizer=optimizer, clip_grad=None) | ||
|
||
# learning policy | ||
param_scheduler = [ | ||
dict( | ||
type='LinearLR', start_factor=0.2, begin=0, end=1), | ||
dict( | ||
type='CosineAnnealingLR', begin=1, end=5, eta_min=0.00001) | ||
] | ||
|
||
# runtime settings | ||
train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=5, val_interval=1) | ||
val_cfg = dict(type='ValLoop') | ||
test_cfg = dict(type='TestLoop') | ||
|
||
# default hooks - logger & checkpoint configs | ||
default_hooks = dict( | ||
|
||
# print log every 100 iterations. | ||
logger=dict(type='LoggerHook', interval=1), #, log_metric_by_epoch=False), | ||
|
||
# enable the parameter scheduler. | ||
param_scheduler=dict(type='ParamSchedulerHook'), | ||
|
||
# save checkpoint every 5 epochs. | ||
checkpoint=dict(type='CheckpointHook', | ||
interval=1, | ||
save_best='mIoU', | ||
rule='greater', | ||
max_keep_ckpts=5), | ||
) | ||
|
||
# tensorboard vis ('LocalVisBackend' might be redundant) save_dir='./tf_dir/<exp_name>' | ||
visualizer = dict(type='SegLocalVisualizer', | ||
vis_backends=[dict(type='LocalVisBackend'), dict(type='TensorboardVisBackend')], | ||
name='visualizer') | ||
|
||
# data preprocessing | ||
norm_cfg = dict(type='SyncBN', requires_grad=True) | ||
crop_size = (512, 1024) | ||
data_preprocessor = dict( | ||
type='SegDataPreProcessor', | ||
mean=[0.0, 0.0, 0.0], | ||
std=[1.0, 1.0, 1.0], | ||
bgr_to_rgb=True, | ||
pad_val=0, | ||
seg_pad_val=255, | ||
size=crop_size) | ||
|
||
model = dict( | ||
type='EncoderDecoder', | ||
backbone=dict( | ||
type='hailoFPN', | ||
depth=0.33, | ||
width=0.125, | ||
bb_channels_list=[128, 256, 512, 1024], | ||
bb_num_repeats_list=[9, 15, 21, 12], | ||
neck_channels_list=[256, 128, 128, 256, 256, 512], | ||
neck_num_repeats_list=[9, 12, 12, 9]), | ||
decode_head=dict( | ||
type='ConvHead', | ||
in_channels=16, | ||
channels=128, | ||
num_convs=1, | ||
num_classes=10, | ||
norm_cfg=norm_cfg, | ||
align_corners=True, | ||
loss_decode=dict( | ||
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), | ||
# model training and testing settings | ||
train_cfg=dict(), | ||
test_cfg=dict(mode='whole'), | ||
infer_wo_softmax=True) |
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 |
---|---|---|
@@ -0,0 +1,19 @@ | ||
from mmengine.hooks import CheckpointHook | ||
from mmseg.registry import HOOKS | ||
|
||
|
||
@HOOKS.register_module() | ||
class ExtCheckpointHook(CheckpointHook): | ||
# def __init__(self): | ||
# self.by_epoch = False | ||
|
||
def after_val_epoch(self, runner, metrics): | ||
if runner.iter == self.save_begin: | ||
runner.logger.info('Resetting best_score to 0.0') | ||
runner.message_hub.update_info('best_score', 0.0) | ||
runner.message_hub.pop_info('best_ckpt', None) | ||
if (runner.iter + 1 >= self.save_begin): | ||
runner.logger.info('ExtCheckpointHook ExtCheckpointHook ExtCheckpointHook') | ||
runner.logger.info( | ||
f'Saving checkpoint at iter {runner.iter}') | ||
super().after_val_epoch(runner, metrics) |
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
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,43 +1,38 @@ | ||
from mmseg.registry import RUNNERS, HOOKS | ||
from mmseg.registry import HOOKS | ||
from mmseg.utils.misc import calc_sparsity | ||
from mmengine.hooks import Hook | ||
from sparseml.pytorch.optim import ScheduledModifierManager | ||
|
||
|
||
@HOOKS.register_module() | ||
class SparseMLHook(Hook): | ||
def __init__(self, interval=10): | ||
self.interval = interval | ||
def __init__(self, steps_per_epoch=1488, start_epoch=50, prune_interval_epoch=2): | ||
self.steps_per_epoch = steps_per_epoch | ||
self.start_epoch = start_epoch | ||
self.prune_interval_epoch = prune_interval_epoch | ||
|
||
def before_train(self, runner) -> None: | ||
self.manager = ScheduledModifierManager.from_yaml(runner.cfg.recipe) | ||
|
||
optimizer = runner.optim_wrapper.optimizer | ||
optimizer = self.manager.modify(runner.model.module, optimizer, steps_per_epoch=1488, epoch=40) | ||
optimizer = self.manager.modify(runner.model.module, | ||
optimizer, | ||
steps_per_epoch=self.steps_per_epoch, | ||
epoch=self.start_epoch) | ||
runner.optim_wrapper.optimizer = optimizer | ||
|
||
def after_train(self, runner) -> None: | ||
self.manager.finalize(runner.model.module) | ||
|
||
def after_train_iter(self, runner, batch_idx, data_batch, outputs): | ||
if batch_idx % (1488 * 2) == 0: # 2 Epochs | ||
runner.logger.info(f"Epoch #{batch_idx // 1488} End") | ||
self._calc_sparsity(runner.model.state_dict(), runner.logger) | ||
if batch_idx % (self.steps_per_epoch * self.prune_interval_epoch) == 0: # 2 Epochs | ||
calc_sparsity(runner.model.state_dict(), runner.logger) | ||
runner.logger.info(f"Epoch #{batch_idx // self.steps_per_epoch} End") | ||
|
||
def after_test_epoch(self, runner, metrics): | ||
runner.logger.info("Switching to deployment model") | ||
# if repvgg style -> deploy | ||
for module in runner.model.modules(): | ||
if hasattr(module, 'switch_to_deploy'): | ||
module.switch_to_deploy() | ||
self._calc_sparsity(runner.model.state_dict(), runner.logger) | ||
|
||
def _calc_sparsity(self, model_dict, logger): | ||
weights_layers_num, total_weights, total_zeros = 0, 0, 0 | ||
prefix = next(iter(model_dict)).split('backbone.stage0')[0] | ||
for k, v in model_dict.items(): | ||
if k.startswith(prefix) and k.endswith('weight'): | ||
weights_layers_num += 1 | ||
total_weights += v.numel() | ||
total_zeros += (v.numel() - v.count_nonzero()) | ||
logger.info(f"Model has {weights_layers_num} weight layers") | ||
logger.info(f"Overall Sparsity is roughly: {100 * total_zeros / total_weights:.1f}%") | ||
|
||
calc_sparsity(runner.model.state_dict(), runner.logger, True) |
Oops, something went wrong.