util.py 8.1 KB
Newer Older
T
tangwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

T
tangwei 已提交
15
import datetime
X
xiexionghang 已提交
16
import os
X
xionghang 已提交
17
import sys
X
xiexionghang 已提交
18
import time
19 20
import warnings
import random
X
xionghang 已提交
21
import numpy as np
T
tangwei 已提交
22
from paddle import fluid
T
tangwei 已提交
23

T
tangwei 已提交
24

T
tangwei 已提交
25 26 27 28 29 30 31 32 33 34
def save_program_proto(path, program=None):
    if program is None:
        _program = fluid.default_main_program()
    else:
        _program = program

    with open(path, "wb") as f:
        f.write(_program.desc.serialize_to_string())


T
tangwei 已提交
35 36 37 38 39 40 41 42 43
def str2bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise ValueError('Boolean value expected.')
T
tangwei 已提交
44

X
xiexionghang 已提交
45

T
tangwei 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59
def run_which(command):
    regex = "/usr/bin/which: no {} in"
    ret = run_shell_cmd("which {}".format(command))
    if ret.startswith(regex.format(command)):
        return None
    else:
        return ret


def run_shell_cmd(command):
    assert command is not None and isinstance(command, str)
    return os.popen(command).read().strip()


X
xiexionghang 已提交
60
def get_env_value(env_name):
X
xiexionghang 已提交
61 62 63
    """
    get os environment value
    """
X
xiexionghang 已提交
64 65
    return os.popen("echo -n ${" + env_name + "}").read().strip()

X
xiexionghang 已提交
66

X
xiexionghang 已提交
67
def now_time_str():
X
xiexionghang 已提交
68 69 70 71
    """
    get current format str_time
    """
    return "\n" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "[0]:"
X
xiexionghang 已提交
72

X
xiexionghang 已提交
73

X
xiexionghang 已提交
74
def get_absolute_path(path, params):
X
xiexionghang 已提交
75 76
    """R
    """
X
xiexionghang 已提交
77 78
    if path.startswith('afs:') or path.startswith('hdfs:'):
        sub_path = path.split('fs:')[1]
T
tangwei 已提交
79
        if ':' in sub_path:  # such as afs://xxx:prot/xxxx
X
xiexionghang 已提交
80 81 82 83 84 85
            return path
        elif 'fs_name' in params:
            return params['fs_name'] + sub_path
    else:
        return path

X
xiexionghang 已提交
86

X
xiexionghang 已提交
87
def make_datetime(date_str, fmt=None):
X
xiexionghang 已提交
88 89 90 91 92 93 94 95
    """
    create a datetime instance by date_string
    Args:
        date_str: such as 2020-01-14
        date_str_format: "%Y-%m-%d"
    Return:
        datetime 
    """
X
xiexionghang 已提交
96
    if fmt is None:
T
tangwei 已提交
97
        if len(date_str) == 8:  # %Y%m%d
X
xiexionghang 已提交
98
            return datetime.datetime.strptime(date_str, '%Y%m%d')
T
tangwei 已提交
99
        if len(date_str) == 12:  # %Y%m%d%H%M
X
xiexionghang 已提交
100 101 102 103
            return datetime.datetime.strptime(date_str, '%Y%m%d%H%M')
    return datetime.datetime.strptime(date_str, fmt)


X
xionghang 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
def wroker_numric_opt(fleet, value, env, opt):
    """
    numric count opt for workers
    Args:
        value: value for count
        env: mpi/gloo
        opt: count operator, SUM/MAX/MIN/AVG
    Return:
        count result
    """
    local_value = np.array([value])
    global_value = np.copy(local_value) * 0
    fleet._role_maker.all_reduce_worker(local_value, global_value, opt)
    return global_value[0]


def worker_numric_sum(fleet, value, env="mpi"):
X
xiexionghang 已提交
121 122
    """R
    """
X
xionghang 已提交
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
    return wroker_numric_opt(fleet, value, env, "sum")


def worker_numric_avg(fleet, value, env="mpi"):
    """R
    """
    return worker_numric_sum(fleet, value, env) / fleet.worker_num()


def worker_numric_min(fleet, value, env="mpi"):
    """R
    """
    return wroker_numric_opt(fleet, value, env, "min")


def worker_numric_max(fleet, value, env="mpi"):
    """R
    """
    return wroker_numric_opt(fleet, value, env, "max")


def print_log(log_str, params):
    """R
    """
    time_str = time.strftime("[%Y-%m-%d %H:%M:%S]", time.localtime())
    log_str = time_str + " " + log_str
    if 'master' in params and params['master']:
        if 'index' in params and params['index'] == 0:
            print(log_str)
    else:
        print(log_str)
    sys.stdout.flush()
    if 'stdout' in params:
        params['stdout'] += log_str + '\n'


def rank0_print(log_str, fleet):
    """R
    """
    print_log(log_str, {'master': True, 'index': fleet.worker_index()})
X
xiexionghang 已提交
163

X
xiexionghang 已提交
164

X
xiexionghang 已提交
165
def print_cost(cost, params):
X
xiexionghang 已提交
166 167
    """R
    """
