run.py 9.5 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 16
import argparse
import os
T
tangwei 已提交
17
import subprocess
T
tangwei 已提交
18 19
import tempfile

T
tangwei 已提交
20
import yaml
T
tangwei 已提交
21

22 23 24
from paddlerec.core.factory import TrainerFactory
from paddlerec.core.utils import envs
from paddlerec.core.utils import util
T
tangwei 已提交
25

T
tangwei 已提交
26 27
engines = {}
device = ["CPU", "GPU"]
T
tangwei 已提交
28
clusters = ["SINGLE", "LOCAL_CLUSTER", "CLUSTER"]
C
chengmo 已提交
29
custom_model = ['tdm']
C
fix  
chengmo 已提交
30
model_name = ""
T
tangwei 已提交
31 32


T
tangwei 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
def engine_registry():
    cpu = {"TRANSPILER": {}, "PSLIB": {}}
    cpu["TRANSPILER"]["SINGLE"] = single_engine
    cpu["TRANSPILER"]["LOCAL_CLUSTER"] = local_cluster_engine
    cpu["TRANSPILER"]["CLUSTER"] = cluster_engine
    cpu["PSLIB"]["SINGLE"] = local_mpi_engine
    cpu["PSLIB"]["LOCAL_CLUSTER"] = local_mpi_engine
    cpu["PSLIB"]["CLUSTER"] = cluster_mpi_engine

    gpu = {"TRANSPILER": {}, "PSLIB": {}}
    gpu["TRANSPILER"]["SINGLE"] = single_engine

    engines["CPU"] = cpu
    engines["GPU"] = gpu


C
chengmo 已提交
49 50
def get_engine(args):
    device = args.device
T
tangwei 已提交
51 52
    d_engine = engines[device]
    transpiler = get_transpiler()
C
chengmo 已提交
53

C
fix  
chengmo 已提交
54
    engine = args.engine
T
tangwei 已提交
55 56 57
    run_engine = d_engine[transpiler].get(engine, None)

    if run_engine is None:
C
chengmo 已提交
58 59
        raise ValueError(
            "engine {} can not be supported on device: {}".format(engine, device))
T
tangwei 已提交
60 61 62 63
    return run_engine


def get_transpiler():
T
tangwei 已提交
64 65 66 67 68 69
    FNULL = open(os.devnull, 'w')
    cmd = ["python", "-c",
           "import paddle.fluid as fluid; fleet_ptr = fluid.core.Fleet(); [fleet_ptr.copy_table_by_feasign(10, 10, [2020, 1010])];"]
    proc = subprocess.Popen(cmd, stdout=FNULL, stderr=FNULL, cwd=os.getcwd())
    ret = proc.wait()
    if ret == -11:
T
tangwei 已提交
70
        return "PSLIB"
T
tangwei 已提交
71
    else:
T
tangwei 已提交
72
        return "TRANSPILER"
T
tangwei 已提交
73 74


T
tangwei 已提交
75
def set_runtime_envs(cluster_envs, engine_yaml):
T
tangwei 已提交
76
    def get_engine_extras():
T
tangwei 已提交
77 78
        with open(engine_yaml, 'r') as rb:
            _envs = yaml.load(rb.read(), Loader=yaml.FullLoader)
T
tangwei 已提交
79 80 81 82 83 84 85 86

        flattens = envs.flatten_environs(_envs)

        engine_extras = {}
        for k, v in flattens.items():
            if k.startswith("train.trainer."):
                engine_extras[k] = v
        return engine_extras
T
tangwei 已提交
87 88 89

    if cluster_envs is None:
        cluster_envs = {}
T
tangwei 已提交
90

91 92 93
    engine_extras = get_engine_extras()
    if "train.trainer.threads" in engine_extras and "CPU_NUM" in cluster_envs:
        cluster_envs["CPU_NUM"] = engine_extras["train.trainer.threads"]
T
tangwei 已提交
94
    envs.set_runtime_environs(cluster_envs)
95
    envs.set_runtime_environs(engine_extras)
T
fix bug  
tangwei 已提交
96 97 98

    need_print = {}
    for k, v in os.environ.items():
T
tangwei 已提交
99
        if k.startswith("train.trainer."):
T
fix bug  
tangwei 已提交
100 101 102
            need_print[k] = v

    print(envs.pretty_print_envs(need_print, ("Runtime Envs", "Value")))
T
tangwei 已提交
103 104


C
chengmo 已提交
105 106 107 108
def get_trainer_prefix(args):
    if model_name in custom_model:
        return model_name.upper()
    return ""
T
tangwei 已提交
109

C
chengmo 已提交
110

C
chengmo 已提交
111 112
def single_engine(args):
    trainer = get_trainer_prefix(args) + "SingleTrainer"
