base.py 30.5 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
from ..wrapped_decorator import signature_safe_contextmanager, wrap_decorator
S
songyouwei 已提交
15
import decorator
16
import contextlib
17 18
import functools
import inspect
19
import sys
20
import numpy as np
21 22 23 24
from paddle.base import core
from paddle.base import framework
from paddle.base.framework import global_var
from paddle.base.multiprocess_utils import CleanupFuncRegistrar
M
minqiyang 已提交
25
from .tracer import Tracer
Z
Zeng Jinle 已提交
26
import logging
27
from ..data_feeder import convert_dtype
L
Leo Chen 已提交
28
import warnings
29
from ..framework import _get_paddle_place
30
import paddle
31
import warnings
32

33
__all__ = [
34 35 36 37 38 39 40 41
    'no_grad',
    'no_grad_',
    'grad',
    'guard',
    'enable_dygraph',
    'disable_dygraph',
    'enabled',
    'to_variable',
42
]
43

44
NON_PERSISTABLE_VAR_NAME_SUFFIX = "__non_persistable"
45 46 47 48


def in_declarative_mode():
    """
H
hjyp 已提交
49
    Return a bool value that indicates whether running code under `@to_static`
50 51

    """
52
    return global_var._in_declarative_mode_
53

54

55 56 57
def declarative_unsupport_argument_warning(
    func_name, input_names, inputs, support_values
):
58 59 60 61 62 63 64 65
    """
    Warning if inputs do not elementwisely equals to support_values.
    It's a utility function for dy2static when dygraph interface have
    more inputs than static interface such as paddle.grad.

    """
    for name, inp, sup in zip(input_names, inputs, support_values):
        if inp != sup:
66 67 68 69
            warnings.warn(
                f"{func_name} has unsupported parameter in jit: "
                + f"{name}, jit will discard it"
            )
70 71


72 73 74 75 76 77 78 79 80 81 82
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_)


83 84
@signature_safe_contextmanager
def _switch_declarative_mode_guard_(is_declarative=True):
85 86 87
    global global_var
    original_val = global_var._in_declarative_mode_
    global_var._in_declarative_mode_ = is_declarative
88
    yield
89
    global_var._in_declarative_mode_ = original_val
90 91


92 93 94 95 96 97
@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
98 99 100 101 102
    try:
        yield
    finally:
        if tracer:
            tracer._enable_program_desc_tracing = original_val
103 104


105 106
@signature_safe_contextmanager
def param_guard(parameters):
107
    # Note: parameters is a reference of self._parameters or self._buffers
108
    if in_declarative_mode() and not paddle.in_dynamic_mode() and parameters:
X
xiongkun 已提交
109 110 111 112 113 114 115 116 117 118 119
        try:
            origin_parameters = parameters.copy()
            for name, var_base in parameters.items():
                if isinstance(var_base, list):
                    new_var = [_convert_into_variable(var) for var in var_base]
                else:
                    new_var = _convert_into_variable(var_base)
                parameters[name] = new_var
            yield
        finally:
            parameters.update(origin_parameters)
120 121 122 123
    else:
        yield


J
Jiabin Yang 已提交
124
def _convert_into_variable(tensor):
125
    """
126
    Convert Tensor into Variable.
127
    """
W
wanghuancoder 已提交
128
    if isinstance(tensor, core.eager.Tensor):
129
        # Check whether has been created before.
J
Jiabin Yang 已提交
130
        new_var = tensor.block._find_var_recursive(tensor.name)
131 132
        if new_var is not None:
            assert isinstance(new_var, framework.Variable)
W
wanghuancoder 已提交
133 134
        # Convert EagerParamBase into Parameter with same attributes in dy2stat.
        elif isinstance(tensor, framework.EagerParamBase):
J
Jiabin Yang 已提交
135
            new_var = tensor._to_static_var(to_parameter=True)
136
        else:
W
wanghuancoder 已提交
137
            # Note(Aurelius84): Convert Tensor in self._buffers into Variable with
138
            # same attributes and set persistable=True to allow saving this var.
W
wanghuancoder 已提交
139
            # Because users can create a Tensor in `__init__`  like a
