network.py 19.2 KB
Newer Older
C
Chengmo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# 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.

from __future__ import print_function

import os
import warnings

import paddle.fluid as fluid
from paddlerec.core.utils import envs
W
wangjiawei04 已提交
22
from paddlerec.core.trainers.framework.dataset import DataLoader, QueueDataset, InMemoryDataset
C
Chengmo 已提交
23 24 25

__all__ = [
    "NetworkBase", "SingleNetwork", "PSNetwork", "PslibNetwork",
C
Chengmo 已提交
26
    "CollectiveNetwork", "FineTuningNetwork"
C
Chengmo 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
]


class NetworkBase(object):
    """R
    """

    def __init__(self, context):
        pass

    def build_network(self, context):
        pass


class SingleNetwork(NetworkBase):
    """R
    """

    def __init__(self, context):
        print("Running SingleNetwork.")
        pass

    def build_network(self, context):
        context["model"] = {}
T
tangwei 已提交
51
        for model_dict in context["phases"]:
C
Chengmo 已提交
52 53 54 55 56 57 58 59 60
            context["model"][model_dict["name"]] = {}
            train_program = fluid.Program()
            startup_program = fluid.Program()
            scope = fluid.Scope()
            dataset_name = model_dict["dataset_name"]

            with fluid.program_guard(train_program, startup_program):
                with fluid.unique_name.guard():
                    with fluid.scope_guard(scope):
T
tangwei 已提交
61 62
                        model_path = envs.os_path_adapter(
                            envs.workspace_adapter(model_dict["model"]))
T
tangwei 已提交
63 64
                        model = envs.lazy_instance_by_fliename(
                            model_path, "Model")(context["env"])
C
Chengmo 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

                        if context["is_infer"]:
                            model._infer_data_var = model.input_data(
                                is_infer=context["is_infer"],
                                dataset_name=model_dict["dataset_name"])
                        else:
                            model._data_var = model.input_data(
                                dataset_name=model_dict["dataset_name"])

                        if envs.get_global_env("dataset." + dataset_name +
                                               ".type") == "DataLoader":
                            model._init_dataloader(
                                is_infer=context["is_infer"])
                            data_loader = DataLoader(context)
                            data_loader.get_dataloader(context, dataset_name,
                                                       model._data_loader)

                        if context["is_infer"]:
                            model.net(model._infer_data_var,
                                      context["is_infer"])
                        else:
                            model.net(model._data_var, context["is_infer"])
                            optimizer = model.optimizer()
                            optimizer.minimize(model._cost)
            context["model"][model_dict["name"]][
                "main_program"] = train_program
            context["model"][model_dict["name"]][
                "startup_program"] = startup_program
            context["model"][model_dict["name"]]["scope"] = scope
            context["model"][model_dict["name"]]["model"] = model
            context["model"][model_dict["name"]][
C
Chengmo 已提交
96 97 98 99 100 101 102 103 104 105 106 107
                "default_main_program"] = train_program.clone()
            context["model"][model_dict["name"]]["compiled_program"] = None

        context["dataset"] = {}
        for dataset in context["env"]["dataset"]:
            type = envs.get_global_env("dataset." + dataset["name"] + ".type")

            if type == "QueueDataset":
                dataset_class = QueueDataset(context)
                context["dataset"][dataset[
                    "name"]] = dataset_class.create_dataset(dataset["name"],
                                                            context)
W
wangjiawei04 已提交
108 109 110 111 112
            elif type == "InMemoryDataset":
                dataset_class = InMemoryDataset(context)
                context["dataset"][dataset[
                    "name"]] = dataset_class.create_dataset(dataset["name"],
                                                            context)
C
Chengmo 已提交
113 114 115 116 117 118 119 120 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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        context["status"] = "startup_pass"


