Skip to content
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

add gradient test framework #3226

Merged
merged 28 commits into from
Aug 8, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
70c42fa
init grad op checker
jacquesqiao Aug 4, 2017
44a95e0
can run
jacquesqiao Aug 4, 2017
8fde952
add GradeChecker class
jacquesqiao Aug 4, 2017
25a0c13
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
jacquesqiao Aug 4, 2017
ccc4869
use get_numeric_gradient
jacquesqiao Aug 4, 2017
3dc5f9f
refine code
jacquesqiao Aug 4, 2017
602ea1a
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
jacquesqiao Aug 7, 2017
d280694
add softmax and cross entropy auto grad test
jacquesqiao Aug 7, 2017
d98bca7
use close to judge op_grad and numeric_grad
jacquesqiao Aug 7, 2017
646aedf
add cpu and gpu compare
jacquesqiao Aug 7, 2017
cd93735
add comments
jacquesqiao Aug 7, 2017
c33de52
add support_gpu
jacquesqiao Aug 7, 2017
200ca59
fix allclose
jacquesqiao Aug 7, 2017
22bdd99
fix name error and symplify code
jacquesqiao Aug 7, 2017
e054765
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
jacquesqiao Aug 7, 2017
c578c40
Merge branch 'is_support_gpu' of https://github.com/jacquesqiao/Paddl…
jacquesqiao Aug 7, 2017
d383542
optimize gradient checker
jacquesqiao Aug 7, 2017
6d87260
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
jacquesqiao Aug 7, 2017
59dd91b
add test_cross_entropy_op
jacquesqiao Aug 7, 2017
0701341
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
jacquesqiao Aug 7, 2017
c46b85e
update gradient_checker.py
jacquesqiao Aug 7, 2017
6c18e43
optimize code
jacquesqiao Aug 8, 2017
cfa981f
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
jacquesqiao Aug 8, 2017
e2f3fda
use random.uniform instead of random.random
jacquesqiao Aug 8, 2017
10e8449
fix type bug
jacquesqiao Aug 8, 2017
f39be65
optimize check_grad
jacquesqiao Aug 8, 2017
cba3821
put SupportGPU into OperatorBase
jacquesqiao Aug 8, 2017
b1d78f2
typo
jacquesqiao Aug 8, 2017
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions paddle/framework/pybind.cc
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ void ExposeOperator(ClassType &m) {
[](const typename ClassType::type &op) -> std::vector<std::string> {
return op.outputs_;
})
.def("inputs",
[](const typename ClassType::type &op) -> std::vector<std::string> {
return op.inputs_;
})
.def("__str__", &ClassType::type::DebugString);
}

Expand Down
66 changes: 66 additions & 0 deletions python/paddle/v2/framework/tests/op_test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,69 @@ def test_all(self):

obj.test_all = test_all
return obj


def create_grad_op(op_type):
func = getattr(creation.op_creations, op_type, None)
assert (func is not None)

kwargs = dict()
for in_name in func.all_input_args:
kwargs[in_name] = in_name
for out_name in func.all_output_args:
kwargs[out_name] = out_name
op = func(**kwargs)
backward_op = core.Operator.backward(op, set())
return backward_op


class GradOpTestMeta(type):
"""
Operator Test ClassMeta.

It injects `test_all` method into user's OperatorTest class, to make Python
unittest module run that method.

The `test_all` read what value is stored in `self`. It use self's values to
create and run a operator, and check whether that op is OK or not.

See `test_add_two_op` for example usage.
"""

def __new__(cls, name, bases, attrs):
obj = super(GradOpTestMeta, cls).__new__(cls, name, bases, attrs)

def test_all(self):
backward_op = create_grad_op(self.type)

scope = core.Scope()

places = []
places.append(core.CPUPlace())
if core.is_compile_gpu():
places.append(core.GPUPlace(0))

for place in places:
for in_name in backward_op.inputs():
if hasattr(self, in_name):
var = scope.new_var(in_name).get_tensor()
arr = getattr(self, in_name)
var.set_dims(arr.shape)
var.set(arr, place)

for out_name in backward_op.outputs():
if hasattr(self, out_name):
scope.new_var(out_name).get_tensor()

backward_op.infer_shape(scope)

ctx = core.DeviceContext.create(place)
backward_op.run(scope, ctx)

for out_name in backward_op.outputs():
actual = numpy.array(scope.find_var(out_name).get_tensor())
expect = getattr(self, out_name)
numpy.testing.assert_almost_equal(actual, expect, decimal=3)

obj.test_all = test_all
return obj
28 changes: 27 additions & 1 deletion python/paddle/v2/framework/tests/test_softmax_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import paddle.v2.framework.core as core
import paddle.v2.framework.create_op_creation_methods as creation

from op_test_util import OpTestMeta
from op_test_util import OpTestMeta, GradOpTestMeta


def stable_softmax(x):
Expand All @@ -23,6 +23,32 @@ def setUp(self):
self.Y = np.apply_along_axis(stable_softmax, 1, self.X)


class TestSoftmaxGradOp1(unittest.TestCase):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does the class name have suffix 1? Should we give it a more specific name?

__metaclass__ = GradOpTestMeta

def setUp(self):
batch_size = 3
class_num = 5

# Initialize X and add 1e-2 for numerical stability
Y = np.random.rand(batch_size, class_num).astype(np.float32)
Y = Y + 1e-2
dY = np.random.rand(batch_size, class_num).astype(np.float32)

# Reference implementation of cross entropy with soft labels
def label_softmax_grad(Y, dY):
dX = Y * 0.0
for i in range(batch_size):
d = np.dot(Y[i, :], dY[i, :])
dX[i, :] = Y[i, :] * (dY[i, :] - d)
return dX

self.type = "softmax"
setattr(self, "Y", Y)
setattr(self, "Y@GRAD", dY)
setattr(self, "X@GRAD", label_softmax_grad(Y, dY))


class TestSoftmaxGradOp(unittest.TestCase):
def test_softmax_grad(self):
op = creation.op_creations.softmax(X="X", Y="Y")
Expand Down