140 141 142 143
            # `mask` Tensor or `hidden_0` in RNN layers, which is equivalent to a Parameter
            # and necessary for inferring. It will be pruned if it's not necessary for inferring.

            # But if its shape is empty while created from `create_variable()`, we consider this buffer
144 145 146 147
            # non-persistable. See case of `dropout_state` in lstm api.
            is_persistable = True
            if tensor.name.endswith(NON_PERSISTABLE_VAR_NAME_SUFFIX):
                is_persistable = False
148

149 150 151
            new_var = tensor._to_static_var(
                to_parameter=False, persistable=is_persistable
            )
152 153 154 155 156 157 158 159 160
        # add param into parameter recorder to collect all the params used in this program.
        if new_var.persistable is True:
            from paddle.jit.dy2static.program_translator import (
                ProgramTranslator,
            )

            ProgramTranslator.get_instance()._params_recorder.add(
                tensor.block.program, tensor
            )
161 162
        return new_var
    else:
J
Jiabin Yang 已提交
163
        return tensor
164 165


166
def enabled():
167 168
    """
    This function checks whether the program runs in dynamic graph mode or not.
169 170 171
    You can enter dynamic graph mode with :ref:`api_base_dygraph_guard` api,
    or enable and disable dynamic graph mode with :ref:`api_base_dygraph_enable_dygraph`
    and :ref:`api_base_dygraph_disable_dygraph` api .
172 173

    **Note**:
174 175
        ``base.dygraph.enabled`` is the alias of ``base.in_dygraph_mode``, and
        ``base.in_dygraph_mode`` is recommended to use for now.
176 177 178 179 180 181 182

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

    Examples:
        .. code-block:: python

183
            import paddle.base as base
184

185 186 187 188
            base.enable_dygraph()  # Now we are in dygragh mode
            print(base.dygraph.enabled())  # True
            base.disable_dygraph()
            print(base.dygraph.enabled())  # False
189
    """
J
Jiabin Yang 已提交
190
    # TODO(jiabin): Make this check as in_dygraph_mode when we support default eager mode.
姜永久 已提交
191
    return framework.in_dygraph_mode()
192 193


194 195
def enable_dygraph(place=None):
    """
196 197 198 199 200

    .. note::
        Dynamic graph mode is turn ON by default since paddle 2.0.0

    This API turn OFF static graph mode. You can turn ON static graph mode by `enable_static <./disable_dygraph_en.html>`_ .
201 202

    Parameters:
203
        place(paddle.CPUPlace|paddle.CUDAPlace|str, optional): Place to run dynamic graph. Default: None. Which means that the running place will be
204 205
            determined according to the way of paddle compilation. If ``place`` is string, It can be ``cpu``, and ``gpu:x``, where ``x`` is the
            index of the GPUs.
206 207 208 209 210 211 212

    return:
        None

    Examples:
        .. code-block:: python

213 214 215 216
            import paddle
            print(paddle.in_dynamic_mode())  # True, dynamic mode is turn ON by default since paddle 2.0.0

            paddle.enable_static()
217
            print(paddle.in_dynamic_mode())  # False, Now we are in static graph mode
218 219 220

            paddle.disable_static()
            print(paddle.in_dynamic_mode())  # True, Now we are in dynamic mode
221 222

    """
223 224 225
    global global_var
    if global_var._functional_dygraph_context_manager is None:
        global_var._functional_dygraph_context_manager = guard(
226 227
            place=_get_paddle_place(place)
        )
228
        global_var._functional_dygraph_context_manager.__enter__()
229

H
hong 已提交
230 231 232
        # call disable_dygraph when Python exit
        CleanupFuncRegistrar.register(disable_dygraph)

233 234 235

