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

22
from paddlerec.core.utils import fs as fs
T
tangwei 已提交
23 24


T
tangwei 已提交
25
def save_program_proto(path, program=None):
T
tangwei 已提交
26

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

X
xiexionghang 已提交
46

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

X
xiexionghang 已提交
67

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

X
xiexionghang 已提交
74

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

X
xiexionghang 已提交
87

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


X
xionghang 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
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 已提交
122 123
    """R
    """
X
xionghang 已提交
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
    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 已提交
164

X
xiexionghang 已提交
165

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

X
xiexionghang 已提交
173

X
xiexionghang 已提交
174
class CostPrinter(object):
X
xiexionghang 已提交
175 176 177
    """
    For count cost time && print cost log
    """
T
tangwei 已提交
178

X
xiexionghang 已提交
179
    def __init__(self, callback, callback_params):
X
xiexionghang 已提交
180 181
        """R
        """
X
xiexionghang 已提交
182 183
        self.reset(callback, callback_params)
        pass
T
tangwei 已提交
184

X
xiexionghang 已提交
185
    def __del__(self):
X
xiexionghang 已提交
186 187
        """R
        """
X
xiexionghang 已提交
188 189 190
        if not self._done:
            self.done()
        pass
T
tangwei 已提交
191

X
xiexionghang 已提交
192
    def reset(self, callback, callback_params):
X
xiexionghang 已提交
193 194
        """R
        """
X
xiexionghang 已提交
195 196 197 198 199
        self._done = False
        self._callback = callback
        self._callback_params = callback_params
        self._begin_time = time.time()
        pass
T
tangwei 已提交
200

X
xiexionghang 已提交
201
    def done(self):
X
xiexionghang 已提交
202 203
        """R
        """
X
xiexionghang 已提交
204
        cost = time.time() - self._begin_time
T
tangwei 已提交
205
        log_str = self._callback(cost, self._callback_params)  # cost(s)
X
xiexionghang 已提交
206 207 208
        self._done = True
        return cost, log_str

X
xiexionghang 已提交
209 210

class PathGenerator(object):
X
xiexionghang 已提交
211 212 213
    """
    generate path with template & runtime variables
    """
T
tangwei 已提交
214

X
xiexionghang 已提交
215
    def __init__(self, config):
X
xiexionghang 已提交
216 217
        """R
        """
T
tangwei 已提交
218
        self._templates = {}
X
xiexionghang 已提交
219 220
        self.add_path_template(config)
        pass
T
tangwei 已提交
221

X
xiexionghang 已提交
222
    def add_path_template(self, config):
X
xiexionghang 已提交
223 224
        """R
        """
X
xiexionghang 已提交
225 226 227 228 229 230
        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 已提交
231 232
        """R
        """
X
xiexionghang 已提交
233 234
        if template_name in self._templates:
            if 'time_format' in param:
T
tangwei 已提交
235 236
                str = param['time_format'].strftime(self._templates[
                    template_name])
X
xiexionghang 已提交
237 238 239 240
                return str.format(**param)
            return self._templates[template_name].format(**param)
        else:
            return ""