base.py 12.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
# 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.
14 15
from ..wrapped_decorator import signature_safe_contextmanager, wrap_decorator
import contextlib
16
import sys
17 18 19
import numpy as np
from paddle.fluid import core
from paddle.fluid import framework
M
minqiyang 已提交
20
from .tracer import Tracer
Z
Zeng Jinle 已提交
21
import logging
J
Jiabin Yang 已提交
22
import objgraph
23

24 25 26
__all__ = [
    'no_grad',
    'guard',
27 28 29
    'enable_dygraph',
    'disable_dygraph',
    'enabled',
30 31
    'to_variable',
]
32 33


34 35 36 37 38 39 40 41 42 43 44
def _switch_to_static_graph_(func):
    def __impl__(*args, **kwargs):
        with framework._dygraph_guard(None):
            return func(*args, **kwargs)

    return __impl__


switch_to_static_graph = wrap_decorator(_switch_to_static_graph_)


45 46 47 48 49 50 51 52 53 54 55
@signature_safe_contextmanager
def program_desc_tracing_guard(enable):
    tracer = framework._dygraph_tracer()
    if tracer:
        original_val = tracer._enable_program_desc_tracing
        tracer._enable_program_desc_tracing = enable
    yield
    if tracer:
        tracer._enable_program_desc_tracing = original_val


56 57 58
_functional_dygraph_context_manager = None


59
def enabled():
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    """
    This function checks whether the program runs in dynamic graph mode or not.
    You can enter dynamic graph mode with :ref:`api_fluid_dygraph_guard` api,
    or enable and disable dynamic graph mode with :ref:`api_fluid_dygraph_enable`
    and :ref:`api_fluid_dygraph_disable` api .

    **Note**:
        ``fluid.dygraph.enabled`` is the alias of ``fluid.in_dygraph_mode``, and
        ``fluid.in_dygraph_mode`` is recommended to use.

    Returns:
        bool: Whether the program is running in dynamic graph mode.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid

            fluid.enable_dygraph()  # Now we are in dygragh mode
            print(fluid.dygraph.enabled())  # True
            fluid.disable_dygraph()
            print(fluid.dygraph.enabled())  # False
    """
L
lujun 已提交
83
    return framework.in_dygraph_mode()
84 85


86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
def enable_dygraph(place=None):
    """
    This function enables dynamic graph mode.

    Parameters:
        place(fluid.CPUPlace or fluid.CUDAPlace, optional): Place to execute dygraph.
            If None, the running place will be determined according to the way of paddle compilation. Default: None

    return:
        None

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid

            fluid.enable_dygraph()  # Now we are in dygragh mode
            print(fluid.in_dygraph_mode())  # True
            fluid.disable_dygraph()
            print(fluid.in_dygraph_mode())  # False
    """
    global _functional_dygraph_context_manager
S
songyouwei 已提交
108 109 110
    if _functional_dygraph_context_manager is None:
        _functional_dygraph_context_manager = guard(place=place)
        _functional_dygraph_context_manager.__enter__()
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135


def disable_dygraph():
    """
    This function disables dynamic graph mode.

    return:
        None

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid

            fluid.enable_dygraph()  # Now we are in dygragh mode
            print(fluid.in_dygraph_mode())  # True
            fluid.disable_dygraph()
            print(fluid.in_dygraph_mode())  # False
    """
    global _functional_dygraph_context_manager
    if _functional_dygraph_context_manager is not None:
        _functional_dygraph_context_manager.__exit__(*sys.exc_info())
        _functional_dygraph_context_manager = None


136 137 138 139 140 141 142 143 144 145 146 147 148
@contextlib.contextmanager
def _switch_tracer_mode_guard_(is_train=True):
    tracer = framework._dygraph_tracer()
    if tracer:
        mode = tracer._train_mode
        tracer._train_mode = is_train
        yield
        tracer._train_mode = mode
    else:
        yield