def disable_dygraph():
    """
236 237 238 239 240

    .. note::
        Dynamic graph mode is turn ON by default since paddle 2.0.0

    This API turn ON static graph mode. You can turn ON static graph mode by `disable_static <./enable_dygraph_en.html>`_ .
241 242 243 244 245 246 247

    return:
        None

    Examples:
        .. code-block:: python

248 249 250 251
            import paddle
            print(paddle.in_dynamic_mode())  # True, dynamic mode is turn ON by default since paddle 2.0.0

            paddle.enable_static()
252
            print(paddle.in_dynamic_mode())  # False, Now we are in static graph mode
253 254 255

            paddle.disable_static()
            print(paddle.in_dynamic_mode())  # True, Now we are in dynamic mode
256 257

    """
258 259 260 261
    global global_var
    if global_var._functional_dygraph_context_manager is not None:
        global_var._functional_dygraph_context_manager.__exit__(*sys.exc_info())
        global_var._functional_dygraph_context_manager = None
262 263


264 265 266 267
@signature_safe_contextmanager
def _switch_tracer_mode_guard_(is_train=True):
    tracer = framework._dygraph_tracer()
    if tracer:
268 269
        has_grad = tracer._has_grad
        tracer._has_grad = is_train
270 271 272
        try:
            yield
        finally:
273
            tracer._has_grad = has_grad
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    else:
        yield


def no_grad(func=None):
    """
    :api_attr: imperative

    Create a context which disables dygraph gradient calculation.
    In this mode, the result of every computation will have `stop_gradient=True`.

    Also functions as a decorator. (Make sure to instantiate without parenthesis.)

    Examples:

     .. code-block:: python

        import numpy as np
292
        import paddle.base as base
293 294 295 296

        # use as generator

        data = np.array([[2, 3], [4, 5]]).astype('float32')
297 298 299 300
        with base.dygraph.guard():
            l0 = base.Linear(2, 2)  # l0.weight.gradient() is None
            l1 = base.Linear(2, 2)
            with base.dygraph.no_grad():
301 302
                # l1.weight.stop_gradient is False
                tmp = l1.weight * 2  # tmp.stop_gradient is True
303
            x = base.dygraph.to_variable(data)
304 305 306 307 308 309 310 311
            y = l0(x) + tmp
            o = l1(y)
            o.backward()
            print(tmp.gradient() is None)  # True
            print(l0.weight.gradient() is None)  # False

        # use as decorator

312
        @base.dygraph.no_grad
313
        def test_layer():
314
            with base.dygraph.guard():
315
                inp = np.ones([3, 1024], dtype='float32')
316 317 318
                t = base.dygraph.base.to_variable(inp)
                linear1 = base.Linear(1024, 4, bias_attr=False)
                linear2 = base.Linear(4, 4)
319 320 321 322 323 324
                ret = linear1(t)
                dy_ret = linear2(ret)

        test_layer()

    """
325 326 327 328
    if in_declarative_mode():
        warnings.warn(
            "paddle.no_grad is only supported for inference model, and not supported for training under @to_static."
        )
329 330 331 332 333 334 335 336 337 338 339 340
    if func is None:
        return _switch_tracer_mode_guard_(is_train=False)
    else:

        @decorator.decorator
        def __impl__(func, *args, **kwargs):
            with _switch_tracer_mode_guard_(is_train=False):
                return func(*args, **kwargs)

        return __impl__(func)


341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
class _DecoratorContextManager:
    """Allow a context manager to be used as a decorator"""

    def __call__(self, func):
        @decorator.decorator
        def _decorate_function(func, *args, **kwargs):
            with self:
                return func(*args, **kwargs)

        @decorator.decorator
        def _decorate_generator(func, *args, **kwargs):
            gen = func(*args, **kwargs)
            with self:
                for x in gen:
                    yield x

        if inspect.isgeneratorfunction(func):
            return _decorate_generator(func)
        else:
            return _decorate_function(func)

    def __enter__(self):
        raise NotImplementedError

    def __exit__(self, exc_type, exc_value, traceback):
        raise NotImplementedError

    def clone(self):
        # override this method if your children class takes __init__ parameters
        return self.__class__()