X
xiexionghang 已提交
168
    log_str = params['log_format'] % cost
T
tangwei 已提交
169
    print_log(log_str, params)
X
xiexionghang 已提交
170
    return log_str
T
tangwei 已提交
171

X
xiexionghang 已提交
172

C
Chengmo 已提交
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
def split_files(files, trainer_id, trainers):
    """
    split files before distributed training,
    example 1: files is [a, b, c ,d, e]  and trainer_num = 2, then trainer
               0 gets [a, b, c] and trainer 1 gets [d, e].
    example 2: files is [a, b], and trainer_num = 3, then trainer 0 gets
               [a], trainer 1 gets [b],  trainer 2 gets []

    Args:
        files(list): file list need to be read.

    Returns:
        list: files belongs to this worker.
    """
    if not isinstance(files, list):
        raise TypeError("files should be a list of file need to be read.")

    remainder = len(files) % trainers
    blocksize = int(len(files) / trainers)

    blocks = [blocksize] * trainers
    for i in range(remainder):
        blocks[i] += 1

    trainer_files = [[]] * trainers
    begin = 0
    for i in range(trainers):
        trainer_files[i] = files[begin:begin + blocks[i]]
        begin += blocks[i]

    return trainer_files[trainer_id]


206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
def check_filelist(hidden_file_list, data_file_list, train_data_path):
    for root, dirs, files in os.walk(train_data_path):
        if (files == None and dirs == None):
            return None, None
        else:
            # use files and dirs
            for file_name in files:
                file_path = os.path.join(train_data_path, file_name)
                if file_name[0] == '.':
                    hidden_file_list.append(file_path)
                else:
                    data_file_list.append(file_path)
            for dirs_name in dirs:
                dirs_path = os.path.join(train_data_path, dirs_name)
                if dirs_name[0] == '.':
                    hidden_file_list.append(dirs_path)
                else:
                    #train_data_path = os.path.join(train_data_path, dirs_name)
                    check_filelist(hidden_file_list, data_file_list, dirs_path)
            return hidden_file_list, data_file_list


228 229 230 231 232 233 234 235 236 237
def shuffle_files(need_shuffle_files, filelist):
    if not isinstance(need_shuffle_files, bool):
        raise ValueError(
            "In your config yaml, 'shuffle_filelist': %s must be written as a boolean type,such as True or False"
            % need_shuffle_files)
    elif need_shuffle_files:
        random.shuffle(filelist)
    return filelist


X
xiexionghang 已提交
238
class CostPrinter(object):
X
xiexionghang 已提交
239 240 241
    """
    For count cost time && print cost log
    """
T
tangwei 已提交
242

X
xiexionghang 已提交
243
    def __init__(self, callback, callback_params):
X
xiexionghang 已提交
244 245
        """R
        """
X
xiexionghang 已提交
246 247
        self.reset(callback, callback_params)
        pass
T
tangwei 已提交
248

X
xiexionghang 已提交
249
    def __del__(self):
X
xiexionghang 已提交
250 251
        """R
        """
X
xiexionghang 已提交
252 253 254
        if not self._done:
            self.done()
        pass
T
tangwei 已提交
255

X
xiexionghang 已提交
256
    def reset(self, callback, callback_params):
X
xiexionghang 已提交
257 258
        """R
        """
X
xiexionghang 已提交
259 260 261 262 263
        self._done = False
        self._callback = callback
        self._callback_params = callback_params
        self._begin_time = time.time()
        pass
T
tangwei 已提交
264

X
xiexionghang 已提交
265
    def done(self):
X
xiexionghang 已提交
266 267
        """R
        """
X
xiexionghang 已提交
268
        cost = time.time() - self._begin_time
T
tangwei 已提交
269
        log_str = self._callback(cost, self._callback_params)  # cost(s)
X
xiexionghang 已提交
270 271 272
        self._done = True
        return cost, log_str

X
xiexionghang 已提交
273 274

class PathGenerator(object):
X
xiexionghang 已提交
275 276 277
    """
    generate path with template & runtime variables
    """
T
tangwei 已提交
278

X
xiexionghang 已提交
279
    def __init__(self, config):
X
xiexionghang 已提交
280 281
        """R
        """
T
tangwei 已提交
282
        self._templates = {}
X
xiexionghang 已提交
283 284
        self.add_path_template(config)
        pass
T
tangwei 已提交
285

X
xiexionghang 已提交
286
    def add_path_template(self, config):
X
xiexionghang 已提交
287 288
        """R
        """
X
xiexionghang 已提交
289 290 291 292 293 294
        if 'templates' in config:
            for template in config['templates']:
                self._templates[template['name']] = template['template']
        pass

    def generate_path(self, template_name, param):
X
xiexionghang 已提交
295 296
        """R
        """
X
xiexionghang 已提交
297 298
        if template_name in self._templates:
            if 'time_format' in param:
T
tangwei 已提交
299 300
                str = param['time_format'].strftime(self._templates[
                    template_name])
X
xiexionghang 已提交
301 302 303 304
                return str.format(**param)
            return self._templates[template_name].format(**param)
        else:
            return ""