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

T
tangwei 已提交
22

T
tangwei 已提交
23 24 25 26 27 28 29 30 31 32
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 已提交
33 34 35 36 37 38 39 40 41
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 已提交
42

X
xiexionghang 已提交
43

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

X
xiexionghang 已提交
64

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

X
xiexionghang 已提交
71

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

X
xiexionghang 已提交
84

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


X
xionghang 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
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 已提交
119 120
    """R
    """
X
xionghang 已提交
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
    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 已提交
161

X
xiexionghang 已提交
162

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

X
xiexionghang 已提交
170

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


X
xiexionghang 已提交
204
class CostPrinter(object):
X
xiexionghang 已提交
205 206 207
    """
    For count cost time && print cost log
    """
T
tangwei 已提交
208

X
xiexionghang 已提交
209
    def __init__(self, callback, callback_params):
X
xiexionghang 已提交
210 211
        """R
        """
X
xiexionghang 已提交
212 213
        self.reset(callback, callback_params)
        pass
T
tangwei 已提交
214

X
xiexionghang 已提交
215
    def __del__(self):
X
xiexionghang 已提交
216 217
        """R
        """
X
xiexionghang 已提交
218 219 220
        if not self._done:
            self.done()
        pass
T
tangwei 已提交
221

X
xiexionghang 已提交
222
    def reset(self, callback, callback_params):
X
xiexionghang 已提交
223 224
        """R
        """
X
xiexionghang 已提交
225 226 227 228 229
        self._done = False
        self._callback = callback
        self._callback_params = callback_params
        self._begin_time = time.time()
        pass
T
tangwei 已提交
230

X
xiexionghang 已提交
231
    def done(self):
X
xiexionghang 已提交
232 233
        """R
        """
X
xiexionghang 已提交
234
        cost = time.time() - self._begin_time
T
tangwei 已提交
235
        log_str = self._callback(cost, self._callback_params)  # cost(s)
X
xiexionghang 已提交
236 237 238
        self._done = True
        return cost, log_str

X
xiexionghang 已提交
239 240

class PathGenerator(object):
X
xiexionghang 已提交
241 242 243
    """
    generate path with template & runtime variables
    """
T
tangwei 已提交
244

X
xiexionghang 已提交
245
    def __init__(self, config):
X
xiexionghang 已提交
246 247
        """R
        """
T
tangwei 已提交
248
        self._templates = {}
X
xiexionghang 已提交
249 250
        self.add_path_template(config)
        pass
T
tangwei 已提交
251

X
xiexionghang 已提交
252
    def add_path_template(self, config):
X
xiexionghang 已提交
253 254
        """R
        """
X
xiexionghang 已提交
255 256 257 258 259 260
        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 已提交
261 262
        """R
        """
X
xiexionghang 已提交
263 264
        if template_name in self._templates:
            if 'time_format' in param:
T
tangwei 已提交
265 266
                str = param['time_format'].strftime(self._templates[
                    template_name])
X
xiexionghang 已提交
267 268 269 270
                return str.format(**param)
            return self._templates[template_name].format(**param)
        else:
            return ""