def is_grad_enabled():
    """
    Returns whether current dygraph gradient calculation mode is enabled.

    Returns:
        bool: True if current dygraph gradient calculation mode is enabled, otherwise false.

    Examples:
        .. code-block:: python

            import paddle

            # Dygraph gradient calculation mode is enabled by default.
            paddle.is_grad_enabled() # True

            with paddle.set_grad_enabled(False):
                paddle.is_grad_enabled() # False

            paddle.enable_static()
            paddle.is_grad_enabled() # False
    """
    tracer = framework._dygraph_tracer()
    return tracer._has_grad if tracer else False


def _set_grad_enabled(mode):
    tracer = framework._dygraph_tracer()
    if tracer:
        tracer._has_grad = mode


class set_grad_enabled(_DecoratorContextManager):
    """
    Create a context which enables or disables dygraph gradient calculation.

    Args:
        mode(bool): whether to enable (`True`), or disable (`False`) grad.

    Returns:
        None.

    Examples:
        .. code-block:: python

            import paddle
            x = paddle.to_tensor([1.], stop_gradient=False)
            is_train = False
            with paddle.set_grad_enabled(is_train):
                y = x * 2
            assert(y.stop_gradient == True)

            paddle.set_grad_enabled(True)
            y = x * 2
            assert(y.stop_gradient == False)

            paddle.set_grad_enabled(False)
            y = x * 2
            assert(y.stop_gradient == True)
    """

    def __init__(self, mode):
        self.prev = is_grad_enabled()
        _set_grad_enabled(mode)
        self.mode = mode

    def __enter__(self):
        ...

    def __exit__(self, *args):
        _set_grad_enabled(self.prev)

    def clone(self):
        return self.__class__(self.mode)


class no_grad_(_DecoratorContextManager):
449
    """
450 451
    :api_attr: imperative

452
    Create a context which disables dygraph gradient calculation.
453 454
    In this mode, the result of every computation will have `stop_gradient` set
    to `True`.
455

456
    Also functions as a decorator. (Make sure to use an instance.)
457 458 459 460 461 462

    Examples:

     .. code-block:: python

        import numpy as np
463
        import paddle
464

465 466 467
        # use as generator

        data = np.array([[2, 3], [4, 5]]).astype('float32')
468 469 470
        l0 = paddle.nn.Linear(2, 2)  # l0.weight.gradient() is None
        l1 = paddle.nn.Linear(2, 2)
        with paddle.no_grad():
471 472
            # l1.weight.stop_gradient is False
            tmp = l1.weight * 2  # tmp.stop_gradient is True
473
        x = paddle.to_tensor(data)
474 475 476 477 478
        y = l0(x) + tmp
        o = l1(y)
        o.backward()
        print(tmp.gradient() is None)  # True
        print(l0.weight.gradient() is None)  # False
479 480 481

        # use as decorator

482
        @paddle.no_grad()
483
        def test_layer():
484
            inp = np.ones([3, 1024], dtype='float32')
485 486 487
            t = paddle.to_tensor(inp)
            linear1 = paddle.nn.Linear(1024, 4, bias_attr=False)
            linear2 = paddle.nn.Linear(4, 4)
488 489
            ret = linear1(t)
            dy_ret = linear2(ret)
490 491 492 493

        test_layer()
    """

494 495 496
    def __enter__(self):
        self.prev = is_grad_enabled()
        _set_grad_enabled(False)
497

498 499
    def __exit__(self, *args):
        _set_grad_enabled(self.prev)
500

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540

class enable_grad(_DecoratorContextManager):
    """
    :api_attr: imperative

    Create a context which enable dygraph gradient calculation,
    if it has been disabled by `no_grad` or `set_grad_enabled`.

    In this mode, the result of every computation will have `stop_gradient` set
    to `False`.

    Also functions as a decorator. (Make sure to use an instance.)

    Examples:

     .. code-block:: python

        import paddle

        # use as generator

        x = paddle.to_tensor([1.], stop_gradient=False)
        with paddle.no_grad():
            with paddle.enable_grad():
                y = x * 2
        assert(y.stop_gradient == False)
        y.backward()
        assert(x.grad is not None)

        # use as decorator

        @paddle.enable_grad()
        def double(x):
            return x * 2

        with paddle.no_grad():
            z = double(x)

        assert(z.stop_gradient == False)
    """
541 542

    def __enter__(self):
