test_beam_search_op.py 14.4 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Y
Yan Chunwei 已提交
15
import unittest
16

Y
Yan Chunwei 已提交
17
import numpy as np
18 19

import paddle
20
import paddle.fluid as fluid
21
import paddle.fluid.core as core
22
from paddle.fluid.framework import Program, program_guard
23
from paddle.fluid.op import Operator
Y
Yan Chunwei 已提交
24 25 26 27 28 29 30 31 32


def create_tensor(scope, name, np_data):
    tensor = scope.var(name).get_tensor()
    tensor.set(np_data, core.CPUPlace())
    return tensor


class BeamSearchOpTester(unittest.TestCase):
33 34
    """unittest of beam_search_op"""

Y
Yan Chunwei 已提交
35 36 37
    def setUp(self):
        self.scope = core.Scope()
        self._create_ids()
38
        self._create_pre_scores()
Y
Yan Chunwei 已提交
39 40
        self._create_scores()
        self._create_pre_ids()
P
pangyoki 已提交
41
        self.set_outputs()
42 43 44
        self.scope.var('selected_ids').get_tensor()
        self.scope.var('selected_scores').get_tensor()
        self.scope.var('parent_idx').get_tensor()
Y
Yan Chunwei 已提交
45 46

    def test_run(self):
47 48 49 50 51 52 53 54 55 56 57 58 59 60
        op = Operator(
            'beam_search',
            pre_ids='pre_ids',
            pre_scores='pre_scores',
            ids='ids',
            scores='scores',
            selected_ids='selected_ids',
            selected_scores='selected_scores',
            parent_idx='parent_idx',
            level=0,
            beam_size=self.beam_size,
            end_id=0,
            is_accumulated=self.is_accumulated,
        )
D
dzhwinter 已提交
61
        op.run(self.scope, core.CPUPlace())
Y
Yan Chunwei 已提交
62
        selected_ids = self.scope.find_var("selected_ids").get_tensor()
63
        selected_scores = self.scope.find_var("selected_scores").get_tensor()
64
        parent_idx = self.scope.find_var("parent_idx").get_tensor()
65 66 67 68 69 70
        np.testing.assert_allclose(
            np.array(selected_ids), self.output_ids, rtol=1e-05
        )
        np.testing.assert_allclose(
            np.array(selected_scores), self.output_scores, rtol=1e-05
        )
P
pangyoki 已提交
71
        self.assertEqual(selected_ids.lod(), self.output_lod)
72 73 74
        np.testing.assert_allclose(
            np.array(parent_idx), self.output_parent_idx, rtol=1e-05
        )
Y
Yan Chunwei 已提交
75 76

    def _create_pre_ids(self):
77
        np_data = np.array([[1, 2, 3, 4]], dtype='int64')
78 79 80 81 82
        tensor = create_tensor(self.scope, 'pre_ids', np_data)

    def _create_pre_scores(self):
        np_data = np.array([[0.1, 0.2, 0.3, 0.4]], dtype='float32')
        tensor = create_tensor(self.scope, 'pre_scores', np_data)
Y
Yan Chunwei 已提交
83 84

    def _create_ids(self):
85
        self.lod = [[0, 2, 4], [0, 1, 2, 3, 4]]
86 87 88
        np_data = np.array(
            [[4, 2, 5], [2, 1, 3], [3, 5, 2], [8, 2, 1]], dtype='int64'
        )
Y
Yan Chunwei 已提交
89 90 91 92
        tensor = create_tensor(self.scope, "ids", np_data)
        tensor.set_lod(self.lod)

    def _create_scores(self):
93 94 95 96 97 98 99 100 101
        np_data = np.array(
            [
                [0.5, 0.3, 0.2],
                [0.6, 0.3, 0.1],
                [0.9, 0.5, 0.1],
                [0.7, 0.5, 0.1],
            ],
            dtype='float32',
        )
Y
Yan Chunwei 已提交
102 103 104
        tensor = create_tensor(self.scope, "scores", np_data)
        tensor.set_lod(self.lod)

