paddle.py 8.4 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
#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.
Z
zhangjinchao01 已提交
14
#!/usr/bin/python
15
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
Z
zhangjinchao01 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#
# 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.
""" module for launching cluster job """

import os
import argparse
import socket
import copy
import time
import signal

37
from fabric.api import run, put, settings, env, prefix
Z
zhangjinchao01 已提交
38 39 40 41 42
from fabric.tasks import execute

#configuration for cluster
import conf

43

Z
zhangjinchao01 已提交
44 45 46 47 48 49 50
def refine_unknown_args(cmd_args):
    '''
    refine unknown parameters to handle some special parameters
    '''
    new_args = []
    for arg in cmd_args:
        if arg.startswith("--") and arg.find("=") != -1:
51
            equal_pos = arg.find("=")  #find first = pos
Z
zhangjinchao01 已提交
52 53 54 55 56 57 58 59 60 61 62 63
            arglist = list(arg)
            arglist[equal_pos] = " "
            arg = "".join(arglist)
            arg = arg.lstrip("-")
            new_args += arg.split(" ")
        elif arg.startswith("--") and arg.find("=") == -1:
            arg = arg.lstrip("-")
            new_args.append(arg)
        else:
            new_args.append(arg)
    return new_args

64

Z
zhangjinchao01 已提交
65 66 67 68 69 70 71 72 73 74
def kill_process():
    '''
    kill comments threads
    '''
    run("ps aux \
         | grep paddle_process_by_paddle \
         | grep -v grep  \
         | awk '{print $2}' \
         | xargs kill > /dev/null 2>&1")

75

Z
zhangjinchao01 已提交
76 77 78 79
def job_prepare(jobdir, data=None):
    '''
    prepare job related workspace data

L
lipeng17 已提交
80 81
    Assuming you already installed PaddlePaddle in all nodes which means
    PaddlePaddle related bins and dependencies libraries.
Z
zhangjinchao01 已提交
82 83 84 85
    Assuming the train/test data have already been installed.
    This function just prepare all related model and other resources
    needed at runtime.
    '''
86

Z
zhangjinchao01 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    def job_create_workspace(jobdir, data=None):
        '''
        prepare job workspace, common file, etc.
        '''
        log = os.path.join(jobdir, "log")
        if data is not None:
            #create job dir
            run('rm ' + jobdir + ' -fr && ' + 'mkdir -p ' + jobdir)
            #push data and paddle bin
            put(data + "/*", jobdir)
            run("mkdir -p " + log)
        run('rm -fr ' + log + "/*")

    def set_nodefile(nodeid):
        '''
        create nodefile for later usage
        '''
        run('echo ' + str(nodeid) + ' > ' + jobdir + '/nodefile')

    execute(job_create_workspace, jobdir, data, hosts=conf.HOSTS)
    for i in xrange(len(conf.HOSTS)):
        execute(set_nodefile, i, hosts=conf.HOSTS[i])
    #clean rubbish caused by exception 
    with settings(warn_only=True):
111 112
        execute(kill_process, hosts=conf.HOSTS)

Z
zhangjinchao01 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

def job_pserver(jobdir, pids=None):
    '''
    start all pservers
    '''
    pargs = " --num_gradient_servers=" + str(len(conf.HOSTS))
    pargs += (" --nics=" + conf.PADDLE_NIC)
    pargs += " --port=" + str(conf.PADDLE_PORT)
    pargs += " --ports_num=" + str(conf.PADDLE_PORTS_NUM)
    #always start sparse pserver by default
    pargs += " --ports_num_for_sparse=" + str(conf.PADDLE_PORTS_NUM_FOR_SPARSE)
    pargs += " --comment=" + "paddle_process_by_paddle"

    def start_pserver(jobdir, pargs):
        '''
        start pserver process with fabric executor
        '''
130 131 132 133 134 135 136 137 138
        with prefix('export LD_LIBRARY_PATH=' + \
                conf.LD_LIBRARY_PATH + \
                ':$LD_LIBRARY_PATH'):
            program = 'paddle pserver'
            run('cd ' + jobdir + '; '  + \
                'GLOG_logtostderr=0 GLOG_log_dir="./log" ' + \
                'nohup ' + \
                program + " " + pargs + ' > ./log/server.log 2>&1 < /dev/null & ',
                pty=False)
Z
zhangjinchao01 已提交
139 140 141

    execute(start_pserver, jobdir, pargs, hosts=conf.HOSTS)

142 143

