Skip to content

Commit f9066e6

Browse files
authored
Update the demo code and the doc of varbase.backward. (#26506)
* update the demo code and the doc of varbase.backward. * update the doc of the fake interface `paddle.fluid.Variable`. * remove BackwardStrategy.
1 parent 1c898b6 commit f9066e6

36 files changed

Lines changed: 148 additions & 294 deletions

paddle/fluid/imperative/backward_strategy.h

Lines changed: 0 additions & 33 deletions
This file was deleted.

paddle/fluid/imperative/basic_engine.cc

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,13 @@
3030
#include "paddle/fluid/operators/math/math_function.h"
3131
#include "paddle/fluid/platform/profiler.h"
3232

33+
DECLARE_bool(sort_sum_gradient);
34+
3335
namespace paddle {
3436
namespace imperative {
3537

36-
void BasicEngine::Init(VarBase* var, const detail::BackwardStrategy& strategy,
37-
bool retain_graph) {
38-
backward_strategy_ = strategy;
38+
void BasicEngine::Init(VarBase* var, bool retain_graph) {
39+
sorted_sum_gradient_ = FLAGS_sort_sum_gradient;
3940
retain_graph_ = retain_graph;
4041
init_node_ = var->GradVarBase()->GradNode();
4142
var->GradVarBase()->ClearGradNode();
@@ -105,7 +106,7 @@ void BasicEngine::PrepareGradAccumulators(const OpBase& op) {
105106

106107
auto& accumulator = accumulators_[var.get()];
107108
if (!accumulator) {
108-
if (backward_strategy_.sorted_sum_gradient_) {
109+
if (sorted_sum_gradient_) {
109110
accumulator.reset(new SortedGradientAccumulator(var.get()));
110111
} else {
111112
accumulator.reset(new EagerGradientAccumulator(var.get()));

paddle/fluid/imperative/basic_engine.h

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
#include <unordered_map>
1919
#include <utility>
2020
#include <vector>
21-
#include "paddle/fluid/imperative/backward_strategy.h"
2221
#include "paddle/fluid/imperative/engine.h"
2322
#include "paddle/fluid/imperative/gradient_accumulator.h"
2423

@@ -30,8 +29,7 @@ class OpBase;
3029

3130
class BasicEngine : public Engine {
3231
public:
33-
void Init(VarBase* var, const detail::BackwardStrategy& strategy,
34-
bool retain_graph = false);
32+
void Init(VarBase* var, bool retain_graph = false);
3533

3634
void Execute() override;
3735

@@ -46,7 +44,7 @@ class BasicEngine : public Engine {
4644

4745
private:
4846
std::shared_ptr<GradOpNode> init_node_;
49-
detail::BackwardStrategy backward_strategy_;
47+
bool sorted_sum_gradient_;
5048
std::unordered_map<GradOpNode*, size_t> node_deps_;
5149
std::unordered_map<VariableWrapper*, std::unique_ptr<GradientAccumulator>>
5250
accumulators_;

paddle/fluid/imperative/partial_grad_engine.cc

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@
3333
#include "paddle/fluid/platform/profiler.h"
3434
#include "paddle/fluid/string/string_helper.h"
3535

36+
DECLARE_bool(sort_sum_gradient);
37+
3638
namespace paddle {
3739
namespace imperative {
3840

@@ -529,8 +531,7 @@ class PartialGradTask {
529531
const std::vector<std::shared_ptr<VarBase>> &output_targets,
530532
const std::vector<std::shared_ptr<VarBase>> &output_grads,
531533
const std::vector<std::shared_ptr<VarBase>> &no_grad_vars,
532-
const platform::Place &place,
533-
const detail::BackwardStrategy &strategy, bool create_graph,
534+
const platform::Place &place, bool create_graph,
534535
bool retain_graph, bool allow_unused, bool only_inputs);
535536

536537
std::vector<std::shared_ptr<VarBase>> Run();
@@ -577,23 +578,22 @@ class PartialGradTask {
577578
bool retain_graph_;
578579
bool allow_unused_;
579580
bool only_inputs_;
580-
detail::BackwardStrategy strategy_;
581+
bool sorted_sum_gradient_{FLAGS_sort_sum_gradient};
581582
};
582583

583584
PartialGradTask::PartialGradTask(
584585
const std::vector<std::shared_ptr<VarBase>> &input_targets,
585586
const std::vector<std::shared_ptr<VarBase>> &output_targets,
586587
const std::vector<std::shared_ptr<VarBase>> &output_grads,
587588
const std::vector<std::shared_ptr<VarBase>> &no_grad_vars,
588-
const platform::Place &place, const detail::BackwardStrategy &strategy,
589-
bool create_graph, bool retain_graph, bool allow_unused, bool only_inputs) {
589+
const platform::Place &place, bool create_graph, bool retain_graph,
590+
bool allow_unused, bool only_inputs) {
590591
input_targets_ = input_targets;
591592
place_ = place;
592593
create_graph_ = create_graph;
593594
retain_graph_ = retain_graph;
594595
allow_unused_ = allow_unused;
595596
only_inputs_ = only_inputs;
596-
strategy_ = strategy;
597597

598598
PADDLE_ENFORCE_EQ(only_inputs_, true,
599599
platform::errors::Unimplemented(
@@ -981,7 +981,7 @@ void PartialGradTask::PrepareInitialGradientAccumulators(const OpBase *op) {
981981

982982
if (!accumulator) {
983983
accumulator.reset(new GradientAccumulationInfo(
984-
var, strategy_.sorted_sum_gradient_, create_graph_));
984+
var, sorted_sum_gradient_, create_graph_));
985985
}
986986

987987
accumulator->IncreaseTotalRefCnt();
@@ -1033,11 +1033,11 @@ PartialGradEngine::PartialGradEngine(
10331033
const std::vector<std::shared_ptr<VarBase>> &output_targets,
10341034
const std::vector<std::shared_ptr<VarBase>> &output_grads,
10351035
const std::vector<std::shared_ptr<VarBase>> &no_grad_vars,
1036-
const platform::Place &place, const detail::BackwardStrategy &strategy,
1037-
bool create_graph, bool retain_graph, bool allow_unused, bool only_inputs)
1036+
const platform::Place &place, bool create_graph, bool retain_graph,
1037+
bool allow_unused, bool only_inputs)
10381038
: task_(new PartialGradTask(input_targets, output_targets, output_grads,
1039-
no_grad_vars, place, strategy, create_graph,
1040-
retain_graph, allow_unused, only_inputs)) {}
1039+
no_grad_vars, place, create_graph, retain_graph,
1040+
allow_unused, only_inputs)) {}
10411041

10421042
PartialGradEngine::~PartialGradEngine() { Clear(); }
10431043

paddle/fluid/imperative/partial_grad_engine.h

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616

1717
#include <memory>
1818
#include <vector>
19-
#include "paddle/fluid/imperative/backward_strategy.h"
2019
#include "paddle/fluid/imperative/engine.h"
2120
#include "paddle/fluid/platform/place.h"
2221

@@ -33,8 +32,7 @@ class PartialGradEngine : public Engine {
3332
const std::vector<std::shared_ptr<VarBase>> &output_targets,
3433
const std::vector<std::shared_ptr<VarBase>> &output_grads,
3534
const std::vector<std::shared_ptr<VarBase>> &no_grad_vars,
36-
const platform::Place &place,
37-
const detail::BackwardStrategy &strategy, bool create_graph,
35+
const platform::Place &place, bool create_graph,
3836
bool retain_graph, bool allow_unused, bool only_inputs);
3937

4038
~PartialGradEngine();

paddle/fluid/imperative/tests/test_tracer.cc

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -240,9 +240,8 @@ TEST(test_tracer, test_trace_op_with_multi_device_inputs) {
240240
framework::AttributeMap reduce_attr_map;
241241
tracer.TraceOp("reduce_sum", reduce_in, reduce_out, reduce_attr_map,
242242
gpu_place, true);
243-
detail::BackwardStrategy back_st;
244243
imperative::BasicEngine engine;
245-
engine.Init(reduce_sum_out.get(), back_st);
244+
engine.Init(reduce_sum_out.get());
246245
engine.Execute();
247246

248247
framework::LoDTensor rlt;
@@ -356,9 +355,8 @@ TEST(test_tracer, test_var_without_grad_var) {
356355
ASSERT_EQ(y_in->GradVarBase()->GradOpNum(), 0UL);
357356
ASSERT_EQ(vout->GradVarBase()->GradOpNum(), 1UL);
358357

359-
detail::BackwardStrategy back_st;
360358
imperative::BasicEngine engine;
361-
engine.Init(vout.get(), back_st);
359+
engine.Init(vout.get());
362360
engine.Execute();
363361

364362
// check the grad

paddle/fluid/platform/flags.cc

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,3 +508,16 @@ DEFINE_int32(
508508
"summary will be shown."
509509
"If FLAGS_call_stack_level == 2, the python stack, c++ stack, and "
510510
"error message summary will be shown.");
511+
512+
/**
513+
* Debug related FLAG
514+
* Name: sort_sum_gradient
515+
* Since Version: 2.0.0
516+
* Value Range: bool, default=false
517+
* Example:
518+
* Note: If True, gradients are summed by the reverse order of
519+
* the forward execution sequence.
520+
*/
521+
DEFINE_bool(sort_sum_gradient, false,
522+
"Sum gradients by the reverse order of "
523+
"the forward execution sequence.");

paddle/fluid/pybind/global_value_getter_setter.cc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ DECLARE_bool(enable_rpc_profiler);
3838
DECLARE_int32(multiple_of_cupti_buffer_size);
3939
DECLARE_bool(reader_queue_speed_test_mode);
4040
DECLARE_int32(call_stack_level);
41+
DECLARE_bool(sort_sum_gradient);
4142
// device management
4243
DECLARE_int32(paddle_num_threads);
4344
// executor
@@ -340,7 +341,7 @@ static void RegisterGlobalVarGetterSetter() {
340341
REGISTER_PUBLIC_GLOBAL_VAR(
341342
FLAGS_eager_delete_tensor_gb, FLAGS_enable_parallel_graph,
342343
FLAGS_allocator_strategy, FLAGS_use_system_allocator, FLAGS_check_nan_inf,
343-
FLAGS_call_stack_level, FLAGS_cpu_deterministic,
344+
FLAGS_call_stack_level, FLAGS_sort_sum_gradient, FLAGS_cpu_deterministic,
344345
FLAGS_enable_rpc_profiler, FLAGS_multiple_of_cupti_buffer_size,
345346
FLAGS_reader_queue_speed_test_mode, FLAGS_pe_profile_fname,
346347
FLAGS_print_sub_graph_dir, FLAGS_fraction_of_cpu_memory_to_use,

paddle/fluid/pybind/imperative.cc

Lines changed: 7 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ limitations under the License. */
3030

3131
#include "paddle/fluid/imperative/all_reduce.h"
3232
#include "paddle/fluid/imperative/amp_auto_cast.h"
33-
#include "paddle/fluid/imperative/backward_strategy.h"
3433
#include "paddle/fluid/imperative/basic_engine.h"
3534
#include "paddle/fluid/imperative/data_loader.h"
3635
#include "paddle/fluid/imperative/layer.h"
@@ -507,50 +506,6 @@ void BindImperative(py::module *m_ptr) {
507506
[]() { memory::allocation::MemoryMapFdSet::Instance().Clear(); });
508507
#endif
509508

510-
py::class_<imperative::detail::BackwardStrategy> backward_strategy(
511-
m, "BackwardStrategy", R"DOC(
512-
513-
BackwardStrategy is a descriptor of how to run the backward process.
514-
515-
**Note**:
516-
**This API is only available in** `Dygraph <../../user_guides/howto/dygraph/DyGraph.html>`_ **Mode**
517-
518-
Attribute:
519-
**sort_sum_gradient**:
520-
521-
If framework will sum the gradient by the reverse order of trace. eg. x_var ( :ref:`api_guide_Variable` ) will be the input of multiple OP such as :ref:`api_fluid_layers_scale` , this attr will decide if framework will sum gradient of `x_var` by the reverse order.
522-
523-
By Default: False
524-
525-
Examples:
526-
.. code-block:: python
527-
528-
import numpy as np
529-
import paddle.fluid as fluid
530-
531-
x = np.ones([2, 2], np.float32)
532-
with fluid.dygraph.guard():
533-
x_var = fluid.dygraph.to_variable(x)
534-
sums_inputs = []
535-
# x_var will be multi-scales' input here
536-
for _ in range(10):
537-
sums_inputs.append(fluid.layers.scale(x_var))
538-
ret2 = fluid.layers.sums(sums_inputs)
539-
loss2 = fluid.layers.reduce_sum(ret2)
540-
backward_strategy = fluid.dygraph.BackwardStrategy()
541-
backward_strategy.sort_sum_gradient = True
542-
loss2.backward(backward_strategy)
543-
)DOC");
544-
backward_strategy.def(py::init())
545-
.def_property("sort_sum_gradient",
546-
[](const imperative::detail::BackwardStrategy &self) {
547-
return self.sorted_sum_gradient_;
548-
},
549-
[](imperative::detail::BackwardStrategy &self,
550-
bool sorted_sum_gradient) {
551-
self.sorted_sum_gradient_ = sorted_sum_gradient;
552-
});
553-
554509
m.def("start_imperative_gperf_profiler",
555510
[]() { imperative::StartProfile(); });
556511

@@ -745,21 +700,18 @@ void BindImperative(py::module *m_ptr) {
745700
inputs2.append(tmp)
746701
ret2 = fluid.layers.sums(inputs2)
747702
loss2 = fluid.layers.reduce_sum(ret2)
748-
backward_strategy = fluid.dygraph.BackwardStrategy()
749-
backward_strategy.sort_sum_gradient = True
750-
loss2.backward(backward_strategy)
703+
loss2.backward()
751704
print(loss2.gradient())
752705
loss2.clear_gradient()
753706
print("After clear {}".format(loss2.gradient()))
754707
)DOC")
755708
.def("_run_backward",
756-
[](imperative::VarBase &self,
757-
const imperative::detail::BackwardStrategy &bckst,
758-
const imperative::Tracer &tracer, bool retain_graph) {
709+
[](imperative::VarBase &self, const imperative::Tracer &tracer,
710+
bool retain_graph) {
759711
// TODO(jiabin): when we impl more backward execution we can
760712
// select them
761713
auto *engine = tracer.GetEngine();
762-
engine->Init(&self, bckst, retain_graph);
714+
engine->Init(&self, retain_graph);
763715
VLOG(3) << "Start backward";
764716
engine->Execute();
765717
VLOG(3) << "Finish backward";
@@ -1024,13 +976,11 @@ void BindImperative(py::module *m_ptr) {
1024976
&output_targets,
1025977
const std::vector<std::shared_ptr<imperative::VarBase>> &output_grads,
1026978
const std::vector<std::shared_ptr<imperative::VarBase>> &no_grad_vars,
1027-
const platform::Place &place,
1028-
const imperative::detail::BackwardStrategy &strategy,
1029-
bool create_graph, bool retain_graph, bool allow_unused,
1030-
bool only_inputs) {
979+
const platform::Place &place, bool create_graph, bool retain_graph,
980+
bool allow_unused, bool only_inputs) {
1031981
imperative::PartialGradEngine engine(
1032982
input_targets, output_targets, output_grads, no_grad_vars, place,
1033-
strategy, create_graph, retain_graph, allow_unused, only_inputs);
983+
create_graph, retain_graph, allow_unused, only_inputs);
1034984
engine.Execute();
1035985
return engine.GetResult();
1036986
},

python/paddle/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,6 @@
225225
from .framework import CUDAPlace #DEFINE_ALIAS
226226
from .framework import CUDAPinnedPlace #DEFINE_ALIAS
227227

228-
from .framework import BackwardStrategy #DEFINE_ALIAS
229228
from .framework import to_variable #DEFINE_ALIAS
230229
from .framework import grad #DEFINE_ALIAS
231230
from .framework import no_grad #DEFINE_ALIAS

0 commit comments

Comments
 (0)