P
pangyoki 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    def set_outputs(self):
        self.beam_size = 2
        self.is_accumulated = True
        self.output_ids = np.array([4, 2, 3, 8])[:, np.newaxis]
        self.output_scores = np.array([0.5, 0.6, 0.9, 0.7])[:, np.newaxis]
        self.output_lod = [[0, 2, 4], [0, 1, 2, 3, 4]]
        self.output_parent_idx = np.array([0, 1, 2, 3])


class BeamSearchOpTester2(BeamSearchOpTester):
    def _create_pre_ids(self):
        np_data = np.array([[1], [2], [3], [4]], dtype='int64')
        tensor = create_tensor(self.scope, 'pre_ids', np_data)

    def _create_pre_scores(self):
        np_data = np.array([[0.1, 0.2, 0.3, 0.4]], dtype='float32')
        tensor = create_tensor(self.scope, 'pre_scores', np_data)

    def _create_ids(self):
        self.lod = [[0, 2, 4], [0, 1, 2, 3, 4]]
        np_data = np.array([[4, 2], [7, 3], [3, 5], [8, 1]], dtype='int64')
        tensor = create_tensor(self.scope, "ids", np_data)
        tensor.set_lod(self.lod)

    def _create_scores(self):
130 131 132 133 134 135 136 137 138
        np_data = np.array(
            [
                [0.6, 0.9],
                [0.5, 0.3],
                [0.9, 0.5],
                [0.1, 0.7],
            ],
            dtype='float32',
        )
P
pangyoki 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
        tensor = create_tensor(self.scope, "scores", np_data)
        tensor.set_lod(self.lod)

    def set_outputs(self):
        self.beam_size = 2
        self.is_accumulated = True
        self.output_ids = np.array([2, 4, 3, 1])[:, np.newaxis]
        self.output_scores = np.array([0.9, 0.6, 0.9, 0.7])[:, np.newaxis]
        self.output_lod = [[0, 2, 4], [0, 2, 2, 3, 4]]
        self.output_parent_idx = np.array([0, 0, 2, 3])


class BeamSearchOpTester3(BeamSearchOpTester):
    # pre_id = end_id
    def _create_pre_ids(self):
        np_data = np.array([[1], [0], [0], [4]], dtype='int64')
        tensor = create_tensor(self.scope, 'pre_ids', np_data)

    def _create_pre_scores(self):
        np_data = np.array([[0.1], [1.2], [0.5], [0.4]], dtype='float32')
        tensor = create_tensor(self.scope, 'pre_scores', np_data)

    def _create_ids(self):
        self.lod = [[0, 2, 4], [0, 1, 2, 3, 4]]
        np_data = np.array([[4, 2], [7, 3], [3, 5], [8, 1]], dtype='int64')
        tensor = create_tensor(self.scope, "ids", np_data)
        tensor.set_lod(self.lod)

    def _create_scores(self):
168 169 170 171 172 173 174 175 176
        np_data = np.array(
            [
                [0.6, 0.9],
                [0.5, 0.3],
                [0.9, 0.5],
                [0.6, 0.7],
            ],
            dtype='float32',
        )
P
pangyoki 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        tensor = create_tensor(self.scope, "scores", np_data)
        tensor.set_lod(self.lod)

    def set_outputs(self):
        self.beam_size = 2
        self.is_accumulated = True
        self.output_ids = np.array([2, 0, 1, 8])[:, np.newaxis]
        self.output_scores = np.array([0.9, 1.2, 0.7, 0.6])[:, np.newaxis]
        self.output_lod = [[0, 2, 4], [0, 1, 2, 2, 4]]
        self.output_parent_idx = np.array([0, 1, 3, 3])


class BeamSearchOpTester4(BeamSearchOpTester):
    # prune beam search while pre_id of in all beams is end_id
    def _create_pre_ids(self):
        np_data = np.array([[0], [0], [0], [4]], dtype='int64')
        tensor = create_tensor(self.scope, 'pre_ids', np_data)

    def _create_pre_scores(self):
        np_data = np.array([[0.1], [1.2], [0.5], [0.4]], dtype='float32')
        tensor = create_tensor(self.scope, 'pre_scores', np_data)

    def _create_ids(self):
        self.lod = [[0, 2, 4], [0, 1, 2, 3, 4]]
        np_data = np.array([[4, 2], [7, 3], [3, 5], [8, 1]], dtype='int64')
        tensor = create_tensor(self.scope, "ids", np_data)
        tensor.set_lod(self.lod)

    def _create_scores(self):
