Skip to content

Commit

Permalink
[Eager] Support numpy.ndarry in CastNumpy2Scalar (#42136)
Browse files Browse the repository at this point in the history
  • Loading branch information
veyron95 authored Apr 25, 2022
1 parent 1178f15 commit 4a16d5c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
15 changes: 14 additions & 1 deletion paddle/fluid/pybind/eager_utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1025,7 +1025,20 @@ paddle::experimental::Scalar CastNumpy2Scalar(PyObject* obj,
PyTypeObject* type = obj->ob_type;
auto type_name = std::string(type->tp_name);
VLOG(1) << "type_name: " << type_name;
if (type_name == "numpy.float64") {
if (type_name == "numpy.ndarray" && PySequence_Check(obj)) {
PyObject* item = nullptr;
item = PySequence_GetItem(obj, 0);
if (PyObject_CheckFloatOrToFloat(&item)) {
float value = static_cast<float>(PyFloat_AsDouble(item));
return paddle::experimental::Scalar(value);
} else {
PADDLE_THROW(platform::errors::InvalidArgument(
"%s(): argument (position %d) is numpy.ndarry, the inner elements "
"must be "
"numpy.float32/float64 now, but got %s",
op_type, arg_pos + 1, type_name)); // NOLINT
}
} else if (type_name == "numpy.float64") {
double value = CastPyArg2Double(obj, op_type, arg_pos);
return paddle::experimental::Scalar(value);
} else if (type_name == "numpy.float32") {
Expand Down
8 changes: 7 additions & 1 deletion python/paddle/fluid/tests/unittests/test_bfgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import paddle.nn.functional as F

from paddle.incubate.optimizer.functional.bfgs import minimize_bfgs
from paddle.fluid.framework import _test_eager_guard

from paddle.fluid.framework import _enable_legacy_dygraph
_enable_legacy_dygraph()
Expand Down Expand Up @@ -120,7 +121,7 @@ def func(x):
results = test_static_graph(func, x0, dtype='float64')
self.assertTrue(np.allclose(0.8, results[2]))

def test_rosenbrock(self):
def func_rosenbrock(self):
# The Rosenbrock function is a standard optimization test case.
a = np.random.random(size=[1]).astype('float32')
minimum = [a.item(), (a**2).item()]
Expand All @@ -139,6 +140,11 @@ def func(position):
results = test_dynamic_graph(func, x0)
self.assertTrue(np.allclose(minimum, results[2]))

def test_rosenbrock(self):
with _test_eager_guard():
self.func_rosenbrock()
self.func_rosenbrock()

def test_exception(self):
def func(x):
return paddle.dot(x, x)
Expand Down

0 comments on commit 4a16d5c

Please sign in to comment.