-
Notifications
You must be signed in to change notification settings - Fork 5.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[NPU] Support npu kernel for amp_check_finite_and_unscale_npu op #31457
Merged
zhiqiu
merged 10 commits into
PaddlePaddle:ascendrc
from
xymyeah:check_finite_unscale_npu_op_pick
Mar 12, 2021
Merged
Changes from 7 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
88a1bc5
Support npu kernel for amp_check_finite_and_unscale_npu op
xymyeah 58a69a2
support EnforceNotMet exception
xymyeah 1053395
Merge branch 'ascendrc' of https://github.com/PaddlePaddle/Paddle int…
xymyeah 4bf03e4
fix exception bug
xymyeah 4e5f2dd
modify python unittest
xymyeah 5f8f86f
precommit
xymyeah a713d6f
update c++ unittest
xymyeah 2db1116
Merge branch 'ascendrc' of https://github.com/PaddlePaddle/Paddle int…
xymyeah a0b34b5
fix review
xymyeah 922a036
fix review
xymyeah File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
118 changes: 118 additions & 0 deletions
118
paddle/fluid/operators/amp/check_finite_and_unscale_op_npu.cc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
/* Copyright (c) 2021 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. */ | ||
|
||
#include <memory> | ||
#include <string> | ||
|
||
#include "paddle/fluid/framework/tensor_util.h" | ||
#include "paddle/fluid/operators/amp/check_finite_and_unscale_op.h" | ||
#include "paddle/fluid/operators/npu_op_runner.h" | ||
|
||
namespace paddle { | ||
namespace operators { | ||
|
||
using Tensor = framework::Tensor; | ||
|
||
template <typename T> | ||
class CheckFiniteAndUnscaleNPUKernel : public framework::OpKernel<T> { | ||
public: | ||
void Compute(const framework::ExecutionContext& ctx) const { | ||
const auto xs = ctx.MultiInput<framework::Tensor>("X"); | ||
const auto* scale = ctx.Input<framework::Tensor>("Scale"); | ||
auto outs = ctx.MultiOutput<framework::Tensor>("Out"); | ||
auto* found_inf = ctx.Output<framework::Tensor>("FoundInfinite"); | ||
|
||
found_inf->mutable_data<bool>(ctx.GetPlace()); | ||
|
||
bool found_inf_data = false; | ||
|
||
auto stream = | ||
ctx.template device_context<paddle::platform::NPUDeviceContext>() | ||
.stream(); | ||
|
||
// step1: inverse scale(RealDiv) | ||
Tensor const_tensor; | ||
const_tensor.mutable_data<T>({1}, ctx.GetPlace()); | ||
TensorFromVector(std::vector<T>{static_cast<T>(1.0)}, ctx.device_context(), | ||
&const_tensor); | ||
|
||
ctx.template device_context<paddle::platform::NPUDeviceContext>().Wait(); | ||
|
||
// Inverse(1.0/scale) | ||
Tensor* tmp_inverse_out = const_cast<Tensor*>(scale); | ||
Tensor inverse_out(scale->type()); | ||
inverse_out.Resize(scale->dims()); | ||
inverse_out.mutable_data<T>(ctx.GetPlace()); | ||
auto runner_inverse = | ||
NpuOpRunner("Div", {const_tensor, *scale}, {inverse_out}, {}); | ||
runner_inverse.Run(stream); | ||
tmp_inverse_out = &inverse_out; | ||
|
||
size_t x_size = xs.size(); | ||
for (size_t i = 0; i < x_size; ++i) { | ||
const auto* x = xs[i]; | ||
auto* out = outs[i]; | ||
out->mutable_data<T>(ctx.GetPlace()); | ||
|
||
// step2: CheckNumerics | ||
// CheckNumerics runs on the Ascend AI CPU, which delivers poor | ||
// performance. | ||
Tensor* tmp_checkxout = const_cast<Tensor*>(x); | ||
Tensor check_xout(x->type()); | ||
check_xout.Resize(x->dims()); | ||
check_xout.mutable_data<T>(ctx.GetPlace()); | ||
try { | ||
auto runner_checknumerics = | ||
NpuOpRunner("CheckNumerics", {*x}, {check_xout}, | ||
{{"message", std::string("check_nan_and_inf")}}); | ||
runner_checknumerics.Run(stream); | ||
tmp_checkxout = &check_xout; | ||
} catch (platform::EnforceNotMet& exception) { | ||
LOG(WARNING) << "[check_nan_and_inf] detected contains NaN or INF!!!"; | ||
tmp_checkxout = nullptr; | ||
found_inf_data = true; | ||
} | ||
|
||
if (tmp_checkxout != nullptr) { | ||
// MatMul | ||
auto runner_matmul = | ||
NpuOpRunner("Mul", {*x, *tmp_inverse_out}, {*out}, {}); | ||
runner_matmul.Run(stream); | ||
|
||
// set found_inf to true | ||
if (found_inf_data) { | ||
Tensor found_inf_tensor; | ||
found_inf_tensor.Resize({1}); | ||
bool* is_found_inf = | ||
found_inf_tensor.mutable_data<bool>(paddle::platform::CPUPlace()); | ||
*is_found_inf = true; | ||
framework::TensorCopy(found_inf_tensor, ctx.GetPlace(), found_inf); | ||
} | ||
} else { | ||
// ZerosLike | ||
auto runner_zeroslike = NpuOpRunner("ZerosLike", {*x}, {*out}, {}); | ||
runner_zeroslike.Run(stream); | ||
} // end if | ||
} // end for | ||
} | ||
}; | ||
|
||
} // namespace operators | ||
} // namespace paddle | ||
|
||
namespace ops = paddle::operators; | ||
namespace plat = paddle::platform; | ||
REGISTER_OP_NPU_KERNEL(check_finite_and_unscale, | ||
ops::CheckFiniteAndUnscaleNPUKernel<float>, | ||
ops::CheckFiniteAndUnscaleNPUKernel<plat::float16>); |
131 changes: 131 additions & 0 deletions
131
paddle/fluid/operators/amp/check_finite_and_unscale_op_npu_test.cc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/* Copyright (c) 2021 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. */ | ||
|
||
#ifndef _WIN32 | ||
#include <unistd.h> | ||
#endif | ||
|
||
#include <algorithm> | ||
#include <cstdlib> | ||
#include <memory> | ||
#include <random> | ||
#include "gtest/gtest.h" | ||
#include "paddle/fluid/framework/op_registry.h" | ||
#include "paddle/fluid/framework/operator.h" | ||
#include "paddle/fluid/framework/program_desc.h" | ||
#include "paddle/fluid/operators/math/math_function.h" | ||
#include "paddle/fluid/platform/enforce.h" | ||
|
||
namespace f = paddle::framework; | ||
namespace p = paddle::platform; | ||
namespace m = paddle::operators::math; | ||
|
||
using Tensor = paddle::framework::Tensor; | ||
|
||
USE_OP(check_finite_and_unscale); | ||
USE_OP_DEVICE_KERNEL(check_finite_and_unscale, NPU); | ||
|
||
struct InputVars { | ||
std::string name; | ||
f::LoDTensor *tensor; | ||
}; | ||
|
||
template <typename T> | ||
void Compare(f::Scope *scope, const p::DeviceContext &ctx) { | ||
const f::DDim dims = f::make_ddim({2, 2}); | ||
auto place = ctx.GetPlace(); | ||
|
||
// init input | ||
std::vector<InputVars> input_names = { | ||
{"x", scope->Var("x")->GetMutable<f::LoDTensor>()}, | ||
{"x1", scope->Var("x1")->GetMutable<f::LoDTensor>()}}; | ||
|
||
auto *scale = scope->Var("scale")->GetMutable<f::LoDTensor>(); | ||
|
||
// init output | ||
auto *out = scope->Var("out")->GetMutable<f::LoDTensor>(); | ||
auto *out1 = scope->Var("out1")->GetMutable<f::LoDTensor>(); | ||
auto *found_inf = scope->Var("found_inf")->GetMutable<f::LoDTensor>(); | ||
|
||
// Initialize input data | ||
const int num_inputs = input_names.size(); | ||
size_t numel = static_cast<size_t>(f::product(dims)); | ||
|
||
for (int i = 0; i < num_inputs; ++i) { | ||
std::vector<T> init_xs; | ||
for (size_t j = 0; j < numel; ++j) { | ||
if (j == 0) { | ||
init_xs.push_back(static_cast<T>(NAN)); | ||
} else { | ||
init_xs.push_back(static_cast<T>(j + 1)); | ||
} | ||
} | ||
f::TensorFromVector(init_xs, ctx, input_names[i].tensor); | ||
input_names[i].tensor->Resize(dims); | ||
} | ||
|
||
f::TensorFromVector(std::vector<T>{static_cast<T>(0.5)}, ctx, scale); | ||
|
||
ctx.Wait(); | ||
|
||
// run | ||
f::AttributeMap attrs; | ||
auto op = f::OpRegistry::CreateOp( | ||
"check_finite_and_unscale", {{"X", {"x", "x1"}}, {"Scale", {"scale"}}}, | ||
{{"Out", {"out", "out1"}}, {"FoundInfinite", {"found_inf"}}}, attrs); | ||
op->Run(*scope, place); | ||
ctx.Wait(); | ||
|
||
// out0 | ||
std::vector<T> out_vec; | ||
f::TensorToVector(*out, ctx, &out_vec); | ||
EXPECT_EQ(out_vec.size(), static_cast<size_t>(4)); | ||
for (size_t j = 0; j < out_vec.size(); ++j) { | ||
VLOG(3) << "out_vec[" << j << "]:" << out_vec[j]; | ||
} | ||
|
||
ctx.Wait(); | ||
|
||
// out0 | ||
std::vector<T> out1_vec; | ||
f::TensorToVector(*out1, ctx, &out1_vec); | ||
EXPECT_EQ(out1_vec.size(), static_cast<size_t>(4)); | ||
for (size_t j = 0; j < out1_vec.size(); ++j) { | ||
VLOG(3) << "out1_vec[" << j << "]:" << out1_vec[j]; | ||
} | ||
|
||
ctx.Wait(); | ||
|
||
// out found_inf | ||
Tensor found_inf_tensor; | ||
found_inf_tensor.Resize({1}); | ||
bool *is_finite_data = | ||
found_inf_tensor.mutable_data<bool>(paddle::platform::CPUPlace()); | ||
f::TensorCopy(*found_inf, place, &found_inf_tensor); | ||
EXPECT_FALSE(*is_finite_data); | ||
|
||
ctx.Wait(); | ||
} | ||
|
||
TEST(check_finite_and_unscale, NPU_fp32) { | ||
f::Scope scope; | ||
p::NPUDeviceContext ctx(p::NPUPlace(0)); | ||
Compare<float>(&scope, ctx); | ||
} | ||
|
||
TEST(check_finite_and_unscale, NPU_fp16) { | ||
f::Scope scope; | ||
p::NPUDeviceContext ctx(p::NPUPlace(0)); | ||
Compare<p::float16>(&scope, ctx); | ||
} |
123 changes: 123 additions & 0 deletions
123
python/paddle/fluid/tests/unittests/npu/test_amp_check_finite_and_scale_op_npu.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
# Copyright (c) 2020 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. | ||
|
||
import unittest | ||
import numpy as np | ||
from op_test import OpTest, skip_check_grad_ci | ||
import paddle | ||
import paddle.fluid as fluid | ||
|
||
paddle.enable_static() | ||
|
||
|
||
@unittest.skipIf(not paddle.is_compiled_with_npu(), | ||
"core is not compiled with NPU") | ||
class TestCheckFiniteAndUnscaleOp(OpTest): | ||
def setUp(self): | ||
self.set_npu() | ||
self.op_type = "check_finite_and_unscale" | ||
self.place = paddle.NPUPlace(0) | ||
self.init_dtype() | ||
x = np.random.random((1024, 1024)).astype(self.dtype) | ||
scale = np.random.random((1)).astype(self.dtype) | ||
|
||
self.inputs = {'X': [('x0', x)], 'Scale': scale} | ||
self.outputs = { | ||
'FoundInfinite': np.array([0]), | ||
'Out': [('out0', x / scale)], | ||
} | ||
|
||
def set_npu(self): | ||
self.__class__.use_npu = True | ||
|
||
def init_kernel_type(self): | ||
self.use_mkldnn = False | ||
|
||
def init_dtype(self): | ||
self.dtype = np.float32 | ||
|
||
def test_check_output(self): | ||
self.check_output_with_place(self.place, check_dygraph=False) | ||
|
||
|
||
@unittest.skipIf(not paddle.is_compiled_with_npu(), | ||
"core is not compiled with NPU") | ||
class TestCheckFiniteAndUnscaleOpWithNan(OpTest): | ||
def setUp(self): | ||
self.set_npu() | ||
self.op_type = "check_finite_and_unscale" | ||
self.place = paddle.NPUPlace(0) | ||
self.init_dtype() | ||
x = np.random.random((1024, 1024)).astype(self.dtype) | ||
x[128][128] = np.nan | ||
scale = np.random.random((1)).astype(self.dtype) | ||
|
||
self.inputs = {'X': [('x0', x)], 'Scale': scale} | ||
self.outputs = { | ||
'FoundInfinite': np.array([1]), | ||
'Out': [('out0', x)], | ||
} | ||
|
||
def set_npu(self): | ||
self.__class__.use_npu = True | ||
|
||
def init_kernel_type(self): | ||
self.use_mkldnn = False | ||
|
||
def init_dtype(self): | ||
self.dtype = np.float32 | ||
|
||
def test_check_output(self): | ||
# When input contains nan, do not check the output, | ||
# since the output may be nondeterministic and will be discarded. | ||
self.check_output_with_place( | ||
self.place, check_dygraph=False, no_check_set=['Out']) | ||
|
||
|
||
@unittest.skipIf(not paddle.is_compiled_with_npu(), | ||
"core is not compiled with NPU") | ||
class TestCheckFiniteAndUnscaleOpWithInf(OpTest): | ||
def setUp(self): | ||
self.set_npu() | ||
self.op_type = "check_finite_and_unscale" | ||
self.place = paddle.NPUPlace(0) | ||
self.init_dtype() | ||
x = np.random.random((1024, 1024)).astype(self.dtype) | ||
x[128][128] = np.inf | ||
scale = np.random.random((1)).astype(self.dtype) | ||
|
||
self.inputs = {'X': [('x0', x)], 'Scale': scale} | ||
self.outputs = { | ||
'FoundInfinite': np.array([1]), | ||
'Out': [('out0', x)], | ||
} | ||
|
||
def set_npu(self): | ||
self.__class__.use_npu = True | ||
|
||
def init_kernel_type(self): | ||
self.use_mkldnn = False | ||
|
||
def init_dtype(self): | ||
self.dtype = np.float32 | ||
|
||
def test_check_output(self): | ||
# When input contains inf, do not check the output, | ||
# since the output may be nondeterministic and will be discarded. | ||
self.check_output_with_place( | ||
self.place, check_dygraph=False, no_check_set=['Out']) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -85,4 +85,4 @@ def test_check_output(self): | |
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() | ||
unittest.main() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No need changes.