543 544
        self.prev = is_grad_enabled()
        _set_grad_enabled(True)
545 546

    def __exit__(self, *args):
547
        _set_grad_enabled(self.prev)
548 549


S
rename  
sneaxiy 已提交
550
@signature_safe_contextmanager
P
Paddle CI 已提交
551
def guard(place=None):
552
    """
553 554
    :api_attr: imperative

555
    This context will create a dygraph context for dygraph to run, using python ``with`` statement.
556

557
    Parameters:
558
        place(base.CPUPlace| base.CUDAPlace|str, optional): Place to execute dygraph.
559 560 561
            If None, the running place will be determined according to the way of paddle compilation.
            If ``place`` is string, It can be ``cpu``, ``gpu:x`` and ``xpu:x``, where ``x`` is the
            index of the GPUs or XPUs. Default: None
562 563 564 565 566 567 568 569 570

    return:
        None

    Examples:

     .. code-block:: python

        import numpy as np
571
        import paddle.base as base
572

573
        with base.dygraph.guard():
574
            inp = np.ones([3, 1024], dtype='float32')
575 576 577
            t = base.dygraph.base.to_variable(inp)
            linear1 = base.Linear(1024, 4, bias_attr=False)
            linear2 = base.Linear(4, 4)
578 579
            ret = linear1(t)
            dy_ret = linear2(ret)
580 581

    """
582 583
    train = framework.Program()
    startup = framework.Program()
J
Jiabin Yang 已提交
584
    tracer = Tracer()
M
minqiyang 已提交
585

586
    if place is not None:
587
        expected_place = _get_paddle_place(place)
588 589
    else:
        expected_place = framework._current_expected_place()
M
minqiyang 已提交
590

591 592
    with framework.program_guard(train, startup):
        with framework.unique_name.guard():
L
lujun 已提交
593
            with framework._dygraph_guard(tracer):
594
                with framework._dygraph_place_guard(expected_place):
P
Paddle CI 已提交
595
                    yield
596 597


