-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding the squared L2 norm operator for L2 regularization (#5030)
* Adding the L2 loss operator for L2 regularization * Renaming l2_loss op to squared_l2_norm_op * Addressing code review feedback
- Loading branch information
1 parent
b68f2d2
commit b0a267c
Showing
4 changed files
with
195 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. | ||
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 "paddle/operators/squared_l2_norm_op.h" | ||
|
||
namespace paddle { | ||
namespace operators { | ||
|
||
using framework::Tensor; | ||
|
||
class SquaredL2NormOp : public framework::OperatorWithKernel { | ||
public: | ||
using framework::OperatorWithKernel::OperatorWithKernel; | ||
|
||
void InferShape(framework::InferShapeContext* ctx) const override { | ||
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should be not null."); | ||
PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) should be not null."); | ||
|
||
ctx->SetOutputDim("Out", {1}); | ||
} | ||
}; | ||
|
||
class SquaredL2NormGradOp : public framework::OperatorWithKernel { | ||
public: | ||
using framework::OperatorWithKernel::OperatorWithKernel; | ||
|
||
void InferShape(framework::InferShapeContext* ctx) const override { | ||
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should be not null."); | ||
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")), | ||
"Input(Out@GRAD) should be not null."); | ||
PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")), | ||
"Output(X@GRAD) should be not null."); | ||
|
||
ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X")); | ||
} | ||
}; | ||
|
||
class SquaredL2NormOpMaker : public framework::OpProtoAndCheckerMaker { | ||
public: | ||
SquaredL2NormOpMaker(framework::OpProto* proto, | ||
framework::OpAttrChecker* op_checker) | ||
: framework::OpProtoAndCheckerMaker(proto, op_checker) { | ||
AddInput("X", "(Tensor) The input of squared_l2_norm op."); | ||
AddOutput("Out", "(Float) The output of squared_l2_norm op."); | ||
AddComment(R"DOC( | ||
SquaredL2Norm Operator. | ||
Computes the squared L2 norm of a tensor. | ||
Out = sum (X ** 2) | ||
)DOC"); | ||
} | ||
}; | ||
|
||
} // namespace operators | ||
} // namespace paddle | ||
|
||
namespace ops = paddle::operators; | ||
REGISTER_OP(squared_l2_norm, ops::SquaredL2NormOp, ops::SquaredL2NormOpMaker, | ||
squared_l2_norm_grad, ops::SquaredL2NormGradOp); | ||
REGISTER_OP_CPU_KERNEL( | ||
squared_l2_norm, | ||
ops::SquaredL2NormKernel<paddle::platform::CPUPlace, float>); | ||
REGISTER_OP_CPU_KERNEL( | ||
squared_l2_norm_grad, | ||
ops::SquaredL2NormGradKernel<paddle::platform::CPUPlace, float>); |
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,24 @@ | ||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. | ||
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. */ | ||
|
||
#define EIGEN_USE_GPU | ||
#include "paddle/operators/squared_l2_norm_op.h" | ||
|
||
namespace ops = paddle::operators; | ||
REGISTER_OP_GPU_KERNEL( | ||
squared_l2_norm, | ||
ops::SquaredL2NormKernel<paddle::platform::GPUPlace, float>); | ||
REGISTER_OP_GPU_KERNEL( | ||
squared_l2_norm_grad, | ||
ops::SquaredL2NormGradKernel<paddle::platform::GPUPlace, float>); |
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,64 @@ | ||
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. | ||
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. */ | ||
|
||
#pragma once | ||
#include "paddle/framework/eigen.h" | ||
#include "paddle/framework/op_registry.h" | ||
|
||
namespace paddle { | ||
namespace operators { | ||
|
||
// Out = sum(square(X)) | ||
template <typename Place, typename T> | ||
class SquaredL2NormKernel : public framework::OpKernel<T> { | ||
public: | ||
void Compute(const framework::ExecutionContext &context) const override { | ||
const framework::Tensor *X = context.Input<framework::Tensor>("X"); | ||
framework::Tensor *Out = context.Output<framework::Tensor>("Out"); | ||
Out->mutable_data<T>(context.GetPlace()); | ||
|
||
auto x = framework::EigenVector<T>::Flatten(*X); | ||
auto out = framework::EigenVector<T>::Flatten(*Out); | ||
auto place = context.GetEigenDevice<Place>(); | ||
|
||
out.device(place) = x.square().sum(); | ||
} | ||
}; | ||
|
||
// dX = X | ||
template <typename Place, typename T> | ||
class SquaredL2NormGradKernel : public framework::OpKernel<T> { | ||
public: | ||
void Compute(const framework::ExecutionContext &context) const override { | ||
const framework::Tensor *X = context.Input<framework::Tensor>("X"); | ||
const framework::Tensor *dOut = | ||
context.Input<framework::Tensor>(framework::GradVarName("Out")); | ||
PADDLE_ENFORCE(dOut->numel() == 1, | ||
"Squared L2 Norm Gradient should be scalar"); | ||
framework::Tensor *dX = | ||
context.Output<framework::Tensor>(framework::GradVarName("X")); | ||
dX->mutable_data<T>(context.GetPlace()); | ||
|
||
auto x = framework::EigenVector<T>::Flatten(*X); | ||
auto dout = framework::EigenVector<T>::Flatten(*dOut); | ||
auto dx = framework::EigenVector<T>::Flatten(*dX); | ||
auto place = context.GetEigenDevice<Place>(); | ||
|
||
Eigen::DSizes<int, 1> x_dsize(X->numel()); | ||
dx.device(place) = (dout.broadcast(x_dsize) * x) * static_cast<T>(2.0); | ||
} | ||
}; | ||
|
||
} // namespace operators | ||
} // namespace paddle |
29 changes: 29 additions & 0 deletions
29
python/paddle/v2/framework/tests/test_squared_l2_norm_op.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,29 @@ | ||
import numpy as np | ||
import unittest | ||
from numpy import linalg as LA | ||
from op_test import OpTest | ||
|
||
|
||
class TestL2LossOp(OpTest): | ||
"""Test squared_l2_norm | ||
""" | ||
|
||
def setUp(self): | ||
self.op_type = "squared_l2_norm" | ||
self.max_relative_error = 0.05 | ||
|
||
X = np.random.uniform(-1, 1, (13, 19)).astype("float32") | ||
X[np.abs(X) < self.max_relative_error] = 0.1 | ||
self.inputs = {'X': X} | ||
self.outputs = {'Out': np.square(LA.norm(X))} | ||
|
||
def test_check_output(self): | ||
self.check_output() | ||
|
||
def test_check_grad(self): | ||
self.check_grad( | ||
['X'], 'Out', max_relative_error=self.max_relative_error) | ||
|
||
|
||
if __name__ == "__main__": | ||
unittest.main() |