C
chengmo 已提交
113
    single_envs = {}
C
chengmo 已提交
114
    single_envs["train.trainer.trainer"] = trainer
C
chengmo 已提交
115 116 117 118
    single_envs["train.trainer.threads"] = "2"
    single_envs["train.trainer.engine"] = "single"
    single_envs["train.trainer.device"] = args.device
    single_envs["train.trainer.platform"] = envs.get_platform()
C
chengmo 已提交
119
    print("use {} engine to run model: {}".format(trainer, args.model))
C
chengmo 已提交
120 121 122 123 124 125

    set_runtime_envs(single_envs, args.model)
    trainer = TrainerFactory.create(args.model)
    return trainer


T
tangwei 已提交
126
def cluster_engine(args):
C
chengmo 已提交
127

T
tangwei 已提交
128 129 130 131 132 133
    def update_workspace(cluster_envs):
        workspace = cluster_envs.get("engine_workspace", None)
        if not workspace:
            return

        # is fleet inner models
134
        if workspace.startswith("paddlerec."):
T
tangwei 已提交
135
            fleet_package = envs.get_runtime_environ("PACKAGE_BASE")
136
            workspace_dir = workspace.split("paddlerec.")[1].replace(".", "/")
T
tangwei 已提交
137 138 139 140 141 142 143 144 145 146
            path = os.path.join(fleet_package, workspace_dir)
        else:
            path = workspace

        for name, value in cluster_envs.items():
            if isinstance(value, str):
                value = value.replace("{workspace}", path)
                cluster_envs[name] = value

    def master():
147
        from paddlerec.core.engine.cluster.cluster import ClusterEngine
T
tangwei 已提交
148 149 150 151 152
        with open(args.backend, 'r') as rb:
            _envs = yaml.load(rb.read(), Loader=yaml.FullLoader)

        flattens = envs.flatten_environs(_envs, "_")
        flattens["engine_role"] = args.role
T
tangwei 已提交
153
        flattens["engine_run_config"] = args.model
T
tangwei 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167
        flattens["engine_temp_path"] = tempfile.mkdtemp()
        update_workspace(flattens)

        envs.set_runtime_environs(flattens)
        print(envs.pretty_print_envs(flattens, ("Submit Runtime Envs", "Value")))

        launch = ClusterEngine(None, args.model)
        return launch

    def worker():
        trainer = get_trainer_prefix(args) + "ClusterTrainer"
        cluster_envs = {}
        cluster_envs["train.trainer.trainer"] = trainer
        cluster_envs["train.trainer.engine"] = "cluster"
T
tangwei 已提交
168
        cluster_envs["train.trainer.threads"] = envs.get_runtime_environ("CPU_NUM")
T
tangwei 已提交
169 170
        cluster_envs["train.trainer.device"] = args.device
        cluster_envs["train.trainer.platform"] = envs.get_platform()
C
chengmo 已提交
171 172
        print("launch {} engine with cluster to with model: {}".format(
            trainer, args.model))
T
tangwei 已提交
173
        set_runtime_envs(cluster_envs, args.model)
T
tangwei 已提交
174

T
bug fix  
tangwei12 已提交
175 176
        trainer = TrainerFactory.create(args.model)
        return trainer
T
tangwei 已提交
177

T
bug fix  
tangwei12 已提交
178
    if args.role == "WORKER":
T
tangwei 已提交
179 180 181
        return worker()
    else:
        return master()
C
chengmo 已提交
182 183


T
tangwei 已提交
184
def cluster_mpi_engine(args):
T
tangwei 已提交
185 186
    print("launch cluster engine with cluster to run model: {}".format(args.model))

T
fix bug  
tangwei 已提交
187
    cluster_envs = {}
T
tangwei 已提交
188
    cluster_envs["train.trainer.trainer"] = "CtrCodingTrainer"
T
tangwei 已提交
189
    cluster_envs["train.trainer.device"] = args.device
T
tangwei 已提交
190
    cluster_envs["train.trainer.platform"] = envs.get_platform()
T
tangwei 已提交
191

T
tangwei 已提交
192
    set_runtime_envs(cluster_envs, args.model)
T
tangwei 已提交
193

T
tangwei 已提交
194 195 196 197 198
    trainer = TrainerFactory.create(args.model)
    return trainer


def local_cluster_engine(args):
199
    from paddlerec.core.engine.local_cluster import LocalClusterEngine
C
chengmo 已提交
200

C
chengmo 已提交
201
    trainer = get_trainer_prefix(args) + "ClusterTrainer"
C
chengmo 已提交
202 203 204
    cluster_envs = {}
    cluster_envs["server_num"] = 1
    cluster_envs["worker_num"] = 1
C
chengmo 已提交
205
    cluster_envs["start_port"] = envs.find_free_port()
