config.py 6.2 KB
Newer Older
W
add ad  
WuHaobo 已提交
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
W
WuHaobo 已提交
2
#
W
add ad  
WuHaobo 已提交
3 4 5
# 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
W
WuHaobo 已提交
6
#
W
add ad  
WuHaobo 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
W
WuHaobo 已提交
8
#
W
add ad  
WuHaobo 已提交
9 10 11 12 13 14
# 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.

L
littletomatodonkey 已提交
15 16 17
import os
import copy
import argparse
W
WuHaobo 已提交
18
import yaml
R
root 已提交
19 20 21
from . import logger
from . import check

W
WuHaobo 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34
__all__ = ['get_config']


class AttrDict(dict):
    def __getattr__(self, key):
        return self[key]

    def __setattr__(self, key, value):
        if key in self.__dict__:
            self.__dict__[key] = value
        else:
            self[key] = value

L
littletomatodonkey 已提交
35 36 37
    def __deepcopy__(self, content):
        return copy.deepcopy(dict(self))

W
WuHaobo 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

def create_attr_dict(yaml_config):
    from ast import literal_eval
    for key, value in yaml_config.items():
        if type(value) is dict:
            yaml_config[key] = value = AttrDict(value)
        if isinstance(value, str):
            try:
                value = literal_eval(value)
            except BaseException:
                pass
        if isinstance(value, AttrDict):
            create_attr_dict(yaml_config[key])
        else:
            yaml_config[key] = value


def parse_config(cfg_file):
    """Load a config file into AttrDict"""
    with open(cfg_file, 'r') as fopen:
W
WuHaobo 已提交
58
        yaml_config = AttrDict(yaml.load(fopen, Loader=yaml.SafeLoader))
W
WuHaobo 已提交
59 60 61 62 63 64 65 66 67
    create_attr_dict(yaml_config)
    return yaml_config


def print_dict(d, delimiter=0):
    """
    Recursively visualize a dict and
    indenting acrrording by the relationship of keys.
    """
W
WuHaobo 已提交
68
    placeholder = "-" * 60
W
WuHaobo 已提交
69
    for k, v in sorted(d.items()):
W
WuHaobo 已提交
70
        if isinstance(v, dict):
L
littletomatodonkey 已提交
71
            logger.info("{}{} : ".format(delimiter * " ", k))
W
WuHaobo 已提交
72 73
            print_dict(v, delimiter + 4)
        elif isinstance(v, list) and len(v) >= 1 and isinstance(v[0], dict):
L
littletomatodonkey 已提交
74
            logger.info("{}{} : ".format(delimiter * " ", k))
W
WuHaobo 已提交
75 76 77
            for value in v:
                print_dict(value, delimiter + 4)
        else:
L
littletomatodonkey 已提交
78
            logger.info("{}{} : {}".format(delimiter * " ", k, v))
W
WuHaobo 已提交
79 80
        if k.isupper():
            logger.info(placeholder)
W
WuHaobo 已提交
81 82


W
WuHaobo 已提交
83
def print_config(config):
W
WuHaobo 已提交
84 85 86 87 88
    """
    visualize configs
    Arguments:
        config: configs
    """
W
WuHaobo 已提交
89
    logger.advertise()
W
WuHaobo 已提交
90 91 92 93 94 95 96 97
    print_dict(config)


def check_config(config):
    """
    Check config
    """
    check.check_version()
littletomatodonkey's avatar
littletomatodonkey 已提交
98 99 100
    use_gpu = config.get('use_gpu', True)
    if use_gpu:
        check.check_gpu()
littletomatodonkey's avatar
littletomatodonkey 已提交
101
    architecture = config.get('ARCHITECTURE')
L
littletomatodonkey 已提交
102
    #check.check_architecture(architecture)
W
WuHaobo 已提交
103
    use_mix = config.get('use_mix', False)
W
WuHaobo 已提交
104 105 106
    check.check_mix(architecture, use_mix)
    classes_num = config.get('classes_num')
    check.check_classes_num(classes_num)