206 207 208 209 210 211 212 213 214
        np_data = np.array(
            [
                [0.6, 0.9],
                [0.5, 0.3],
                [0.9, 0.5],
                [0.6, 0.7],
            ],
            dtype='float32',
        )
P
pangyoki 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
        tensor = create_tensor(self.scope, "scores", np_data)
        tensor.set_lod(self.lod)

    def set_outputs(self):
        self.beam_size = 2
        self.is_accumulated = True
        self.output_ids = np.array([1, 8])[:, np.newaxis]
        self.output_scores = np.array([0.7, 0.6])[:, np.newaxis]
        self.output_lod = [[0, 2, 4], [0, 0, 0, 0, 2]]
        self.output_parent_idx = np.array([3, 3])


class BeamSearchOpTester5(BeamSearchOpTester):
    # is_accumulated = False
    def _create_pre_ids(self):
        np_data = np.array([[1], [2], [3], [4]], dtype='int64')
        tensor = create_tensor(self.scope, 'pre_ids', np_data)

    def _create_pre_scores(self):
        np_data = np.array([[0.1, 2.2, 0.3, 0.4]], dtype='float32')
        tensor = create_tensor(self.scope, 'pre_scores', np_data)

    def _create_ids(self):
        self.lod = [[0, 2, 4], [0, 1, 2, 3, 4]]
        np_data = np.array([[4, 2], [7, 3], [3, 5], [8, 1]], dtype='int64')
        tensor = create_tensor(self.scope, "ids", np_data)
        tensor.set_lod(self.lod)

    def _create_scores(self):
244 245 246 247 248 249 250 251 252
        np_data = np.array(
            [
                [0.6, 0.9],
                [0.5, 0.3],
                [0.9, 0.5],
                [0.1, 0.7],
            ],
            dtype='float32',
        )
P
pangyoki 已提交
253 254 255 256 257 258 259
        tensor = create_tensor(self.scope, "scores", np_data)
        tensor.set_lod(self.lod)

    def set_outputs(self):
        self.beam_size = 2
        self.is_accumulated = False
        self.output_ids = np.array([7, 3, 3, 1])[:, np.newaxis]
260 261 262
        self.output_scores = np.array([1.50685, 0.996027, 0.194639, 0.043325])[
            :, np.newaxis
        ]
P
pangyoki 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        self.output_lod = [[0, 2, 4], [0, 0, 2, 3, 4]]
        self.output_parent_idx = np.array([1, 1, 2, 3])


class BeamSearchOpTester6(BeamSearchOpTester):
    # beam_size = 1
    def _create_pre_ids(self):
        np_data = np.array([[1], [2], [3], [4]], dtype='int64')
        tensor = create_tensor(self.scope, 'pre_ids', np_data)

    def _create_pre_scores(self):
        np_data = np.array([[0.1, 0.2, 0.3, 0.4]], dtype='float32')
        tensor = create_tensor(self.scope, 'pre_scores', np_data)

    def _create_ids(self):
        self.lod = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
        np_data = np.array([[4, 2], [7, 3], [3, 5], [8, 1]], dtype='int64')
        tensor = create_tensor(self.scope, "ids", np_data)
        tensor.set_lod(self.lod)

    def _create_scores(self):
284 285 286 287 288 289 290 291 292
        np_data = np.array(
            [
                [0.6, 0.9],
                [0.5, 0.3],
                [0.9, 0.5],
                [0.1, 0.7],
            ],
            dtype='float32',
        )
P
pangyoki 已提交
293 294 295 296 297 298 299 300 301 302 303
        tensor = create_tensor(self.scope, "scores", np_data)
        tensor.set_lod(self.lod)

    def set_outputs(self):
        self.beam_size = 1
        self.is_accumulated = True
        self.output_ids = np.array([2, 7, 3, 1])[:, np.newaxis]
        self.output_scores = np.array([0.9, 0.5, 0.9, 0.7])[:, np.newaxis]
        self.output_lod = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
        self.output_parent_idx = np.array([0, 1, 2, 3])