def _no_grad_(func):
149 150 151
    """
    This Decorator will avoid the func being decorated creating backward network in dygraph mode

152 153
    Parameter:
        - **func** (python func): the func don't need grad
154 155 156 157 158 159 160 161 162 163 164

    Examples:

     .. code-block:: python

        import numpy as np
        import paddle.fluid as fluid

        @fluid.dygraph.no_grad
        def test_layer():
            with fluid.dygraph.guard():
165
                inp = np.ones([3, 1024], dtype='float32')
166
                t = fluid.dygraph.base.to_variable(inp)
167 168 169 170
                linear1 = fluid.Linear(1024, 4, bias_attr=False)
                linear2 = fluid.Linear(4, 4)
                ret = linear1(t)
                dy_ret = linear2(ret)
171 172 173 174 175

        test_layer()

    """

176 177 178 179 180 181 182 183
    def __impl__(*args, **kwargs):
        with _switch_tracer_mode_guard_(is_train=False):
            return func(*args, **kwargs)

    return __impl__


no_grad = wrap_decorator(_no_grad_)
L
lujun 已提交
184 185
# for fluidDoc
no_grad.__doc__ = _no_grad_.__doc__
186 187


S
rename  
sneaxiy 已提交
188
@signature_safe_contextmanager
P
Paddle CI 已提交
189
def guard(place=None):
190
    """
191
    This context will create a dygraph context for dygraph to run, using python ``with`` statement.
192

193 194 195
    Parameters:
        place(fluid.CPUPlace or fluid.CUDAPlace, optional): Place to execute dygraph. 
            If None, the running place will be determined according to the way of paddle compilation. Default: None
196 197 198 199 200 201 202 203 204 205 206 207

    return:
        None

    Examples:

     .. code-block:: python

        import numpy as np
        import paddle.fluid as fluid

        with fluid.dygraph.guard():
208
            inp = np.ones([3, 1024], dtype='float32')
209
            t = fluid.dygraph.base.to_variable(inp)
210 211 212 213
            linear1 = fluid.Linear(1024, 4, bias_attr=False)
            linear2 = fluid.Linear(4, 4)
            ret = linear1(t)
            dy_ret = linear2(ret)
214 215

    """
216 217
    train = framework.Program()
    startup = framework.Program()
J
Jiabin Yang 已提交
218
    tracer = Tracer()
219
    VarBase = core.VarBase
M
minqiyang 已提交
220

P
Paddle CI 已提交
221
    if place is None:
M
minqiyang 已提交
222
        if core.is_compiled_with_cuda():
P
Paddle CI 已提交
223
            place = core.CUDAPlace(0)
M
minqiyang 已提交
224 225
        else:
            place = core.CPUPlace()
226
    tracer._expected_place = place
M
minqiyang 已提交
227

228 229
    with framework.program_guard(train, startup):
        with framework.unique_name.guard():
L
lujun 已提交
230 231
            with framework._dygraph_guard(tracer):
                with framework._dygraph_place_guard(place):
P
Paddle CI 已提交
232
                    yield
233 234


235
def _print_debug_msg(parameter_list, limit=5, is_test=False):
Z
Zeng Jinle 已提交
236 237 238 239 240 241
    if not core._is_dygraph_debug_enabled():
        logging.warn(
            'Debug mode is not enabled. Please set FLAGS_dygraph_debug=1 to enable debug'
        )
        return
    unique_name_size = len(framework.unique_name.generator.ids)
242
    tracer_var_size = len(parameter_list)
Z
Zeng Jinle 已提交
243
    alive_cpp_var_size = len(core.VarBase._alive_vars())
J
Jiabin Yang 已提交
244 245 246 247 248 249 250
    if not is_test:
        logging.warn(
            'unique_name num: {}, tracer vars num: {}, alive cpp vars num: {}'
            .format(unique_name_size, tracer_var_size, alive_cpp_var_size))
        objgraph.show_growth(limit=limit)
    else:
        return unique_name_size, tracer_var_size, alive_cpp_var_size
Z
Zeng Jinle 已提交
251 252