598
@framework.non_static_only
599 600 601 602 603 604 605 606 607 608
def grad(
    outputs,
    inputs,
    grad_outputs=None,
    retain_graph=None,
    create_graph=False,
    only_inputs=True,
    allow_unused=False,
    no_grad_vars=None,
):
609
    '''
Z
Zeng Jinle 已提交
610
    .. note::
611
        **This API is ONLY available in imperative mode.**
Z
Zeng Jinle 已提交
612 613 614 615

    This API computes the sum of gradients of `outputs` with respect to each `inputs` .

    Parameters:
616
        outputs (Tensor|list(Tensor)|tuple(Tensor)): the output Tensor or
617
            Tensor list/tuple of the graph to compute gradients.
618
        inputs (Tensor|list(Tensor)|tuple(Tensor)): the input Tensor or
619
            Tensor list/tuple of the graph to compute gradients. The returned
620 621 622 623 624
            values of this API are the gradients of `inputs` .
        grad_outputs (Tensor|list(Tensor|None)|tuple(Tensor|None), optional):
            initial gradient values of `outputs` . If `grad_outputs` is None,
            the initial gradient values of `outputs` would be Tensors filled with 1;
            if `grad_outputs` is not None, it must have the same length as `outputs` ,
Z
Zeng Jinle 已提交
625
            and in this case, the initial gradient value of the i-th `outputs` would
626
            be: (1) a Tensor filled with 1 when the i-th element of `grad_outputs`
Z
Zeng Jinle 已提交
627
            is None; (2) the i-th element of `grad_outputs` when the i-th element of
628
            `grad_outputs` is a Tensor. Default None.
629 630 631
        retain_graph (bool, optional): whether to retain the forward graph which
            is used to calculate the gradient. When it is True, the graph would
            be retained, in which way users can calculate backward twice for the
Z
Zeng Jinle 已提交
632
            same graph. When it is False, the graph would be freed. Default None,
633
            which means it is equal to `create_graph` .
Z
Zeng Jinle 已提交
634 635 636 637 638
        create_graph (bool, optional): whether to create the gradient graphs of
            the computing process. When it is True, higher order derivatives are
            supported to compute; when it is False, the gradient graphs of the
            computing process would be discarded. Default False.
        only_inputs (bool, optional): whether to only compute the gradients of
639 640
            `inputs` . If it is False, the gradients of all remaining leaf
            Tensors in the graph would be also computed and accumulated.
Z
Zeng Jinle 已提交
641 642
            If it is True, only the gradients of `inputs` would be computed.
            Default True. only_inputs=False is under development, and it is
643 644 645 646
            not supported yet.
        allow_unused (bool, optional): whether to raise error or return None if some
            Tensors of `inputs` are unreachable in the graph. If some Tensors of
            `inputs` are unreachable in the graph (i.e., their gradients are None),
Z
Zeng Jinle 已提交
647 648
            error would be raised if allow_unused=False, or None would be returned as
            their gradients if allow_unused=True. Default False.
649
        no_grad_vars (Tensor|list(Tensor)|tuple(Tensor)|set(Tensor), optional):
650
            the Tensors whose gradients are not needed to compute. Default None.
Z
Zeng Jinle 已提交
651 652

    Returns:
653 654
        list: a list of Tensors, whose length is the same as the Tensor number
        inside `inputs`, and the i-th returned Tensor is the sum of gradients of
Z
Zeng Jinle 已提交
655 656
        `outputs` with respect to the i-th `inputs`.

657
    Examples:
Z
Zeng Jinle 已提交
658
        .. code-block:: python
659
            :name: code-example-1
Z
Zeng Jinle 已提交
660

661
            import paddle
Z
Zeng Jinle 已提交
662 663

            def test_dygraph_grad(create_graph):
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
                x = paddle.ones(shape=[1], dtype='float32')
                x.stop_gradient = False
                y = x * x

                # Since y = x * x, dx = 2 * x
                dx = paddle.grad(
                        outputs=[y],
                        inputs=[x],
                        create_graph=create_graph,
                        retain_graph=True)[0]

                z = y + dx

                # If create_graph = False, the gradient of dx
                # would not be backpropagated. Therefore,
                # z = x * x + dx, and x.gradient() = 2 * x = 2.0

                # If create_graph = True, the gradient of dx
                # would be backpropagated. Therefore,
                # z = x * x + dx = x * x + 2 * x, and
                # x.gradient() = 2 * x + 2 = 4.0

                z.backward()
                return x.gradient()

            print(test_dygraph_grad(create_graph=False)) # [2.]
Z
Zeng Jinle 已提交
690 691 692
            print(test_dygraph_grad(create_graph=True)) # [4.]

        .. code-block:: python
693
            :name: code-example-2
Z
Zeng Jinle 已提交
694

695
            import paddle
Z
Zeng Jinle 已提交
696 697

            def test_dygraph_grad(grad_outputs=None):
698
                x = paddle.to_tensor(2.0)
Z
Zeng Jinle 已提交
699 700 701
                x.stop_gradient = False

                y1 = x * x
702
                y2 = x * 3
Z
Zeng Jinle 已提交
703 704 705 706 707 708 709 710 711 712 713

                # If grad_outputs=None, dy1 = [1], dy2 = [1].
                # If grad_outputs=[g1, g2], then:
                #    - dy1 = [1] if g1 is None else g1
                #    - dy2 = [1] if g2 is None else g2

                # Since y1 = x * x, dx = 2 * x * dy1.
                # Since y2 = x * 3, dx = 3 * dy2.
                # Therefore, the final result would be:
                # dx = 2 * x * dy1 + 3 * dy2 = 4 * dy1 + 3 * dy2.

714
                dx = paddle.grad(
715
                    outputs=[y1, y2],
Z
Zeng Jinle 已提交
716 717 718 719 720
                    inputs=[x],
                    grad_outputs=grad_outputs)[0]

                return dx.numpy()

721
            grad_value = paddle.to_tensor(4.0)
Z
Zeng Jinle 已提交
722 723 724 725
            # dy1 = [1], dy2 = [1]
            print(test_dygraph_grad(None)) # [7.]

            # dy1 = [1], dy2 = [4]
726
            print(test_dygraph_grad([None, grad_value])) # [16.]
Z
Zeng Jinle 已提交
727 728

            # dy1 = [4], dy2 = [1]
729
            print(test_dygraph_grad([grad_value, None])) # [19.]
Z
Zeng Jinle 已提交
730 731

            # dy1 = [3], dy2 = [4]
732
            grad_y1 = paddle.to_tensor(3.0)
733
            print(test_dygraph_grad([grad_y1, grad_value])) # [24.]
734
    '''