Y
Yan Chunwei 已提交
304

305 306 307
class TestBeamSearchOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):
308 309 310 311 312 313
            pre_ids = fluid.data(
                name='pre_id', shape=[1], lod_level=2, dtype='int64'
            )
            pre_scores = fluid.data(
                name='pre_scores', shape=[1], lod_level=2, dtype='float32'
            )
314 315 316 317
            probs = fluid.data(name='probs', shape=[10000], dtype='float32')
            topk_scores, topk_indices = fluid.layers.topk(probs, k=4)
            accu_scores = fluid.layers.elementwise_add(
                x=fluid.layers.log(x=topk_scores),
318
                y=paddle.reshape(pre_scores, shape=[-1]),
319 320
                axis=0,
            )
321 322 323 324

            def test_preids_Variable():
                # the input pre_ids must be Variable
                preids_data = np.random.randint(1, 5, [5, 1]).astype("int64")
325 326 327 328 329 330 331 332
                fluid.layers.beam_search(
                    pre_ids=preids_data,
                    pre_scores=pre_scores,
                    ids=topk_indices,
                    scores=accu_scores,
                    beam_size=4,
                    end_id=1,
                )
333 334 335 336 337

            self.assertRaises(TypeError, test_preids_Variable)

            def test_prescores_Variable():
                # the input pre_scores must be Variable
338 339 340 341 342 343 344 345 346 347 348
                prescores_data = np.random.uniform(1, 5, [5, 1]).astype(
                    "float32"
                )
                fluid.layers.beam_search(
                    pre_ids=pre_ids,
                    pre_scores=prescores_data,
                    ids=topk_indices,
                    scores=accu_scores,
                    beam_size=4,
                    end_id=1,
                )
349 350 351 352 353 354

            self.assertRaises(TypeError, test_prescores_Variable)

            def test_ids_Variable():
                # the input ids must be Variable or None
                ids_data = np.random.randint(1, 5, [5, 1]).astype("int64")
355 356 357 358 359 360 361 362
                fluid.layers.beam_search(
                    pre_ids=pre_ids,
                    pre_scores=pre_scores,
                    ids=ids_data,
                    scores=accu_scores,
                    beam_size=4,
                    end_id=1,
                )
363 364 365 366 367 368

            self.assertRaises(TypeError, test_ids_Variable)

            def test_scores_Variable():
                # the input scores must be Variable
                scores_data = np.random.uniform(1, 5, [5, 1]).astype("float32")
369 370 371 372 373 374 375 376
                fluid.layers.beam_search(
                    pre_ids=pre_ids,
                    pre_scores=pre_scores,
                    ids=topk_indices,
                    scores=scores_data,
                    beam_size=4,
                    end_id=1,
                )
377 378 379 380 381

            self.assertRaises(TypeError, test_scores_Variable)

            def test_preids_dtype():
                # the dtype of input pre_ids must be int64
382 383 384 385 386 387 388 389 390 391 392 393 394 395
                preids_type_data = fluid.data(
                    name='preids_type_data',
                    shape=[1],
                    lod_level=2,
                    dtype='float32',
                )
                fluid.layers.beam_search(
                    pre_ids=preids_type_data,
                    pre_scores=pre_scores,
                    ids=topk_indices,
                    scores=accu_scores,
                    beam_size=4,
                    end_id=1,
                )
396 397 398 399 400

            self.assertRaises(TypeError, test_preids_dtype)

            def test_prescores_dtype():
                # the dtype of input pre_scores must be float32
401 402 403 404 405 406 407 408 409 410 411 412 413 414
                prescores_type_data = fluid.data(
                    name='prescores_type_data',
                    shape=[1],
                    lod_level=2,
                    dtype='int64',
                )
                fluid.layers.beam_search(
                    pre_ids=pre_ids,
                    pre_scores=prescores_type_data,
                    ids=topk_indices,
                    scores=accu_scores,
                    beam_size=4,
                    end_id=1,
                )
415 416 417 418

            self.assertRaises(TypeError, test_prescores_dtype)


Y
Yan Chunwei 已提交
419 420
if __name__ == '__main__':
    unittest.main()