C
chengmo 已提交
206
    cluster_envs["log_dir"] = "logs"
C
chengmo 已提交
207
    cluster_envs["train.trainer.trainer"] = trainer
C
chengmo 已提交
208 209 210 211 212 213 214 215
    cluster_envs["train.trainer.strategy"] = "async"
    cluster_envs["train.trainer.threads"] = "2"
    cluster_envs["train.trainer.engine"] = "local_cluster"

    cluster_envs["train.trainer.device"] = args.device
    cluster_envs["train.trainer.platform"] = envs.get_platform()

    cluster_envs["CPU_NUM"] = "2"
C
chengmo 已提交
216
    print("launch {} engine with cluster to run model: {}".format(trainer, args.model))
C
chengmo 已提交
217 218 219 220 221 222

    set_runtime_envs(cluster_envs, args.model)
    launch = LocalClusterEngine(cluster_envs, args.model)
    return launch


T
tangwei 已提交
223
def local_mpi_engine(args):
T
tangwei 已提交
224
    print("launch cluster engine with cluster to run model: {}".format(args.model))
225
    from paddlerec.core.engine.local_mpi import LocalMPIEngine
T
tangwei 已提交
226

T
tangwei 已提交
227
    print("use 1X1 MPI ClusterTraining at localhost to run model: {}".format(args.model))
T
tangwei 已提交
228

T
tangwei 已提交
229 230 231
    mpi = util.run_which("mpirun")
    if not mpi:
        raise RuntimeError("can not find mpirun, please check environment")
T
fix bug  
tangwei 已提交
232 233
    cluster_envs = {}
    cluster_envs["mpirun"] = mpi
T
tangwei 已提交
234
    cluster_envs["train.trainer.trainer"] = "CtrCodingTrainer"
T
fix bug  
tangwei 已提交
235
    cluster_envs["log_dir"] = "logs"
T
tangwei 已提交
236
    cluster_envs["train.trainer.engine"] = "local_cluster"
T
tangwei 已提交
237

T
tangwei 已提交
238
    cluster_envs["train.trainer.device"] = args.device
T
tangwei 已提交
239
    cluster_envs["train.trainer.platform"] = envs.get_platform()
T
tangwei 已提交
240

T
tangwei 已提交
241
    set_runtime_envs(cluster_envs, args.model)
T
tangwei 已提交
242 243 244 245
    launch = LocalMPIEngine(cluster_envs, args.model)
    return launch


T
tangwei 已提交
246
def get_abs_model(model):
247
    if model.startswith("paddlerec."):
T
tangwei 已提交
248
        fleet_base = envs.get_runtime_environ("PACKAGE_BASE")
249
        workspace_dir = model.split("paddlerec.")[1].replace(".", "/")
T
tangwei 已提交
250 251 252 253 254 255 256 257
        path = os.path.join(fleet_base, workspace_dir, "config.yaml")
    else:
        if not os.path.isfile(model):
            raise IOError("model config: {} invalid".format(model))
        path = model
    return path


T
tangwei 已提交
258
if __name__ == "__main__":
259
    parser = argparse.ArgumentParser(description='paddle-rec run')
T
tangwei 已提交
260
    parser.add_argument("-m", "--model", type=str)
C
chengmo 已提交
261
    parser.add_argument("-e", "--engine", type=str,
C
chengmo 已提交
262 263
                        choices=["single", "local_cluster", "cluster",
                                 "tdm_single", "tdm_local_cluster", "tdm_cluster"])
T
tangwei 已提交
264

C
chengmo 已提交
265 266
    parser.add_argument("-d", "--device", type=str,
                        choices=["cpu", "gpu"], default="cpu")
T
tangwei 已提交
267
    parser.add_argument("-b", "--backend", type=str, default=None)
C
chengmo 已提交
268 269
    parser.add_argument("-r", "--role", type=str,
                        choices=["master", "worker"], default="master")
T
tangwei 已提交
270

T
tangwei 已提交
271 272 273
    abs_dir = os.path.dirname(os.path.abspath(__file__))
    envs.set_runtime_environs({"PACKAGE_BASE": abs_dir})

T
tangwei 已提交
274
    args = parser.parse_args()
T
tangwei 已提交
275 276
    args.engine = args.engine.upper()
    args.device = args.device.upper()
T
tangwei 已提交
277 278
    args.role = args.role.upper()

C
fix  
chengmo 已提交
279
    model_name = args.model.split('.')[-1]
T
tangwei 已提交
280
    args.model = get_abs_model(args.model)
T
tangwei 已提交
281
    engine_registry()
T
tangwei 已提交
282

C
chengmo 已提交
283
    which_engine = get_engine(args)
T
bug fix  
tangwei12 已提交
284

T
tangwei 已提交
285 286
    engine = which_engine(args)
    engine.run()