Skip to content
This repository has been archived by the owner on Nov 16, 2023. It is now read-only.

Update visualization #263

Closed
wants to merge 80 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
80 commits
Select commit Hold shift + click to select a range
b10010b
Merge pull request #4 from microsoft/staging
yalaudah Feb 20, 2020
b26c0d0
Merge pull request #5 from microsoft/staging
yalaudah Feb 21, 2020
b6e184b
Merge pull request #6 from microsoft/staging
Mar 3, 2020
70ae8e9
format with black
Mar 16, 2020
1d85b20
updates to the HRnet notebook
Mar 16, 2020
89008be
updates to penobscot notebook
Mar 17, 2020
b1c1a29
set normalize=True as default in create_image_writer
Mar 26, 2020
2659039
remove HorovodLRScheduler
Mar 30, 2020
cc1c75d
minor cleanup in logging_handlers
Mar 30, 2020
9d36a03
tb_handlers update
Mar 30, 2020
417c721
major changes to train.py
Mar 30, 2020
020c52f
Checkpointing
Mar 30, 2020
1f646d2
Minor update to configs (TRAIN.DEPTH)
Mar 30, 2020
942be67
Remove OpenCV completely :)
Mar 30, 2020
21d9917
Minor formatting, renaming, and cleanup.
Mar 30, 2020
c1e4daa
final cleanup
Mar 31, 2020
759b4e0
resetting some params in the configs
Mar 31, 2020
a17cd95
minor
Mar 31, 2020
76cc485
removed files deleted in PR #226
Mar 31, 2020
5424b9d
Merge branch 'staging' into update-visualization
Mar 31, 2020
aaa73ed
sort imports + use OPENCV_BORDER_CONSTANT instead of 0
Apr 1, 2020
f9b0832
backward compatability fix
Apr 2, 2020
2448580
bug fixes
Apr 3, 2020
3aaccb3
bug fix
Apr 3, 2020
4f49c53
bug pixes
Apr 4, 2020
f108a7d
Merge branch 'staging' into update-visualization
Apr 6, 2020
198129d
add opencv_border_constant to hrnet configs
Apr 6, 2020
a7e4a1d
changed bacth_size back to 100
Apr 7, 2020
bc2795b
Merge branch 'staging' into update-visualization
Apr 8, 2020
8981a99
Bug fix (surprised this didn't fail in the test ?!)
Apr 8, 2020
050e60f
reverting back to toolz.take
Apr 9, 2020
e4f777e
reverting back to Subset
Apr 9, 2020
2d66cd1
revert to using Subset()
Apr 9, 2020
6ac5ddc
Merge branch 'update-visualization' of https://github.com/yalaudah/se…
Apr 9, 2020
728eee2
bug fix
Apr 9, 2020
47f8631
minor update
Apr 9, 2020
15bc908
bug fix
Apr 9, 2020
060934e
bug fix
Apr 9, 2020
1b0d0d3
bug fix
Apr 9, 2020
389db40
debug
Apr 10, 2020
a5cc374
bug fix
Apr 10, 2020
83ee765
bug fix
Apr 10, 2020
f9c8dd5
Merge branch 'update-visualization' of https://github.com/yalaudah/se…
Apr 10, 2020
7013222
bf
Apr 10, 2020
c9bb6e7
testing pytorch random sampler
Apr 10, 2020
c240e6b
test
Apr 10, 2020
680be64
test
Apr 10, 2020
7228c70
bug fix
Apr 10, 2020
ac9f466
bug fix
Apr 10, 2020
7a87219
testing changing # epochs
Apr 10, 2020
65fd65a
reverting back to Subset()
Apr 11, 2020
f23098e
bug fix
Apr 13, 2020
5b92d1a
set normalize=True as default in create_image_writer
Mar 26, 2020
c9296c2
remove HorovodLRScheduler
Mar 30, 2020
6ca225b
minor cleanup in logging_handlers
Mar 30, 2020
fce950c
tb_handlers update
Mar 30, 2020
c00ef21
major changes to train.py
Mar 30, 2020
5621c79
Minor update to configs (TRAIN.DEPTH)
Mar 30, 2020
42cd8a4
resetting some params in the configs
Mar 31, 2020
ad6e110
removed files deleted in PR #226
Mar 31, 2020
e715c6a
sort imports + use OPENCV_BORDER_CONSTANT instead of 0
Apr 1, 2020
dab19f0
backward compatability fix
Apr 2, 2020
86af496
bug fixes
Apr 3, 2020
013c726
bug pixes
Apr 4, 2020
2befab1
reverting back to toolz.take
Apr 9, 2020
d1b7a30
revert to using Subset()
Apr 9, 2020
67fba17
bug fix
Apr 9, 2020
1bc6f93
minor update
Apr 9, 2020
166ed77
bug fix
Apr 9, 2020
efcd2b0
bug fix
Apr 9, 2020
37c1437
bug fix
Apr 10, 2020
fb39cc3
bf
Apr 10, 2020
8558b39
bug fix
Apr 10, 2020
0e41395
bug fix
Apr 10, 2020
bc72ae0
reverting back to Subset()
Apr 11, 2020
fb2fe4b
bug fix
Apr 13, 2020
f32bc76
Merge remote-tracking branch 'upstream/correctness' into pr/yalaudah/256
Apr 13, 2020
c23fa3f
minor fix
Apr 14, 2020
5c07749
attempting to fix "cycle_size equal to 1" error.
Apr 14, 2020
6def684
adding correctness branch to build
Apr 14, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ TRAIN:
LR: 0.02
MOMENTUM: 0.9
WEIGHT_DECAY: 0.0001
DEPTH: "voxel" # Options are No, Patch, Section and Voxel
DEPTH: "voxel" # Options are none, patch, section and voxel
MODEL_DIR: "models"

VALIDATION:
Expand Down
4 changes: 3 additions & 1 deletion contrib/experiments/interpretation/dutchf3_voxel/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
_C.PRINT_FREQ = 20
_C.LOG_CONFIG = "logging.conf"
_C.SEED = 42
_C.OPENCV_BORDER_CONSTANT = 0

# size of voxel cube: WINDOW_SIZE x WINDOW_SIZE x WINDOW_SIZE; used for 3D models only
_C.WINDOW_SIZE = 65

Expand All @@ -50,7 +52,7 @@
_C.TRAIN.LR = 0.01
_C.TRAIN.MOMENTUM = 0.9
_C.TRAIN.WEIGHT_DECAY = 0.0001
_C.TRAIN.DEPTH = "voxel" # Options are None, Patch and Section
_C.TRAIN.DEPTH = "voxel" # Options are none, patch and section
_C.TRAIN.MODEL_DIR = "models" # This will be a subdirectory inside OUTPUT_DIR

# validation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ WORKERS: 4
PRINT_FREQ: 10
LOG_CONFIG: logging.conf
SEED: 2019
OPENCV_BORDER_CONSTANT: 0


DATASET:
Expand Down Expand Up @@ -75,7 +76,7 @@ TRAIN:
WEIGHT_DECAY: 0.0001
SNAPSHOTS: 5
AUGMENTATION: True
DEPTH: "patch" # Options are none, patch and section
DEPTH: "patch" # Options are none, patch, and section
STRIDE: 64
PATCH_SIZE: 128
AUGMENTATIONS:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ TRAIN:
WEIGHT_DECAY: 0.0001
SNAPSHOTS: 5
AUGMENTATION: True
DEPTH: "patch" # Options are none, patch and section
DEPTH: "patch" # Options are none, patch, and section
STRIDE: 64
PATCH_SIZE: 128
AUGMENTATIONS:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
_C.PIN_MEMORY = True
_C.LOG_CONFIG = "logging.conf"
_C.SEED = 42
_C.OPENCV_BORDER_CONSTANT = 0

# size of voxel cube: WINDOW_SIZE x WINDOW_SIZE x WINDOW_SIZE; used for 3D models only
_C.WINDOW_SIZE = 65
Expand Down Expand Up @@ -72,7 +73,7 @@
_C.TRAIN.MEAN = [-0.0001777, 0.49, -0.0000688] # 0.0009996710808862074
_C.TRAIN.STD = [0.14076, 0.2717, 0.06286] # 0.20976548783479299
_C.TRAIN.MAX = 1
_C.TRAIN.DEPTH = "patch" # Options are none, patch and section
_C.TRAIN.DEPTH = "patch" # Options are none, patch, and section
# None adds no depth information and the num of channels remains at 1
# Patch adds depth per patch so is simply the height of that patch from 0 to 1, channels=3
# Section adds depth per section so contains depth information for the whole section, channels=3
Expand Down
41 changes: 13 additions & 28 deletions contrib/experiments/interpretation/penobscot/local/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,45 +18,30 @@
from itertools import chain
from os import path

import cv2
import fire
import numpy as np
import torch
import torchvision
from albumentations import Compose, Normalize, PadIfNeeded, Resize
from cv_lib.utils import load_log_configuration
from ignite.engine import Events
from ignite.metrics import Loss
from ignite.utils import convert_tensor
from toolz import compose, tail, take
from toolz.sandbox.core import unzip
from torch.utils import data

from cv_lib.event_handlers import logging_handlers, tensorboard_handlers
from cv_lib.event_handlers.tensorboard_handlers import (
create_image_writer,
create_summary_writer,
)
from cv_lib.event_handlers.tensorboard_handlers import create_image_writer, create_summary_writer
from cv_lib.segmentation import models
from cv_lib.segmentation.metrics import (
pixelwise_accuracy,
class_accuracy,
mean_class_accuracy,
class_iou,
mean_iou,
)
from cv_lib.segmentation.dutchf3.utils import (
current_datetime,
generate_path,
git_branch,
git_hash,
np_to_tb,
)
from cv_lib.segmentation.dutchf3.utils import current_datetime, generate_path, git_branch, git_hash, np_to_tb
from cv_lib.segmentation.metrics import class_accuracy, class_iou, mean_class_accuracy, mean_iou, pixelwise_accuracy
from cv_lib.segmentation.penobscot.engine import create_supervised_evaluator
from cv_lib.utils import load_log_configuration
from deepseismic_interpretation.dutchf3.data import decode_segmap
from deepseismic_interpretation.penobscot.data import get_patch_dataset
from deepseismic_interpretation.penobscot.metrics import InlineMeanIoU
from default import _C as config
from default import update_config
from ignite.engine import Events
from ignite.metrics import Loss
from ignite.utils import convert_tensor
from toolz import compose, tail, take
from toolz.sandbox.core import unzip
from torch.utils import data


def _prepare_batch(batch, device=None, non_blocking=False):
Expand Down Expand Up @@ -139,7 +124,7 @@ def run(*options, cfg=None, debug=False):
PadIfNeeded(
min_height=config.TRAIN.PATCH_SIZE,
min_width=config.TRAIN.PATCH_SIZE,
border_mode=cv2.BORDER_CONSTANT,
border_mode=config.OPENCV_BORDER_CONSTANT,
always_apply=True,
mask_value=mask_value,
value=0,
Expand All @@ -150,7 +135,7 @@ def run(*options, cfg=None, debug=False):
PadIfNeeded(
min_height=config.TRAIN.AUGMENTATIONS.PAD.HEIGHT,
min_width=config.TRAIN.AUGMENTATIONS.PAD.WIDTH,
border_mode=cv2.BORDER_CONSTANT,
border_mode=config.OPENCV_BORDER_CONSTANT,
always_apply=True,
mask_value=mask_value,
value=0,
Expand Down
52 changes: 13 additions & 39 deletions contrib/experiments/interpretation/penobscot/local/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import logging.config
from os import path

import cv2
import fire
import numpy as np
import torch
Expand All @@ -26,46 +25,21 @@
from ignite.engine import Events
from ignite.metrics import Loss
from ignite.utils import convert_tensor
from toolz import compose
from toolz import compose, take
from torch.utils import data

from cv_lib.event_handlers import SnapshotHandler, logging_handlers, tensorboard_handlers
from cv_lib.event_handlers.logging_handlers import Evaluator
from cv_lib.event_handlers.tensorboard_handlers import create_image_writer, create_summary_writer
from cv_lib.segmentation import extract_metric_from, models
from cv_lib.segmentation.dutchf3.utils import current_datetime, generate_path, git_branch, git_hash, np_to_tb
from cv_lib.segmentation.metrics import class_accuracy, class_iou, mean_class_accuracy, mean_iou, pixelwise_accuracy
from cv_lib.segmentation.penobscot.engine import create_supervised_evaluator, create_supervised_trainer
from cv_lib.utils import load_log_configuration
from deepseismic_interpretation.dutchf3.data import decode_segmap
from deepseismic_interpretation.penobscot.data import get_patch_dataset
from cv_lib.utils import load_log_configuration
from cv_lib.event_handlers import (
SnapshotHandler,
logging_handlers,
tensorboard_handlers,
)
from cv_lib.event_handlers.logging_handlers import Evaluator
from cv_lib.event_handlers.tensorboard_handlers import (
create_image_writer,
create_summary_writer,
)
from cv_lib.segmentation import models, extract_metric_from
from cv_lib.segmentation.penobscot.engine import (
create_supervised_evaluator,
create_supervised_trainer,
)
from cv_lib.segmentation.metrics import (
pixelwise_accuracy,
class_accuracy,
mean_class_accuracy,
class_iou,
mean_iou,
)
from cv_lib.segmentation.dutchf3.utils import (
current_datetime,
generate_path,
git_branch,
git_hash,
np_to_tb,
)

from default import _C as config
from default import update_config
from toolz import take


mask_value = 255
_SEG_COLOURS = np.asarray(
Expand Down Expand Up @@ -108,7 +82,7 @@ def run(*options, cfg=None, debug=False):
load_log_configuration(config.LOG_CONFIG)
logger = logging.getLogger(__name__)
logger.debug(config.WORKERS)
scheduler_step = config.TRAIN.END_EPOCH // config.TRAIN.SNAPSHOTS
epochs_per_cycle = config.TRAIN.END_EPOCH // config.TRAIN.SNAPSHOTS
torch.backends.cudnn.benchmark = config.CUDNN.BENCHMARK

torch.manual_seed(config.SEED)
Expand All @@ -127,7 +101,7 @@ def run(*options, cfg=None, debug=False):
PadIfNeeded(
min_height=config.TRAIN.PATCH_SIZE,
min_width=config.TRAIN.PATCH_SIZE,
border_mode=cv2.BORDER_CONSTANT,
border_mode=config.OPENCV_BORDER_CONSTANT,
always_apply=True,
mask_value=mask_value,
value=0,
Expand All @@ -138,7 +112,7 @@ def run(*options, cfg=None, debug=False):
PadIfNeeded(
min_height=config.TRAIN.AUGMENTATIONS.PAD.HEIGHT,
min_width=config.TRAIN.AUGMENTATIONS.PAD.WIDTH,
border_mode=cv2.BORDER_CONSTANT,
border_mode=config.OPENCV_BORDER_CONSTANT,
always_apply=True,
mask_value=mask_value,
value=0,
Expand Down Expand Up @@ -201,7 +175,7 @@ def run(*options, cfg=None, debug=False):
output_dir = generate_path(config.OUTPUT_DIR, config_file_name, config.TRAIN.MODEL_DIR, current_datetime(),)

summary_writer = create_summary_writer(log_dir=path.join(output_dir, config.LOG_DIR))
snapshot_duration = scheduler_step * len(train_loader)
snapshot_duration = min(epochs_per_cycle * len(train_loader), 2)
scheduler = CosineAnnealingScheduler(optimizer, "lr", config.TRAIN.MAX_LR, config.TRAIN.MIN_LR, snapshot_duration)

# weights are inversely proportional to the frequency of the classes in
Expand Down
43 changes: 2 additions & 41 deletions cv_lib/cv_lib/event_handlers/logging_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,8 @@ def log_lr(optimizer, engine):
logger.info(f"lr - {lr}")


_DEFAULT_METRICS = {"pixacc": "Avg accuracy :", "nll": "Avg loss :"}


@curry
def log_metrics(log_msg, engine, metrics_dict=_DEFAULT_METRICS):
def log_metrics(log_msg, engine, metrics_dict={"pixacc": "Avg accuracy :", "nll": "Avg loss :"}):
logger = logging.getLogger(__name__)
metrics = engine.state.metrics
metrics_msg = " ".join([f"{metrics_dict[k]} {metrics[k]:.2f}" for k in metrics_dict])
Expand All @@ -44,47 +41,11 @@ def log_class_metrics(log_msg, engine, metrics_dict):
logger.info(f"{log_msg} - Epoch {engine.state.epoch} [{engine.state.max_epochs}]\n" + metrics_msg)


# TODO: remove Evaluator once other train.py scripts are updated
class Evaluator:
def __init__(self, evaluation_engine, data_loader):
self._evaluation_engine = evaluation_engine
self._data_loader = data_loader

def __call__(self, engine):
self._evaluation_engine.run(self._data_loader)


class HorovodLRScheduler:
"""
Horovod: using `lr = base_lr * hvd.size()` from the very beginning leads to worse final
accuracy. Scale the learning rate `lr = base_lr` ---> `lr = base_lr * hvd.size()` during
the first five epochs. See https://arxiv.org/abs/1706.02677 for details.
After the warmup reduce learning rate by 10 on the 30th, 60th and 80th epochs.
"""

def __init__(
self, base_lr, warmup_epochs, cluster_size, data_loader, optimizer, batches_per_allreduce,
):
self._warmup_epochs = warmup_epochs
self._cluster_size = cluster_size
self._data_loader = data_loader
self._optimizer = optimizer
self._base_lr = base_lr
self._batches_per_allreduce = batches_per_allreduce
self._logger = logging.getLogger(__name__)

def __call__(self, engine):
epoch = engine.state.epoch
if epoch < self._warmup_epochs:
epoch += float(engine.state.iteration + 1) / len(self._data_loader)
lr_adj = 1.0 / self._cluster_size * (epoch * (self._cluster_size - 1) / self._warmup_epochs + 1)
elif epoch < 30:
lr_adj = 1.0
elif epoch < 60:
lr_adj = 1e-1
elif epoch < 80:
lr_adj = 1e-2
else:
lr_adj = 1e-3
for param_group in self._optimizer.param_groups:
param_group["lr"] = self._base_lr * self._cluster_size * self._batches_per_allreduce * lr_adj
self._logger.debug(f"Adjust learning rate {param_group['lr']}")
Loading