diff --git a/paddle/fluid/operators/lod_array_length_op.cc b/paddle/fluid/operators/lod_array_length_op.cc index 2553b9fb22793ebfc2eda5f8f6783357de179ffb..49e8cbbbaabe75987196f27d1713be389233373f 100644 --- a/paddle/fluid/operators/lod_array_length_op.cc +++ b/paddle/fluid/operators/lod_array_length_op.cc @@ -60,8 +60,9 @@ CPU and the length of LoDTensorArray should be used as control variables. class LoDArrayLengthInferShape : public framework::InferShapeBase { public: void operator()(framework::InferShapeContext *context) const override { - PADDLE_ENFORCE(context->HasInput("X")); - PADDLE_ENFORCE(context->HasOutput("Out")); + OP_INOUT_CHECK(context->HasInput("X"), "Input", "X", "LDArrayLength"); + OP_INOUT_CHECK(context->HasOutput("Out"), "Output", "Out", + "LoDArrayLength"); context->SetOutputDim("Out", {1}); } }; diff --git a/python/paddle/fluid/layers/control_flow.py b/python/paddle/fluid/layers/control_flow.py index 07211bdd0c95d60e9cdfe97a15e40f9c472e424b..74e4206824c9eb009b990ba12bf849332c19cb45 100755 --- a/python/paddle/fluid/layers/control_flow.py +++ b/python/paddle/fluid/layers/control_flow.py @@ -1782,12 +1782,19 @@ def array_length(array): # so the dtype value is typeid(int64_t).Name(), which is 'x' on MacOS, 'l' on Linux, # and '__int64' on Windows. They both represent 64-bit integer variables. """ + if in_dygraph_mode(): assert isinstance( array, list), "The 'array' in array_write must be a list in dygraph mode" return len(array) + if not isinstance( + array, + Variable) or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY: + raise TypeError( + "array should be tensor array vairable in array_length Op") + helper = LayerHelper('array_length', **locals()) tmp = helper.create_variable_for_type_inference(dtype='int64') tmp.stop_gradient = True diff --git a/python/paddle/fluid/tests/unittests/test_lod_array_length_op.py b/python/paddle/fluid/tests/unittests/test_lod_array_length_op.py index 15485df5ac440f2ff666ca27ef8e8bcc5df866c0..363b474bfbb15bf5661c32bc9987fe15cdd768e2 100644 --- a/python/paddle/fluid/tests/unittests/test_lod_array_length_op.py +++ b/python/paddle/fluid/tests/unittests/test_lod_array_length_op.py @@ -18,6 +18,8 @@ import unittest import paddle.fluid.layers as layers from paddle.fluid.executor import Executor import paddle.fluid.core as core +import paddle.fluid as fluid +from paddle.fluid import compiler, Program, program_guard import numpy @@ -33,5 +35,14 @@ class TestLoDArrayLength(unittest.TestCase): self.assertEqual(11, result[0]) +class TestLoDArrayLengthOpError(unittest.TestCase): + def test_errors(self): + with program_guard(Program(), Program()): + #for ci coverage + x1 = numpy.random.randn(2, 4).astype('int32') + + self.assertRaises(TypeError, fluid.layers.array_length, array=x1) + + if __name__ == '__main__': unittest.main()