class FineTuningNetwork(NetworkBase):
    """R
    """

    def __init__(self, context):
        print("Running FineTuningNetwork.")

    def build_network(self, context):
        context["model"] = {}
        for model_dict in context["phases"]:
            context["model"][model_dict["name"]] = {}
            train_program = fluid.Program()
            startup_program = fluid.Program()
            scope = fluid.Scope()
            dataset_name = model_dict["dataset_name"]

            with fluid.program_guard(train_program, startup_program):
                with fluid.unique_name.guard():
                    with fluid.scope_guard(scope):
                        model_path = envs.os_path_adapter(
                            envs.workspace_adapter(model_dict["model"]))
                        model = envs.lazy_instance_by_fliename(
                            model_path, "Model")(context["env"])

                        model._data_var = model.input_data(
                            dataset_name=model_dict["dataset_name"])

                        if envs.get_global_env("dataset." + dataset_name +
                                               ".type") == "DataLoader":
                            model._init_dataloader(
                                is_infer=context["is_infer"])
                            data_loader = DataLoader(context)
                            data_loader.get_dataloader(context, dataset_name,
                                                       model._data_loader)

                        model.net(model._data_var, context["is_infer"])

                        finetuning_varnames = envs.get_global_env(
                            "runner." + context["runner_name"] +
                            ".finetuning_aspect_varnames",
                            default_value=[])

                        if len(finetuning_varnames) == 0:
                            raise ValueError(
                                "nothing need to be fine tuning, you may use other traning mode"
                            )

                        if len(finetuning_varnames) != 1:
                            raise ValueError(
                                "fine tuning mode can only accept one varname now"
                            )

                        varname = finetuning_varnames[0]
                        finetuning_vars = train_program.global_block().vars[
                            varname]
                        finetuning_vars.stop_gradient = True
                        optimizer = model.optimizer()
                        optimizer.minimize(model._cost)

            context["model"][model_dict["name"]][
                "main_program"] = train_program
            context["model"][model_dict["name"]][
                "startup_program"] = startup_program
            context["model"][model_dict["name"]]["scope"] = scope
            context["model"][model_dict["name"]]["model"] = model
            context["model"][model_dict["name"]][
C
Chengmo 已提交
182
                "default_main_program"] = train_program.clone()
183
            context["model"][model_dict["name"]]["compiled_program"] = None
C
Chengmo 已提交
184 185

        context["dataset"] = {}
T
tangwei 已提交
186
        for dataset in context["env"]["dataset"]:
T
tangwei 已提交
187
            type = envs.get_global_env("dataset." + dataset["name"] + ".type")
188 189

            if type == "QueueDataset":
C
Chengmo 已提交
190 191 192 193
                dataset_class = QueueDataset(context)
                context["dataset"][dataset[
                    "name"]] = dataset_class.create_dataset(dataset["name"],
                                                            context)
W
wangjiawei04 已提交
194 195 196 197 198
            elif type == "InMemoryDataset":
                dataset_class = InMemoryDataset(context)
                context["dataset"][dataset[
                    "name"]] = dataset_class.create_dataset(dataset["name"],
                                                            context)
C
Chengmo 已提交
199 200 201 202 203 204 205 206 207 208
        context["status"] = "startup_pass"


class PSNetwork(NetworkBase):
    def __init__(self, context):
        print("Running PSNetwork.")
        pass

    def build_network(self, context):
        context["model"] = {}
T
tangwei 已提交
209
        if len(context["env"]["phase"]) > 1:
C
Chengmo 已提交
210 211 212 213
            warnings.warn(
                "Cluster Train Only Support One Phase.",
                category=UserWarning,
                stacklevel=2)
T
tangwei 已提交
214
        model_dict = context["env"]["phase"][0]
C
Chengmo 已提交
215 216 217
        context["model"][model_dict["name"]] = {}
        dataset_name = model_dict["dataset_name"]

T
tangwei 已提交
218 219
        model_path = envs.os_path_adapter(
            envs.workspace_adapter(model_dict["model"]))
T
tangwei 已提交
220 221
        model = envs.lazy_instance_by_fliename(model_path,
                                               "Model")(context["env"])
C
Chengmo 已提交
222 223 224 225 226
        model._data_var = model.input_data(
            dataset_name=model_dict["dataset_name"])
        if envs.get_global_env("dataset." + dataset_name +
                               ".type") == "DataLoader":
            model._init_dataloader(is_infer=False)
227

C
Chengmo 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241
        model.net(model._data_var, False)
        optimizer = model.optimizer()
        strategy = self._build_strategy(context)
        optimizer = context["fleet"].distributed_optimizer(optimizer, strategy)
        optimizer.minimize(model._cost)

        context["model"][model_dict["name"]]["main_program"] = context[
            "fleet"].main_program
        context["model"][model_dict["name"]]["startup_program"] = context[
            "fleet"].startup_program
        context["model"][model_dict["name"]]["scope"] = fluid.global_scope()
        context["model"][model_dict["name"]]["model"] = model
        context["model"][model_dict["name"]]["default_main_program"] = context[
            "fleet"].main_program.clone()