735 736 737 738
    if in_declarative_mode():
        # In dy2static context, we call static interface `gradients`
        # to calculate grads.
        from paddle.static import gradients
739

740 741 742 743
        declarative_unsupport_argument_warning(
            "paddle.grad",
            ["retain_graph", "create_grad", "only_inputs", "allow_unused"],
            [retain_graph, create_graph, only_inputs, allow_unused],
744 745
            [None, False, True, False],
        )
746
        return gradients(outputs, inputs, grad_outputs, no_grad_vars)
Z
Zeng Jinle 已提交
747

748 749 750 751 752 753
    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:
W
wanghuancoder 已提交
754 755 756
                assert isinstance(
                    each_var, core.eager.Tensor
                ), "Elements of {} must be Tensor".format(name)
757 758
            return in_out_list
        else:
W
wanghuancoder 已提交
759 760 761
            assert isinstance(
                in_out_list, core.eager.Tensor
            ), "{} must be Tensor or list of Tensor".format(name)
762 763 764 765 766 767 768 769 770 771 772
            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:
W
wanghuancoder 已提交
773 774 775
                assert isinstance(
                    each_var, core.eager.Tensor
                ), "grad_outputs must be None, a Variable or a list containing None or Variables"
776 777 778 779 780
    else:
        grad_outputs = []

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

Z
Zeng Jinle 已提交
784 785
    if no_grad_vars is None:
        no_grad_vars = []
W
wanghuancoder 已提交
786
    elif isinstance(no_grad_vars, core.eager.Tensor):
Z
Zeng Jinle 已提交
787
        no_grad_vars = [no_grad_vars]
788 789
    elif isinstance(no_grad_vars, core.eager.Tensor):
        no_grad_vars = [no_grad_vars]
Z
Zeng Jinle 已提交
790 791 792
    elif isinstance(no_grad_vars, (list, tuple, set)):
        no_grad_vars = list(no_grad_vars)
        for var in no_grad_vars:
W
wanghuancoder 已提交
793 794 795
            assert isinstance(
                var, core.eager.Tensor
            ), "no_grad_vars can only contains Tensor"
796
    else:
797 798 799
        raise AssertionError(
            "no_grad_vars must be None, Tensor or list/tuple/set of Tensors"
        )
800 801 802

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

Z
Zeng Jinle 已提交
803 804 805
    if retain_graph is None:
        retain_graph = create_graph

806 807 808
    assert isinstance(
        retain_graph, bool
    ), "retain_graph must be None, True or False"
Z
Zeng Jinle 已提交
809 810 811 812 813 814

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

    assert isinstance(only_inputs, bool), "only_inputs must be True or False"
    assert only_inputs, "only_inputs=False is not supported yet"

815 816 817 818 819 820 821 822 823 824
    return core.eager.run_partial_grad(
        outputs,
        inputs,
        grad_outputs,
        retain_graph,
        create_graph,
        only_inputs,
        allow_unused,
        no_grad_vars,
    )
825 826


