paddle.py 7.9 KB
Newer Older
Z
zhangjinchao01 已提交
1
#!/usr/bin/python
2
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
Z
zhangjinchao01 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# 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

24
from fabric.api import run, put, settings, env, prefix
Z
zhangjinchao01 已提交
25 26 27 28 29
from fabric.tasks import execute

#configuration for cluster
import conf

30

Z
zhangjinchao01 已提交
31 32 33 34 35 36 37
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:
38
            equal_pos = arg.find("=")  #find first = pos
Z
zhangjinchao01 已提交
39 40 41 42 43 44 45 46 47 48 49 50
            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

51

Z
zhangjinchao01 已提交
52 53 54 55 56 57 58 59 60 61
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")

62

Z
zhangjinchao01 已提交
63 64 65 66
def job_prepare(jobdir, data=None):
    '''
    prepare job related workspace data

L
lipeng17 已提交
67 68
    Assuming you already installed PaddlePaddle in all nodes which means
    PaddlePaddle related bins and dependencies libraries.
Z
zhangjinchao01 已提交
69 70 71 72
    Assuming the train/test data have already been installed.
    This function just prepare all related model and other resources
    needed at runtime.
    '''
73

Z
zhangjinchao01 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    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):
98 99
        execute(kill_process, hosts=conf.HOSTS)

Z
zhangjinchao01 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

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
        '''
117 118 119 120 121 122 123 124 125
        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 已提交
126 127 128

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

129 130

def job_trainer(jobdir, train_args_dict, pids=None):
Z
zhangjinchao01 已提交
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
    '''
    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
        '''
159 160 161 162 163 164 165 166 167 168
        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 已提交
169 170 171 172 173 174

    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])

175 176

def job_all(job_package, jobdir=None, train_args_dict=None):
Z
zhangjinchao01 已提交
177 178 179 180 181 182 183 184 185
    '''
    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)
186
    time.sleep(5)  #wait until pservers completely start
Z
zhangjinchao01 已提交
187 188 189
    job_trainer(jobdir, train_args_dict)
    job_clean()

190

Z
zhangjinchao01 已提交
191 192 193 194 195 196
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.
    '''
197

Z
zhangjinchao01 已提交
198 199 200 201
    def signal_handler(signal, frame):
        '''
        SIGINT handler
        '''
202

Z
zhangjinchao01 已提交
203
        def kill_process():
204
            run("ps aux \
Z
zhangjinchao01 已提交
205 206 207 208
                  | grep paddle_process_by_paddle \
                  | grep -v grep  \
                  | awk '{print $2}' \
                  | xargs kill > /dev/null 2>&1")
209

Z
zhangjinchao01 已提交
210
        with settings(warn_only=True):
211
            execute(kill_process, hosts=conf.HOSTS)
Z
zhangjinchao01 已提交
212 213 214 215

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

216

Z
zhangjinchao01 已提交
217
if __name__ == '__main__':
218 219 220 221 222 223 224 225 226 227 228 229 230 231
    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 已提交
232 233 234 235 236 237 238 239 240

    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
241
        job_all(None, args.job_workspace, train_args_dict)
Z
zhangjinchao01 已提交
242 243 244
    elif args.job_dispatch_package is not None:
        assert args.job_workspace is None
        assert os.path.isdir(args.job_dispatch_package)
245
        job_all(args.job_dispatch_package, None, train_args_dict)
246 247
    else:
        print "--job_workspace or --job_dispatch_package should be set"