diff --git a/python/paddle/fluid/layers/nn.py b/python/paddle/fluid/layers/nn.py index e68166f4148dfda2d69835cd3888c18734ceea5e..3136fca1095ad959d7d9e3a0da423781ea70b014 100644 --- a/python/paddle/fluid/layers/nn.py +++ b/python/paddle/fluid/layers/nn.py @@ -326,6 +326,8 @@ def fc(input, mul_results = [] for input_var, param_attr in helper.iter_inputs_and_params(): input_shape = input_var.shape + if num_flatten_dims == -1: + num_flatten_dims = len(input_shape) - 1 param_shape = [ reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1) ] + [size] diff --git a/python/paddle/fluid/tests/unittests/test_fc_op.py b/python/paddle/fluid/tests/unittests/test_fc_op.py index 1105dcee7b448d1e7481c628d4864a53614e1304..e5a7e6c702aec114968adb7fb23309c9d944559d 100644 --- a/python/paddle/fluid/tests/unittests/test_fc_op.py +++ b/python/paddle/fluid/tests/unittests/test_fc_op.py @@ -16,7 +16,9 @@ import unittest import numpy as np from op_test import OpTest import paddle.fluid as fluid -from paddle.fluid import Program, program_guard +from paddle.fluid import Program, program_guard, core + +SEED = 2020 def fc_refer(matrix, with_bias, with_relu=False): @@ -131,6 +133,35 @@ class TestFCOpWithPadding(TestFCOp): self.matrix = MatrixGenerate(1, 4, 3, 128, 128, 2) +class TestFcOp_NumFlattenDims_NegOne(unittest.TestCase): + def test_api(self): + startup_program = Program() + main_program = Program() + startup_program.random_seed = SEED + main_program.random_seed = SEED + + with program_guard(main_program, startup_program): + input = np.random.random([2, 2, 25]).astype("float32") + x = fluid.layers.data( + name="x", + shape=[2, 2, 25], + append_batch_size=False, + dtype="float32") + + out_1 = fluid.layers.fc(input=x, size=1, num_flatten_dims=-1) + out_2 = fluid.layers.fc(input=x, size=1, num_flatten_dims=2) + + place = fluid.CPUPlace() if not core.is_compiled_with_cuda( + ) else fluid.CUDAPlace(0) + exe = fluid.Executor(place=place) + exe.run(startup_program) + res_1, res_2 = exe.run(main_program, + feed={"x": input}, + fetch_list=[out_1, out_2]) + + assert np.array_equal(res_1, res_2) + + class TestFCOpError(unittest.TestCase): def test_errors(self): with program_guard(Program(), Program()):