242
        context["model"][model_dict["name"]]["compiled_program"] = None
C
Chengmo 已提交
243 244 245 246 247 248

        if context["fleet"].is_server():
            self._server(context)
        else:
            context["fleet"].init_worker()
            context["dataset"] = {}
T
tangwei 已提交
249
            for dataset in context["env"]["dataset"]:
T
tangwei 已提交
250 251
                type = envs.get_global_env("dataset." + dataset["name"] +
                                           ".type")
252 253 254 255 256
                if type == "DataLoader":
                    data_loader = DataLoader(context)
                    data_loader.get_dataloader(context, dataset_name,
                                               model._data_loader)
                elif type == "QueueDataset":
C
Chengmo 已提交
257 258 259 260
                    dataset_class = QueueDataset(context)
                    context["dataset"][dataset[
                        "name"]] = dataset_class.create_dataset(
                            dataset["name"], context)
W
wangjiawei04 已提交
261 262 263 264 265
                elif type == "InMemoryDataset":
                    dataset_class = InMemoryDataset(context)
                    context["dataset"][dataset[
                        "name"]] = dataset_class.create_dataset(
                            dataset["name"], context)
C
Chengmo 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
            context["status"] = "startup_pass"

    def _build_strategy(self, context):
        from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import StrategyFactory
        mode = envs.get_runtime_environ("train.trainer.strategy")
        assert mode in ["async", "geo", "sync", "half_async"]

        strategy = None

        if mode == "async":
            strategy = StrategyFactory.create_async_strategy()
        elif mode == "geo":
            push_num = envs.get_global_env("train.strategy.mode.push_num", 100)
            strategy = StrategyFactory.create_geo_strategy(push_num)
        elif mode == "sync":
            strategy = StrategyFactory.create_sync_strategy()
        elif mode == "half_async":
            strategy = StrategyFactory.create_half_async_strategy()

        assert strategy is not None

        context["strategy"] = strategy
        return strategy

    def _server(self, context):
        init_model_path = envs.get_global_env(
            "runner." + context["runner_name"] + ".init_model_path",
            default_value="")
        context["fleet"].init_server(init_model_path)
        context["fleet"].run_server()
        context['status'] = "terminal_pass"


class PslibNetwork(NetworkBase):
    def __init__(self, context):
        print("Running PslibNetwork.")
        pass

    def build_network(self, context):
        context["model"] = {}
T
tangwei 已提交
306
        if len(context["env"]["phase"]) > 1:
C
Chengmo 已提交
307 308 309 310
            warnings.warn(
                "Cluster Train Only Support One Phase.",
                category=UserWarning,
                stacklevel=2)
T
tangwei 已提交
311
        model_dict = context["env"]["phase"][0]
C
Chengmo 已提交
312 313 314 315 316 317 318 319 320
        train_program = fluid.Program()
        startup_program = fluid.Program()
        scope = fluid.Scope()
        dataset_name = model_dict["dataset_name"]

        with fluid.program_guard(train_program, startup_program):
            with fluid.unique_name.guard():
                with fluid.scope_guard(scope):
                    context["model"][model_dict["name"]] = {}
T
tangwei 已提交
321 322
                    model_path = envs.os_path_adapter(
                        envs.workspace_adapter(model_dict["model"]))
T
tangwei 已提交
323 324
                    model = envs.lazy_instance_by_fliename(
                        model_path, "Model")(context["env"])
C
Chengmo 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
                    model._data_var = model.input_data(
                        dataset_name=model_dict["dataset_name"])
                    if envs.get_global_env("dataset." + dataset_name +
                                           ".type") == "DataLoader":
                        model._init_dataloader(is_infer=False)
                    model.net(model._data_var, False)
                    optimizer = model.optimizer()

                    optimizer = context["fleet"].distributed_optimizer(
                        optimizer)
                    optimizer.minimize([model._cost], [fluid.global_scope()])

                    context["model"][model_dict["name"]][
                        "main_program"] = train_program
                    context["model"][model_dict["name"]][
                        "startup_program"] = startup_program
                    context["model"][model_dict["name"]]["scope"] = scope
                    context["model"][model_dict["name"]]["model"] = model
                    context["model"][model_dict["name"]][
                        "default_main_program"] = train_program.clone()
345 346
                    context["model"][model_dict["name"]][
                        "compile_program"] = None
