compiler.py 12.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 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.

Z
Zeng Jinle 已提交
15
import logging
16 17 18
import multiprocessing
import os
import six
X
polish  
Xin Pan 已提交
19
import sys
20
from .. import compat as cpt
X
Xin Pan 已提交
21
from . import framework
S
sneaxiy 已提交
22
from .framework import cuda_places, cpu_places
23 24 25

from . import core

X
Xin Pan 已提交
26 27
__all__ = ['CompiledProgram', 'ExecutionStrategy', 'BuildStrategy']

28 29
ExecutionStrategy = core.ParallelExecutor.ExecutionStrategy
BuildStrategy = core.ParallelExecutor.BuildStrategy
F
flame 已提交
30 31
InferNativeConfig = core.NativeConfig
InferAnalysisConfig = core.AnalysisConfig
32 33 34 35 36 37 38 39


def _place_obj(place):
    p = core.Place()
    p.set_place(place)
    return p


40 41
def _is_pserver_mode(main_program):
    main = main_program if main_program \
C
chengduo 已提交
42
        else framework.default_main_program()
43 44 45 46 47 48
    for op in main.global_block().ops:
        if op.type in ["send", "recv"]:
            return True
    return False


X
polish  
Xin Pan 已提交
49
class CompiledProgram(object):
X
polish  
Xin Pan 已提交
50
    """
X
Xin Pan 已提交
51
    Compiles to Graph for execution.
X
polish  
Xin Pan 已提交
52

X
Xin Pan 已提交
53 54 55 56
    1. Users first create the program with layers.
    2. Optionally, users use CompiledProgram to optimize the program before run.
    3. The original program or CompiledProgram is run by executor.

X
polish  
Xin Pan 已提交
57 58 59 60 61 62 63 64
    The CompiledProgram is used to transform a program for various
    optimizations, for example.
      * Pre-compute some logic once so that each run is faster.
      * Transform the program so that it can run in multiple devices.
      * TODO: transform the program for optimized inference or distributed
              training.

    Example:
X
Xin Pan 已提交
65
        .. code-block:: python
X
Xin Pan 已提交
66
            place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
X
Xin Pan 已提交
67 68 69 70 71 72 73 74
            exe = fluid.Executor(place)
            exe.run(startup)
            compiled_prog = compiler.CompiledProgram(main).with_data_parallel(
                loss_name=loss.name)
            for i in range(5):
                test_loss, = exe.run(compiled_prog,
                                     feed=feed_dict,
                                     fetch_list=[loss.name])
X
polish  
Xin Pan 已提交
75 76

    Args:
X
Xin Pan 已提交
77 78 79 80 81
        program_or_graph (Graph|Program): If it's Program, it will be first
            lowered to a graph for further optimizations. If it's a graph
            (potentially optimized before), it will be directly used for
            further optimizations. Note: graph is only supported when compiled
            with with_data_parallel option.
X
polish  
Xin Pan 已提交
82 83
    """

X
Xin Pan 已提交
84 85 86 87 88 89 90 91 92 93 94 95
    def __init__(self, program_or_graph):
        if isinstance(program_or_graph, core.Graph):
            self._graph = program_or_graph
            self._program = None
        elif isinstance(program_or_graph, framework.Program):
            self._graph = core.Graph(program_or_graph.desc)
            self._program = program_or_graph
        else:
            raise ValueError("Wrong program_to_graph type: %s" %
                             type(program_or_graph))

        self._program_desc = self._graph.origin_program_desc()
X
polish  
Xin Pan 已提交
96 97 98
        self._scope = None
        self._place = None
        self._executor = None
99 100
        self._compiled = False
        self._is_data_parallel = False
F
flame 已提交
101
        self._is_inference = False
102

X
Xin Pan 已提交
103 104 105 106
    def with_data_parallel(self,
                           loss_name=None,
                           build_strategy=None,
                           exec_strategy=None,
S
sneaxiy 已提交
107 108
                           share_vars_from=None,
                           places=None):
