From 3ea6899f8bfe13acb776bb5883426b85497ec675 Mon Sep 17 00:00:00 2001 From: wangchaochaohu Date: Fri, 10 Apr 2020 15:46:38 +0800 Subject: [PATCH] API(fluid.layers.array_read/array_write) error message enhancement (#23568) --- python/paddle/fluid/layers/control_flow.py | 9 +++++++++ .../tests/unittests/test_array_read_write_op.py | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/python/paddle/fluid/layers/control_flow.py b/python/paddle/fluid/layers/control_flow.py index 7aa90e271ac..437f5e2fc35 100755 --- a/python/paddle/fluid/layers/control_flow.py +++ b/python/paddle/fluid/layers/control_flow.py @@ -1314,7 +1314,15 @@ def array_write(x, i, array=None): array.append(x) return array + check_variable_and_dtype(i, 'i', ['int64'], 'array_write') + check_type(x, 'x', (Variable), 'array_write') helper = LayerHelper('array_write', **locals()) + if array is not None: + if not isinstance( + array, + Variable) or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY: + raise TypeError( + "array should be tensor array vairable in array_write Op") if array is None: array = helper.create_variable( name="{0}.out".format(helper.name), @@ -1686,6 +1694,7 @@ def array_read(array, i): i = i.numpy()[0] return array[i] + check_variable_and_dtype(i, 'i', ['int64'], 'array_read') helper = LayerHelper('array_read', **locals()) if not isinstance( array, diff --git a/python/paddle/fluid/tests/unittests/test_array_read_write_op.py b/python/paddle/fluid/tests/unittests/test_array_read_write_op.py index 3d3a68ac6cf..add465d6c9b 100644 --- a/python/paddle/fluid/tests/unittests/test_array_read_write_op.py +++ b/python/paddle/fluid/tests/unittests/test_array_read_write_op.py @@ -21,6 +21,7 @@ import paddle.fluid.layers as layers from paddle.fluid.executor import Executor from paddle.fluid.backward import append_backward from paddle.fluid.framework import default_main_program +from paddle.fluid import compiler, Program, program_guard import numpy @@ -125,5 +126,19 @@ class TestArrayReadWrite(unittest.TestCase): self.assertAlmostEqual(1.0, g_out_sum_dygraph, delta=0.1) +class TestArrayReadWriteOpError(unittest.TestCase): + def test_errors(self): + with program_guard(Program(), Program()): + #for ci coverage + x1 = numpy.random.randn(2, 4).astype('int32') + x2 = fluid.layers.fill_constant(shape=[1], dtype='int32', value=1) + x3 = numpy.random.randn(2, 4).astype('int32') + + self.assertRaises( + TypeError, fluid.layers.array_read, array=x1, i=x2) + self.assertRaises( + TypeError, fluid.layers.array_write, array=x1, i=x2, out=x3) + + if __name__ == '__main__': unittest.main() -- GitLab