-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathconfig.py
237 lines (193 loc) · 8.08 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import six
import codecs
import os
from ast import literal_eval
from typing import Any, Dict, Optional
import yaml
import paddle
from paddleseg.cvlibs import config_checker as checker
from paddleseg.cvlibs import manager
from paddleseg.utils import logger, utils
_INHERIT_KEY = '_inherited_'
_BASE_KEY = '_base_'
class Config(object):
"""
Configuration parsing.
The following hyper-parameters are available in the config file:
batch_size: The number of samples per gpu.
iters: The total training steps.
train_dataset: A training data config including type/data_root/transforms/mode.
For data type, please refer to paddleseg.datasets.
For specific transforms, please refer to paddleseg.transforms.transforms.
val_dataset: A validation data config including type/data_root/transforms/mode.
optimizer: A optimizer config. Please refer to paddleseg.optimizers.
loss: A loss config. Multi-loss config is available. The loss type order is
consistent with the seg model outputs, where the coef term indicates the
weight of corresponding loss. Note that the number of coef must be the
same as the number of model outputs, and there could be only one loss type
if using the same loss type among the outputs, otherwise the number of
loss type must be consistent with coef.
model: A model config including type/backbone and model-dependent arguments.
For model type, please refer to paddleseg.models.
For backbone, please refer to paddleseg.models.backbones.
Args:
path (str) : The path of config file, supports yaml format only.
opts (list, optional): Use opts to update the key-value pairs of all options.
"""
def __init__(self,
path: str,
learning_rate: Optional[float]=None,
batch_size: Optional[int]=None,
iters: Optional[int]=None,
to_static_training: Optional[bool]=None,
opts: Optional[list]=None,
checker: Optional[checker.ConfigChecker]=None):
assert os.path.exists(path), \
'Config path ({}) does not exist'.format(path)
assert path.endswith('yml') or path.endswith('yaml'), \
'Config file ({}) should be yaml format'.format(path)
self.dic = self._parse_from_yaml(path)
self.dic = self.update_config_dict(
self.dic,
learning_rate=learning_rate,
batch_size=batch_size,
iters=iters,
to_static_training=to_static_training,
opts=opts)
if checker is None:
checker = self._build_default_checker()
checker.apply_all_rules(self)
@property
def batch_size(self) -> int:
return self.dic.get('batch_size')
@property
def iters(self) -> int:
return self.dic.get('iters')
@property
def to_static_training(self) -> bool:
return self.dic.get('to_static_training', False)
@property
def model_cfg(self) -> Dict:
return self.dic.get('model', {}).copy()
@property
def loss_cfg(self) -> Dict:
return self.dic.get('loss', {}).copy()
@property
def distill_loss_cfg(self) -> Dict:
return self.dic.get('distill_loss', {}).copy()
@property
def lr_scheduler_cfg(self) -> Dict:
return self.dic.get('lr_scheduler', {}).copy()
@property
def optimizer_cfg(self) -> Dict:
return self.dic.get('optimizer', {}).copy()
@property
def train_dataset_cfg(self) -> Dict:
return self.dic.get('train_dataset', {}).copy()
@property
def val_dataset_cfg(self) -> Dict:
return self.dic.get('val_dataset', {}).copy()
# TODO merge test_config into val_dataset
@property
def test_config(self) -> Dict:
return self.dic.get('test_config', {}).copy()
@classmethod
def update_config_dict(cls, dic: dict, *args, **kwargs) -> dict:
return update_config_dict(dic, *args, **kwargs)
@classmethod
def _parse_from_yaml(cls, path: str, *args, **kwargs) -> dict:
return parse_from_yaml(path, *args, **kwargs)
@classmethod
def _build_default_checker(cls):
rules = []
rules.append(checker.DefaultPrimaryRule())
rules.append(checker.DefaultSyncNumClassesRule())
rules.append(checker.DefaultSyncImgChannelsRule())
# Losses
rules.append(checker.DefaultLossRule('loss'))
rules.append(checker.DefaultSyncIgnoreIndexRule('loss'))
# Distillation losses
rules.append(checker.DefaultLossRule('distill_loss'))
rules.append(checker.DefaultSyncIgnoreIndexRule('distill_loss'))
return checker.ConfigChecker(rules, allow_update=True)
def __str__(self) -> str:
# Use NoAliasDumper to avoid yml anchor
return yaml.dump(self.dic, Dumper=utils.NoAliasDumper)
def parse_from_yaml(path: str):
"""Parse a yaml file and build config"""
with codecs.open(path, 'r', 'utf-8') as file:
dic = yaml.load(file, Loader=yaml.FullLoader)
if _BASE_KEY in dic:
base_files = dic.pop(_BASE_KEY)
if isinstance(base_files, str):
base_files = [base_files]
for bf in base_files:
base_path = os.path.join(os.path.dirname(path), bf)
base_dic = parse_from_yaml(base_path)
dic = merge_config_dicts(dic, base_dic)
return dic
def merge_config_dicts(dic, base_dic):
"""Merge dic to base_dic and return base_dic."""
base_dic = base_dic.copy()
dic = dic.copy()
if not dic.get(_INHERIT_KEY, True):
dic.pop(_INHERIT_KEY)
return dic
for key, val in dic.items():
if isinstance(val, dict) and key in base_dic:
base_dic[key] = merge_config_dicts(val, base_dic[key])
else:
base_dic[key] = val
return base_dic
def update_config_dict(dic: dict,
learning_rate: Optional[float]=None,
batch_size: Optional[int]=None,
iters: Optional[int]=None,
to_static_training: Optional[bool]=None,
opts: Optional[list]=None):
"""Update config"""
# TODO: If the items to update are marked as anchors in the yaml file,
# we should synchronize the references.
dic = dic.copy()
if learning_rate:
dic['lr_scheduler']['learning_rate'] = learning_rate
if batch_size:
dic['batch_size'] = batch_size
if iters:
dic['iters'] = iters
if to_static_training:
dic['to_static_training'] = to_static_training
if opts is not None:
for item in opts:
assert ('=' in item) and (len(item.split('=')) == 2), "--opts params should be key=value," \
" such as `--opts batch_size=1 test_config.scales=0.75,1.0,1.25`, " \
"but got ({})".format(opts)
key, value = item.split('=')
if isinstance(value, six.string_types):
try:
value = literal_eval(value)
except ValueError:
pass
except SyntaxError:
pass
key_list = key.split('.')
tmp_dic = dic
for subkey in key_list[:-1]:
assert subkey in tmp_dic, "Can not update {}, because it is not in config.".format(
key)
tmp_dic = tmp_dic[subkey]
tmp_dic[key_list[-1]] = value
return dic