827
@framework.dygraph_only
828
def to_variable(value, name=None, zero_copy=None, dtype=None):
829
    r"""
830 831
    :api_attr: imperative

832
    The API will create a ``Variable`` object from
C
chentianyu03 已提交
833
    tuple, list, numpy\.ndarray or Variable object.
834

835
    Parameters:
836
        value(tuple|list|ndarray|Variable|Tensor): Initial data.
C
chentianyu03 已提交
837
            Can be a list, tuple, NumPy ndarray, Variable, Tensor.
838 839
            The shape can be multi-dimensional. The data type is one of
            numpy\.{float16, float32, float64, int16, int32, int64,
840
            uint8, uint16, complex64, complex128}.
841 842 843 844 845
        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` .
        zero_copy(bool, optional): Whether to share memory with the input numpy
            array. This parameter only works with CPUPlace and will be set to
L
Leo Chen 已提交
846
            True when it is None. Default: None. (Note: zero_copy is discarded temporally for some reason.)
847
        dtype(str, optional): The desired data type of returned ``Variable`` .
848
            Can be 'bool' , 'float16' , 'float32' , 'float64' , 'int8' , 'int16' ,
849
            'int32' , 'int64' , 'uint8' . Default: None.
850

851
    Returns:
852 853 854
        Variable : If ``value`` is a tuple/list/numpy\.ndarray object,
            return ``Tensor`` created from the corresponding numpy\.ndarray object, which has
            same data type and shape with ``value``.
855

856 857 858 859 860 861

    Examples:

     .. code-block:: python

        import numpy as np
862
        import paddle.base as base
863

864
        with base.dygraph.guard(base.CPUPlace()):
865
            x = np.ones([2, 2], np.float32)
866
            y = base.dygraph.to_variable(x, zero_copy=False)
867 868
            x[0][0] = -1
            y[0][0].numpy()  # array([1.], dtype=float32)
869
            y = base.dygraph.to_variable(x)
870 871
            x[0][0] = 0
            y[0][0].numpy()  # array([0.], dtype=float32)
872
            c = np.array([2+1j, 2])
873
            z = base.dygraph.to_variable(c)
874 875
            z.numpy() # array([2.+1.j, 2.+0.j])
            z.dtype # 'complex128'
876

877
            y = base.dygraph.to_variable([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
878 879
            y.shape     # [3L, 2L]

880
            y = base.dygraph.to_variable(((0.1, 1.2), (2.2, 3.1), (4.9, 5.2)), dtype='int32')
881 882
            y.shape     # [3L, 2L]

883
    """
884 885 886 887 888 889 890 891 892
    support_type = (
        list,
        tuple,
        np.ndarray,
        core.eager.Tensor,
        framework.Variable,
        core.Tensor,
        core.LoDTensor,
    )
893 894
    if not isinstance(value, support_type):
        raise TypeError(
895
            "The type of 'value' in base.dygraph.to_variable must be %s, but received %s."
896 897
            % (support_type, type(value))
        )
W
wanghuancoder 已提交
898
    if isinstance(value, (core.eager.Tensor, framework.Variable)):
899 900
        return value
    elif isinstance(value, (core.Tensor, core.LoDTensor)):
W
wanghuancoder 已提交
901
        return core.eager.Tensor(value)
902
    else:
903 904 905 906
        if isinstance(
            framework._current_expected_place(), framework.core.CPUPlace
        ):
            # TODO(zhiqiu): we found two problems when enable zero_copy on CPUPlace.
907
            # (1): eigen requires 16-bytes alignments, but the data of numpy array may not statisfy.
L
Leo Chen 已提交
908 909 910 911 912 913 914 915 916
            # Details: https://eigen.tuxfamily.org/dox/group__TopicUnalignedArrayAssert.html
            # (2): when used in flask framework, it may result in hang.
            # Details: https://github.com/PaddlePaddle/Paddle/issues/26635
            # So, we temporally diable the zero_copy strategy.
            if zero_copy == True:
                warnings.warn(
                    "Currently, zero_copy is not supported, and it will be discarded."
                )
                zero_copy = False
917
        else:
918 919 920
            assert (
                not zero_copy
            ), "zero_copy mode can only be used with CPUPlace"
921 922 923 924 925 926 927 928 929

        if not isinstance(value, np.ndarray):
            value = np.array(value)

        if dtype is not None:
            dtype = convert_dtype(dtype)
            if value.dtype != dtype:
                value = value.astype(dtype)

W
wanghuancoder 已提交
930 931 932 933 934 935 936 937
        return core.eager.Tensor(
            value,
            framework._current_expected_place(),
            False,
            zero_copy,
            name if name else None,
            True,
        )