X
Xin Pan 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122
        """Configs the program to run in data parallel way.

        Args:
            loss_name (str): The loss name must set in training. Default None.
            build_strategy(BuildStrategy): build_strategy is used to
                build the graph so it can run on multiple devices/cores with
                optimized topology.
                For more information, please refer to fluid.BuildStrategy.
                Default None.
            exec_strategy(ExecutionStrategy): exec_strategy is used to
                to select the a way to execute the graph, for example how many
                threads are used, how many iterations to clean up the temp
                variables. For more information, please refer
                to fluid.ExecutionStrategy. Default None.
S
sneaxiy 已提交
123
            share_vars_from(CompiledProgram): If provided, this CompiledProgram
X
Xin Pan 已提交
124 125 126
                will share variables from `share_vars_from`. `share_vars_from`
                must be run by the executor before this CompiledProgram so that
                vars are ready.
S
sneaxiy 已提交
127
            places(list(CUDAPlace)|list(CPUPlace)|None): If provided, only compile
S
sneaxiy 已提交
128 129 130
                program in the given places. Otherwise, the places used when compiled 
                is determined by the Executor, and the places used are controlled 
                by environment variables: FLAGS_selected_gpus or CUDA_VISIBLE_DEVICES
S
sneaxiy 已提交
131 132 133
                if using GPU; or CPU_NUM if using CPU. For example, if you want to 
                run on GPU 0 and 1, set places=[fluid.CUDAPlace(0), fluid.CUDAPlace(1)].
                If you want to run on 2 CPU cores, set places=[fluid.CPUPlace()]*2.  
S
sneaxiy 已提交
134

X
Xin Pan 已提交
135 136 137
        Returns:
            self
        """
138
        assert not self._is_data_parallel, "Already compiled with parallel."
X
Xin Pan 已提交
139
        assert not self._is_inference, "Cannot compile both data parallel and inference"
140 141 142 143
        self._is_data_parallel = True
        self._build_strategy = build_strategy
        self._exec_strategy = exec_strategy
        self._loss_name = loss_name
X
polish  
Xin Pan 已提交
144
        self._share_vars_from = share_vars_from
X
fix  
Xin Pan 已提交
145 146 147 148
        if self._exec_strategy is None:
            self._exec_strategy = ExecutionStrategy()
        if self._build_strategy is None:
            self._build_strategy = BuildStrategy()
S
sneaxiy 已提交
149 150 151
        if places is not None:
            if not isinstance(places, (list, tuple)):
                places = [places]
S
sneaxiy 已提交
152
            self._places = places
S
sneaxiy 已提交
153 154
        else:
            self._places = None
S
sneaxiy 已提交
155
        self._build_strategy.is_distribution = _is_pserver_mode(self._program)
Z
Zeng Jinle 已提交
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 182 183 184 185 186 187 188

        # FIXME(dzhwinter): enable_inplace should be after memory_optimize
        # if turn on python memory optimize, turn off the inplace_pass.
        # memory_optimize and enable_inplace default are True, but we can disable them on purpose
        if self._program:
            if self._program._is_mem_optimized:
                self._build_strategy.memory_optimize = False
                self._build_strategy.enable_inplace = False
            elif not self._build_strategy.memory_optimize or not self._build_strategy.enable_inplace:
                # remind the user to try our memmory optimize strategy
                logging.warn("""
     You can try our memory optimize feature to save your memory usage:
         # create a build_strategy variable to set memory optimize option
         build_strategy = compiler.BuildStrategy()
         build_strategy.enable_inplace = True
         build_strategy.memory_optimize = True
         
         # pass the build_strategy to with_data_parallel API
         compiled_prog = compiler.CompiledProgram(main).with_data_parallel(
             loss_name=loss.name, build_strategy=build_strategy)
      
     !!! Memory optimize is our experimental feature !!!
         some variables may be removed/reused internal to save memory usage, 
         in order to fetch the right value of the fetch_list, please set the 
         persistable property to true for each variable in fetch_list

         # Sample
         conv1 = fluid.layers.conv2d(data, 4, 5, 1, act=None) 
         # if you need to fetch conv1, then:
         conv1.persistable = True

                 """)

189 190
        return self

F
flame 已提交
191 192 193 194 195 196 197 198
    def with_inference_optimize(self, config):
        """ Add inference optimize

        Args:
            config: instance of `NativeConfig` or `AnalysisConfig` to create predictor
        Returns:
            self
        """
X
Xin Pan 已提交
199
        assert not self._is_data_parallel, "Cannot compile both data parallel and inference"
X
Xin Pan 已提交
200 201
        assert not self._is_inference, "Already compiled with inference"

F
flame 已提交
202 203 204 205 206 207 208
        assert any([
            isinstance(config, InferNativeConfig),
            isinstance(config, InferAnalysisConfig)
        ])
        self._is_inference = True
        self._infer_config = config
        return self
X
polish  
Xin Pan 已提交
209

F
flame 已提交
210
    def _with_distributed(self):
X
polish  
Xin Pan 已提交
211 212
        raise NotImplementedError()

213
    def _compile_data_parallel(self, use_cuda=False, scope=None):
X
polish  
Xin Pan 已提交
214
        if self._share_vars_from:
215
            if scope:
X
polish  
Xin Pan 已提交
216 217 218 219 220 221 222 223 224 225
                sys.stderr.write("share_vars_from is set, scope is ignored.\n")
            if not self._share_vars_from._is_data_parallel:
                raise ValueError("share_vars_from is not data parallel. Cannot "
                                 "share vars from it.")
            if self._share_vars_from._executor is None:
                raise ValueError(
                    "share_vars_from is not compiled and run, so there is no "
                    "var to share.")
            self._local_scopes = self._share_vars_from._executor.local_scopes()
        else:
226
            assert scope is not None, ""
X
polish  
Xin Pan 已提交
227
            self._local_scopes = []
228

S
sneaxiy 已提交
229
        self._exec_strategy.use_cuda = use_cuda
S
sneaxiy 已提交
230 231 232
        has_set_place = (self._places is not None)
        if has_set_place:
            for p in self._places:
S
sneaxiy 已提交
233
                assert p._type() == self._place._type(), \
S
sneaxiy 已提交
234
                    "Place type not match. You may set the wrong type of places"
235
        else:
S
sneaxiy 已提交
236
            self._places = cuda_places(
S
sneaxiy 已提交
237
            ) if self._exec_strategy.use_cuda else cpu_places()
238 239 240 241 242 243 244 245
        assert self._places, "no place for execution"

        if self._exec_strategy.num_threads == 0:
            if self._exec_strategy.use_cuda:
                # Experiments on se-resnext shows that too many threads hurt
                # performance. Worth tunning for other models in the future.
                self._exec_strategy.num_threads = len(self._places) * 4
            else:
S
sneaxiy 已提交
246
                self._exec_strategy.num_threads = len(self._places) * 2
247

X
Xin Pan 已提交
248 249 250 251 252
        # TODO(wuyi): trainer endpoings should be passed in through
        # build_strategy, not program.xxx.
        if self._program and self._build_strategy.num_trainers > 1 and \
                self._program._trainers_endpoints:
            tps = self._program._trainers_endpoints
D
dzhwinter 已提交
253

254
            assert self._build_strategy.num_trainers == len(
X
Xin Pan 已提交
255 256 257
                tps), "num_trainers == len(end_points)"
            self._build_strategy.trainers_endpoints = tps

Q
qingqing01 已提交
258 259 260
        if self._build_strategy.sync_batch_norm:
            self._build_strategy.enable_sequential_execution = True

X
Xin Pan 已提交
261
        self._persistable_vars = []
Z
Zhen Wang 已提交
262 263 264 265
        for node in self._graph.nodes():
            if node.is_var() and node.var() is not None and node.var().persistable() and \
                    node.var().type() != core.VarDesc.VarType.RAW:
                self._persistable_vars.append(cpt.to_text(node.name()))
266 267

        places = list(map(_place_obj, self._places))
Y
Yan Xu 已提交
268 269 270 271 272 273 274 275 276 277 278
        # ParallelExecutor would broadcast all the parameters during initializing.
        # The parameters of each process should be in the same ordered for the data-parallelism
        # distributed training to keep the broadcast correct.
        self._persistable_vars = list(set(self._persistable_vars))
        self._persistable_vars.sort()

        return core.ParallelExecutor(
            places, self._persistable_vars,
            cpt.to_text(self._loss_name)
            if self._loss_name else six.u(''), self._scope, self._local_scopes,
            self._exec_strategy, self._build_strategy, self._graph)
279

F
flame 已提交
280 281 282
    def _compile_inference(self):
        return core.create_paddle_predictor(self._infer_config)

283
    def _compile(self, scope, place):
X
Xin Pan 已提交
284 285 286 287 288 289 290 291 292 293
        """Compile the program based on the configs.

        Args:
            scope: The variables (resources) that are associated with
               this compiled program.
            place: The location that the compiled program will be run on.

        Returns:
            self
        """
294
        if self._compiled:
X
polish  
Xin Pan 已提交
295 296
            if scope and self._scope != scope:
                raise ValueError("Cannot compile with different scope")
S
sneaxiy 已提交
297
            if place and not self._place._equals(place):
X
polish  
Xin Pan 已提交
298
                raise ValueError("Cannot compile with different place")
299
            return self
X
fix  
Xin Pan 已提交
300
        self._compiled = True
301 302 303 304

        self._scope = scope
        self._place = place
        if self._is_data_parallel:
305 306 307
            self._executor = self._compile_data_parallel(
                use_cuda=isinstance(self._place, core.CUDAPlace),
                scope=self._scope)
F
flame 已提交
308 309
        elif self._is_inference:
            self._executor = self._compile_inference()
310 311 312 313
        else:
            p = _place_obj(self._place)
            self._executor = core.Executor(p)
        return self