def job_trainer(jobdir, train_args_dict, pids=None):
Z
zhangjinchao01 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    '''
    start paddle trainer
    '''
    args = " --num_gradient_servers=" + str(len(conf.HOSTS))
    args += " --nics=" + conf.PADDLE_NIC
    args += " --port=" + str(conf.PADDLE_PORT)
    args += " --ports_num=" + str(conf.PADDLE_PORTS_NUM)
    args += " --comment=" + "paddle_process_by_paddle"
    ip_string = ""
    for i in xrange(len(conf.HOSTS)):
        host = conf.HOSTS[i]
        left = host.find("@")
        right = host.find(':')
        left = 0 if left == -1 else left + 1
        right = len(host) if right == -1 else right
        ip_string += (socket.gethostbyname(host[left:right]) + ",")
    ip_string = ip_string.rstrip(",")
    args += " --pservers=" + ip_string

    args_ext = ""
    for key, value in train_args_dict.items():
        args_ext += (' --' + key + '=' + value)
    args += " " + args_ext

    def start_trainer(jobdir, args):
        '''
        start trainer process with fabric executor
        '''
172 173 174 175 176 177 178 179 180 181
        with prefix('export LD_LIBRARY_PATH=' + \
                conf.LD_LIBRARY_PATH + \
                ':$LD_LIBRARY_PATH'):
            program = 'paddle train'
            run('cd ' + jobdir + '; '  + \
                'GLOG_logtostderr=0 '
                'GLOG_log_dir="./log" '
                'nohup ' + \
                program + " " + args + " > ./log/train.log 2>&1 < /dev/null & ",
                pty=False)
Z
zhangjinchao01 已提交
182 183 184 185 186 187

    for i in xrange(len(conf.HOSTS)):
        train_args = copy.deepcopy(args)
        train_args += " --trainer_id=" + str(i)
        execute(start_trainer, jobdir, train_args, hosts=conf.HOSTS[i])

188 189

def job_all(job_package, jobdir=None, train_args_dict=None):
Z
zhangjinchao01 已提交
190 191 192 193 194 195 196 197 198
    '''
    param job_package
    param train_args_dict
    '''
    if jobdir is None:
        timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
        jobdir = conf.ROOT_DIR + "/JOB" + timestamp
    job_prepare(jobdir, job_package)
    job_pserver(jobdir)
199
    time.sleep(5)  #wait until pservers completely start
Z
zhangjinchao01 已提交
200 201 202
    job_trainer(jobdir, train_args_dict)
    job_clean()

203

Z
zhangjinchao01 已提交
204 205 206 207 208 209
def job_clean():
    '''
    if starting job failed from paddle internal, the framework always
    is launched successfully since these process are daemon processes.
    so this job_clean can alway clean job rubbish process with ctrl+c.
    '''
210

Z
zhangjinchao01 已提交
211 212 213 214
    def signal_handler(signal, frame):
        '''
        SIGINT handler
        '''
215

Z
zhangjinchao01 已提交
216
        def kill_process():
217
            run("ps aux \
Z
zhangjinchao01 已提交
218 219 220 221
                  | grep paddle_process_by_paddle \
                  | grep -v grep  \
                  | awk '{print $2}' \
                  | xargs kill > /dev/null 2>&1")
222

Z
zhangjinchao01 已提交
223
        with settings(warn_only=True):
224
            execute(kill_process, hosts=conf.HOSTS)
Z
zhangjinchao01 已提交
225 226 227 228

    signal.signal(signal.SIGINT, signal_handler)
    signal.pause()

229

Z
zhangjinchao01 已提交
230
if __name__ == '__main__':
231 232 233 234 235 236 237 238 239 240 241 242 243 244
    parser = argparse.ArgumentParser(
        prog="paddle.py", description='simple tool for cluster training')
    parser.add_argument(
        '-j',
        '--job_workspace',
        required=False,
        default=None,
        help='job workspace')
    parser.add_argument(
        '-p',
        '--job_dispatch_package',
        required=False,
        default=None,
        help='job package for dispatching to all other nodes')
Z
zhangjinchao01 已提交
245 246 247 248 249 250 251 252 253

    args, train_args_list = parser.parse_known_args()
    train_args = refine_unknown_args(train_args_list)
    train_args_dict = dict(zip(train_args[:-1:2], train_args[1::2]))

    if args.job_workspace is not None:
        #if assigned workspace, do not need to dispatch data,
        #so job_local_package should be None
        assert args.job_dispatch_package is None
254
        job_all(None, args.job_workspace, train_args_dict)
Z
zhangjinchao01 已提交
255 256 257
    elif args.job_dispatch_package is not None:
        assert args.job_workspace is None
        assert os.path.isdir(args.job_dispatch_package)
258
        job_all(args.job_dispatch_package, None, train_args_dict)
259 260
    else:
        print "--job_workspace or --job_dispatch_package should be set"