C
Chengmo 已提交
347 348 349 350 351

        if context["fleet"].is_server():
            self._server(context)
        else:
            context["dataset"] = {}
T
tangwei 已提交
352
            for dataset in context["env"]["dataset"]:
T
tangwei 已提交
353 354
                type = envs.get_global_env("dataset." + dataset["name"] +
                                           ".type")
355 356 357 358 359
                if type == "DataLoader":
                    data_loader = DataLoader(context)
                    data_loader.get_dataloader(context, dataset_name, context[
                        "model"][model_dict["name"]]["model"]._data_loader)
                elif type == "QueueDataset":
C
Chengmo 已提交
360 361 362 363
                    dataset_class = QueueDataset(context)
                    context["dataset"][dataset[
                        "name"]] = dataset_class.create_dataset(
                            dataset["name"], context)
W
wangjiawei04 已提交
364 365 366 367 368
                elif type == "InMemoryDataset":
                    dataset_class = InMemoryDataset(context)
                    context["dataset"][dataset[
                        "name"]] = dataset_class.create_dataset(
                            dataset["name"], context)
C
Chengmo 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382
            context["status"] = "startup_pass"

    def _server(self, context):
        context["fleet"].run_server()
        context['status'] = "terminal_pass"


class CollectiveNetwork(NetworkBase):
    def __init__(self, context):
        print("Running CollectiveNetwork.")
        pass

    def build_network(self, context):
        context["model"] = {}
T
tangwei 已提交
383
        if len(context["env"]["phase"]) > 1:
C
Chengmo 已提交
384 385 386 387
            warnings.warn(
                "Cluster Train Only Support One Phase.",
                category=UserWarning,
                stacklevel=2)
T
tangwei 已提交
388
        model_dict = context["env"]["phase"][0]
C
Chengmo 已提交
389 390 391 392 393 394 395 396
        context["model"][model_dict["name"]] = {}
        dataset_name = model_dict["dataset_name"]

        train_program = fluid.Program()
        startup_program = fluid.Program()
        scope = fluid.Scope()
        with fluid.program_guard(train_program, startup_program):
            with fluid.scope_guard(scope):
T
tangwei 已提交
397 398
                model_path = envs.os_path_adapter(
                    envs.workspace_adapter(model_dict["model"]))
T
tangwei 已提交
399

C
Chengmo 已提交
400
                model = envs.lazy_instance_by_fliename(model_path,
T
tangwei 已提交
401
                                                       "Model")(context["env"])
C
Chengmo 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
                model._data_var = model.input_data(
                    dataset_name=model_dict["dataset_name"])
                if envs.get_global_env("dataset." + dataset_name +
                                       ".type") == "DataLoader":
                    model._init_dataloader(is_infer=False)
                    data_loader = DataLoader(context)
                    data_loader.get_dataloader(context, dataset_name,
                                               model._data_loader)
                model.net(model._data_var, False)
                optimizer = model.optimizer()
                strategy = self._build_strategy(context)
                optimizer = context["fleet"].distributed_optimizer(optimizer,
                                                                   strategy)
                optimizer.minimize(model._cost)

                context["model"][model_dict["name"]]["main_program"] = context[
                    "fleet"].main_program
                context["model"][model_dict["name"]][
                    "startup_program"] = startup_program
                context["model"][model_dict["name"]]["scope"] = scope
                context["model"][model_dict["name"]]["model"] = model
                context["model"][model_dict["name"]][
                    "default_main_program"] = train_program
425
                context["model"][model_dict["name"]]["compiled_program"] = None
C
Chengmo 已提交
426 427

        context["dataset"] = {}
T
tangwei 已提交
428
        for dataset in context["env"]["dataset"]:
T
tangwei 已提交
429
            type = envs.get_global_env("dataset." + dataset["name"] + ".type")
430 431 432 433
            if type == "QueueDataset":
                raise ValueError(
                    "Collective don't support QueueDataset training, please use DataLoader."
                )
C
Chengmo 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446
                dataset_class = QueueDataset(context)
                context["dataset"][dataset[
                    "name"]] = dataset_class.create_dataset(dataset["name"],
                                                            context)
        context["status"] = "startup_pass"

    def _build_strategy(self, context):
        from paddle.fluid.incubate.fleet.collective import DistributedStrategy
        exec_strategy = fluid.ExecutionStrategy()
        strategy = DistributedStrategy()
        strategy.exec_strategy = exec_strategy
        context["strategy"] = strategy
        return strategy