util.py 7.9 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
import logging
X
xionghang 已提交
20
import numpy as np
T
tangwei 已提交
21
from paddle import fluid
T
tangwei 已提交
22

23 24 25 26
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger("fluid")
logger.setLevel(logging.INFO)

T
tangwei 已提交
27

T
tangwei 已提交
28 29 30 31 32 33 34 35 36 37
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 已提交
38 39 40 41 42 43 44 45 46
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 已提交
47

X
xiexionghang 已提交
48

T
tangwei 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62
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 已提交
63
def get_env_value(env_name):
X
xiexionghang 已提交
64 65 66
    """
    get os environment value
    """
X
xiexionghang 已提交
67 68
    return os.popen("echo -n ${" + env_name + "}").read().strip()

X
xiexionghang 已提交
69

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

X
xiexionghang 已提交
76

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

X
xiexionghang 已提交
89

X
xiexionghang 已提交
90
def make_datetime(date_str, fmt=None):
X
xiexionghang 已提交
91 92 93 94 95 96 97 98
    """
    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 已提交
99
    if fmt is None:
T
tangwei 已提交
100
        if len(date_str) == 8:  # %Y%m%d
X
xiexionghang 已提交
101
            return datetime.datetime.strptime(date_str, '%Y%m%d')
T
tangwei 已提交
102
        if len(date_str) == 12:  # %Y%m%d%H%M
X
xiexionghang 已提交
103 104 105 106
            return datetime.datetime.strptime(date_str, '%Y%m%d%H%M')
    return datetime.datetime.strptime(date_str, fmt)


X
xionghang 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
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 已提交
124 125
    """R
    """
X
xionghang 已提交
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
    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:
154
            logger.info(log_str)
X
xionghang 已提交
155
    else:
156
        logger.info(log_str)
X
xionghang 已提交
157 158 159 160 161 162 163 164 165
    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 已提交
166

X
xiexionghang 已提交
167

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

X
xiexionghang 已提交
175

C
Chengmo 已提交
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
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]


209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
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


X
xiexionghang 已提交
231
class CostPrinter(object):
X
xiexionghang 已提交
232 233 234
    """
    For count cost time && print cost log
    """
T
tangwei 已提交
235

X
xiexionghang 已提交
236
    def __init__(self, callback, callback_params):
X
xiexionghang 已提交
237 238
        """R
        """
X
xiexionghang 已提交
239 240
        self.reset(callback, callback_params)
        pass
T
tangwei 已提交
241

X
xiexionghang 已提交
242
    def __del__(self):
X
xiexionghang 已提交
243 244
        """R
        """
X
xiexionghang 已提交
245 246 247
        if not self._done:
            self.done()
        pass
T
tangwei 已提交
248

X
xiexionghang 已提交
249
    def reset(self, callback, callback_params):
X
xiexionghang 已提交
250 251
        """R
        """
X
xiexionghang 已提交
252 253 254 255 256
        self._done = False
        self._callback = callback
        self._callback_params = callback_params
        self._begin_time = time.time()
        pass
T
tangwei 已提交
257

X
xiexionghang 已提交
258
    def done(self):
X
xiexionghang 已提交
259 260
        """R
        """
X
xiexionghang 已提交
261
        cost = time.time() - self._begin_time
T
tangwei 已提交
262
        log_str = self._callback(cost, self._callback_params)  # cost(s)
X
xiexionghang 已提交
263 264 265
        self._done = True
        return cost, log_str

X
xiexionghang 已提交
266 267

class PathGenerator(object):
X
xiexionghang 已提交
268 269 270
    """
    generate path with template & runtime variables
    """
T
tangwei 已提交
271

X
xiexionghang 已提交
272
    def __init__(self, config):
X
xiexionghang 已提交
273 274
        """R
        """
T
tangwei 已提交
275
        self._templates = {}
X
xiexionghang 已提交
276 277
        self.add_path_template(config)
        pass
T
tangwei 已提交
278

X
xiexionghang 已提交
279
    def add_path_template(self, config):
X
xiexionghang 已提交
280 281
        """R
        """
X
xiexionghang 已提交
282 283 284 285 286 287
        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 已提交
288 289
        """R
        """
X
xiexionghang 已提交
290 291
        if template_name in self._templates:
            if 'time_format' in param:
T
tangwei 已提交
292 293
                str = param['time_format'].strftime(self._templates[
                    template_name])
X
xiexionghang 已提交
294 295 296 297
                return str.format(**param)
            return self._templates[template_name].format(**param)
        else:
            return ""