From 9a2c1aedccedea3ee5130c6a662676c498d7b430 Mon Sep 17 00:00:00 2001 From: wawltor Date: Tue, 9 Jun 2020 20:18:08 +0800 Subject: [PATCH] Fix the elementwise_div op broadcast failed in some shape Fix the bug for elementwise_div op, when the first var is scalar; Use the shape 1 replace the -1 in shape. --- python/paddle/fluid/layers/math_op_patch.py | 12 +++++++++--- .../tests/unittests/test_elementwise_div_op.py | 13 +++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/python/paddle/fluid/layers/math_op_patch.py b/python/paddle/fluid/layers/math_op_patch.py index 12bd0d95190..fc2555e7c27 100644 --- a/python/paddle/fluid/layers/math_op_patch.py +++ b/python/paddle/fluid/layers/math_op_patch.py @@ -98,17 +98,23 @@ def monkey_patch_variable(): block = current_block(ref_var) var = create_new_tmp_var(block, dtype) batch_dim = -1 + out_shape = [] for i, d in enumerate(ref_var.shape): if d < 0: - batch_dim = i - break + if batch_dim < 0: + batch_dim = i + out_shape.append(d) + else: + out_shape.append(1) + else: + out_shape.append(d) assert batch_dim != -1 block.append_op( type='fill_constant_batch_size_like', outputs={'Out': [var]}, inputs={'Input': [ref_var]}, attrs={ - 'shape': ref_var.shape, + 'shape': out_shape, 'value': value, 'input_dim_idx': batch_dim, 'output_dim_idx': batch_dim diff --git a/python/paddle/fluid/tests/unittests/test_elementwise_div_op.py b/python/paddle/fluid/tests/unittests/test_elementwise_div_op.py index c96f9db22b8..91e0dc2b738 100644 --- a/python/paddle/fluid/tests/unittests/test_elementwise_div_op.py +++ b/python/paddle/fluid/tests/unittests/test_elementwise_div_op.py @@ -227,6 +227,19 @@ class TestElementwiseDivOpFp16(ElementwiseDivOp): ['X'], 'Out', max_relative_error=1, no_grad_set=set('Y')) +class TestElementwiseDivBroadcast(unittest.TestCase): + def test_shape_with_batch_sizes(self): + with fluid.program_guard(fluid.Program()): + x_var = fluid.data( + name='x', dtype='float32', shape=[None, 3, None, None]) + one = 2. + out = one / x_var + exe = fluid.Executor(fluid.CPUPlace()) + x = np.random.uniform(0.1, 0.6, (1, 3, 32, 32)).astype("float32") + out_result, = exe.run(feed={'x': x}, fetch_list=[out]) + self.assertEqual((out_result == (2 / x)).all(), True) + + class TestDivOp(unittest.TestCase): def test_out(self): with fluid.program_guard(fluid.Program()): -- GitLab