253 254 255 256 257 258 259 260 261 262 263 264 265 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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
@framework.dygraph_only
def grad(outputs,
         inputs,
         grad_outputs=None,
         no_grad_set=None,
         create_graph=False,
         backward_strategy=None):
    def check_in_out(in_out_list, name):
        assert in_out_list is not None, "{} should not be None".format(name)

        if isinstance(in_out_list, (list, tuple)):
            assert len(in_out_list) > 0, "{} cannot be empty".format(name)
            for each_var in in_out_list:
                assert isinstance(
                    each_var,
                    core.VarBase), "Elements of {} must be Variable".format(
                        name)
            return in_out_list
        else:
            assert isinstance(
                in_out_list,
                core.VarBase), "{} must be Variable or list of Variable".format(
                    name)
            return [in_out_list]

    outputs = check_in_out(outputs, 'outputs')
    inputs = check_in_out(inputs, 'inputs')

    if grad_outputs is not None:
        if not isinstance(grad_outputs, (list, tuple)):
            grad_outputs = [grad_outputs]

        for each_var in grad_outputs:
            if each_var is not None:
                assert isinstance(
                    each_var, core.VarBase
                ), "grad_outputs must be None, a Variable or a list containing None or Variables"
    else:
        grad_outputs = []

    if len(grad_outputs) > 0:
        assert len(grad_outputs) == len(
            outputs), "The length of grad_outputs must be equal to outputs"

    if no_grad_set is None:
        no_grad_set = []
    elif isinstance(no_grad_set, core.VarBase):
        no_grad_set = [no_grad_set]
    elif isinstance(no_grad_set, (list, tuple, set)):
        no_grad_set = list(no_grad_set)
        for var in no_grad_set:
            assert isinstance(
                var, core.VarBase), "no_grad_set can only contains Variable"
    else:
        raise AssertionError(
            "no_grad_set must be None, Variable or list/tuple/set of Variables")

    if backward_strategy is None:
        backward_strategy = core.BackwardStrategy()

    assert isinstance(backward_strategy, core.BackwardStrategy), \
        "backward_strategy must be type paddle.fluid.dygraph.BackwardStrategy"

    assert isinstance(create_graph, bool), "create_graph must be True or False"

    place = core.Place()
    place.set_place(framework._current_expected_place())
    return core.dygraph_partial_grad(inputs, outputs, grad_outputs, no_grad_set,
                                     place, backward_strategy, create_graph)


324
@framework.dygraph_only
325
def to_variable(value, name=None, zero_copy=None):
326
    """
327
    The API will create a ``Variable`` object from numpy\.ndarray or Variable object.
328

329
    Parameters:
330
        value(ndarray|Variable): The numpy\.ndarray or Variable object that needs to be converted, it can be multi-dimension, and the data type is one of numpy\.{float16, float32, float64, int16, int32, int64, uint8, uint16}.
331
        name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`
332
        zero_copy(bool, optional): Whether to share memory with the input numpy array. This parameter only works with CPUPlace and will be set to True when it is None. Default: None.
333

334
    Returns:
335 336
        Variable: If ``value`` is a numpy\.ndarray object, return ``Tensor`` created from the specified numpy\.ndarray object, which has same data type and shape with ``value``. If ``value`` is a Variable object, just return ``value``.

337 338 339 340 341 342 343 344

    Examples:

     .. code-block:: python

        import numpy as np
        import paddle.fluid as fluid

345
        with fluid.dygraph.guard(fluid.CPUPlace()):
346
            x = np.ones([2, 2], np.float32)
347 348 349
            y = fluid.dygraph.to_variable(x, zero_copy=False)
            x[0][0] = -1
            y[0][0].numpy()  # array([1.], dtype=float32)
350
            y = fluid.dygraph.to_variable(x)
351 352
            x[0][0] = 0
            y[0][0].numpy()  # array([0.], dtype=float32)
353 354

    """
355
    if isinstance(value, np.ndarray):
L
lujun 已提交
356 357
        assert framework.in_dygraph_mode(
        ), "to_variable could only be called in dygraph mode"
358 359 360 361 362 363
        if isinstance(framework._current_expected_place(),
                      framework.core.CPUPlace):
            if zero_copy is None:
                zero_copy = True
        else:
            assert not zero_copy, "zero_copy mode can only be used with CPUPlace"
364 365 366 367
            zero_copy = False
        py_var = core.VarBase(
            value=value,
            place=framework._current_expected_place(),
L
Leo Chen 已提交
368 369 370
            persistable=False,
            zero_copy=zero_copy,
            name=name if name else '')
371
        return py_var
372
    elif isinstance(value, (core.VarBase, framework.Variable)):
373
        return value
374 375 376
    else:
        raise TypeError(
            "to_variable only accepts 'ndarray' and 'Variable' as value's input")