littletomatodonkey's avatar
littletomatodonkey 已提交
107
    mode = config.get('mode', 'train')
W
WuHaobo 已提交
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
    if mode.lower() == 'train':
        check.check_function_params(config, 'LEARNING_RATE')
        check.check_function_params(config, 'OPTIMIZER')


def override(dl, ks, v):
    """
    Recursively replace dict of list
    Args:
        dl(dict or list): dict or list to be replaced
        ks(list): list of keys
        v(str): value to be replaced
    """

    def str2num(v):
        try:
            return eval(v)
        except Exception:
            return v

    assert isinstance(dl, (list, dict)), ("{} should be a list or a dict")
    assert len(ks) > 0, ('lenght of keys should larger than 0')
    if isinstance(dl, list):
        k = str2num(ks[0])
        if len(ks) == 1:
            assert k < len(dl), ('index({}) out of range({})'.format(k, dl))
            dl[k] = str2num(v)
        else:
            override(dl[k], ks[1:], v)
    else:
        if len(ks) == 1:
littletomatodonkey's avatar
littletomatodonkey 已提交
139 140
            # assert ks[0] in dl, ('{} is not exist in {}'.format(ks[0], dl))
            if not ks[0] in dl:
D
dongshuilong 已提交
141
                print('A new field ({}) detected!'.format(ks[0], dl))
W
WuHaobo 已提交
142 143
            dl[ks[0]] = str2num(v)
        else:
D
dongshuilong 已提交
144 145
            if ks[0] not in dl.keys():
                dl[ks[0]] = {}
D
dongshuilong 已提交
146
                print("A new Series field ({}) detected!".format(ks[0], dl))
W
WuHaobo 已提交
147 148 149
            override(dl[ks[0]], ks[1:], v)


W
WuHaobo 已提交
150
def override_config(config, options=None):
W
WuHaobo 已提交
151 152 153 154 155 156 157 158 159 160 161 162
    """
    Recursively override the config
    Args:
        config(dict): dict to be replaced
        options(list): list of pairs(key0.key1.idx.key2=value)
            such as: [
                'topk=2',
                'VALID.transforms.1.ResizeImage.resize_short=300'
            ]
    Returns:
        config(dict): replaced config
    """
W
WuHaobo 已提交
163 164 165 166 167 168 169 170 171 172 173 174
    if options is not None:
        for opt in options:
            assert isinstance(opt, str), (
                "option({}) should be a str".format(opt))
            assert "=" in opt, (
                "option({}) should contain a ="
                "to distinguish between key and value".format(opt))
            pair = opt.split('=')
            assert len(pair) == 2, ("there can be only a = in the option")
            key, value = pair
            keys = key.split('.')
            override(config, keys, value)
W
WuHaobo 已提交
175 176 177
    return config


L
littletomatodonkey 已提交
178
def get_config(fname, overrides=None, show=False):
W
WuHaobo 已提交
179 180 181
    """
    Read config from file
    """
W
WuHaobo 已提交
182 183
    assert os.path.exists(fname), (
        'config file({}) is not exist'.format(fname))
W
WuHaobo 已提交
184
    config = parse_config(fname)
W
WuHaobo 已提交
185 186 187
    override_config(config, overrides)
    if show:
        print_config(config)
L
littletomatodonkey 已提交
188
    # check_config(config)
W
WuHaobo 已提交
189
    return config
L
littletomatodonkey 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205


def parse_args():
    parser = argparse.ArgumentParser("generic-image-rec train script")
    parser.add_argument(
        '-c',
        '--config',
        type=str,
        default='configs/config.yaml',
        help='config file path')
    parser.add_argument(
        '-o',
        '--override',
        action='append',
        default=[],
        help='config options to be overridden')
D
dongshuilong 已提交
206 207 208 209 210 211 212
    parser.add_argument(
        '-p',
        '--profiler_options',
        type=str,
        default=None,
        help='The option of profiler, which should be in format \"key1=value1;key2=value2;key3=value3\".'
    )
L
littletomatodonkey 已提交
213 214
    args = parser.parse_args()
    return args