| 57 | } |
| 58 | |
| 59 | TEST(RetainGrad, HookBeforeRetainGrad) { |
| 60 | eager_test::InitEnv(phi::CPUPlace()); |
| 61 | |
| 62 | // Prepare Inputs |
| 63 | std::vector<paddle::Tensor> target_tensors; |
| 64 | phi::DDim ddim = common::make_ddim({4, 16, 16, 32}); |
| 65 | |
| 66 | // Create Target Tensor |
| 67 | paddle::Tensor tensor = |
| 68 | eager_test::CreateTensorWithValue(ddim, |
| 69 | phi::CPUPlace(), |
| 70 | phi::DataType::FLOAT32, |
| 71 | phi::DataLayout::NCHW, |
| 72 | 1.0 /*value*/, |
| 73 | false /*is_leaf*/); |
| 74 | target_tensors.emplace_back(std::move(tensor)); |
| 75 | paddle::Tensor& target_tensor = target_tensors[0]; |
| 76 | |
| 77 | // Create ScaleNode |
| 78 | auto scale_node_ptr = std::make_shared<GradNodeScale>(1, 1); |
| 79 | scale_node_ptr->SetAttributes_scale(5.0 /*scale*/); |
| 80 | |
| 81 | // Set grad in/out meta for node0 |
| 82 | scale_node_ptr->SetDefaultGradInOutMeta(); |
| 83 | |
| 84 | // Connect Input Tensor and ScaleNode via AutoGradMeta |
| 85 | // Apply RetainGrad |
| 86 | { |
| 87 | // ScaleNode Hook: +3 |
| 88 | |
| 89 | auto auto_grad_meta = std::make_shared<AutogradMeta>(); |
| 90 | auto_grad_meta->SetGradNode( |
| 91 | std::dynamic_pointer_cast<GradNodeBase>(scale_node_ptr)); |
| 92 | auto_grad_meta->SetSingleOutRankWithSlot(0, 0); |
| 93 | auto_grad_meta->SetStopGradient(false); |
| 94 | target_tensor.set_autograd_meta( |
| 95 | std::dynamic_pointer_cast<paddle::AbstractAutogradMeta>( |
| 96 | auto_grad_meta)); |
| 97 | |
| 98 | egr_utils_api::RegisterGradientHookForTensor(target_tensor, hook_function); |
| 99 | egr_utils_api::RetainGradForTensor( |
| 100 | target_tensor); // result: 1.0 + 3.0 = 4.0 |
| 101 | egr_utils_api::RetainGradForTensor( |
| 102 | target_tensor); // result: 1.0 + 3.0 = 4.0 |
| 103 | } |
| 104 | |
| 105 | // Retain Grad for leaf tensor1 |
| 106 | paddle::Tensor leaf_tensor = paddle::Tensor(); |
| 107 | { |
| 108 | // AccumulationNode Hook: +3 |
| 109 | auto tmp_tensor0 = paddle::Tensor(); |
| 110 | auto auto_grad_meta = EagerUtils::autograd_meta(&tmp_tensor0); |
| 111 | |
| 112 | auto acc_node_ptr = std::make_shared<GradNodeAccumulation>(tmp_tensor0); |
| 113 | |
| 114 | auto_grad_meta->SetStopGradient(false); |
| 115 | auto_grad_meta->SetGradNode(acc_node_ptr); |
| 116 | auto_grad_meta->SetSingleOutRankWithSlot(0, 0); |
nothing calls this directly
no test coverage detected