test_lstm_cudnn_op.py 20.5 KB
Newer Older
P
phlrain 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

from __future__ import print_function

import unittest
import numpy as np
G
GaoWei8 已提交
19
import math
P
phlrain 已提交
20 21 22

import paddle.fluid.core as core
from op_test import OpTest
G
GaoWei8 已提交
23
import paddle
P
phlrain 已提交
24
import paddle.fluid as fluid
G
GaoWei8 已提交
25
import paddle.fluid.layers as layers
G
GaoWei8 已提交
26
import random
27

G
GaoWei8 已提交
28 29 30
random.seed(2)
np.set_printoptions(threshold=np.inf)
paddle.enable_static()
P
phlrain 已提交
31 32 33 34

SIGMOID_THRESHOLD_MIN = -40.0
SIGMOID_THRESHOLD_MAX = 13.0
EXP_MAX_INPUT = 40.0
P
phlrain 已提交
35 36


G
GaoWei8 已提交
37
class RandomWeight:
38

G
GaoWei8 已提交
39 40 41 42 43 44 45 46 47
    def __init__(self):
        pass

    def updata_weight(self, hidden_size, input_size, dtype):
        std = 1.0 / math.sqrt(hidden_size)
        self.hidden_size = hidden_size
        self.input_size = input_size
        self.dtype = dtype

48 49 50 51
        self.weight_ih = np.random.uniform(low=-std,
                                           high=std,
                                           size=(4 * self.hidden_size,
                                                 self.input_size)).astype(dtype)
G
GaoWei8 已提交
52
        self.weight_hh = np.random.uniform(
53 54 55 56 57 58 59 60 61 62
            low=-std, high=std,
            size=(4 * self.hidden_size, self.hidden_size)).astype(dtype)
        self.bias_ih = np.random.uniform(low=-std,
                                         high=std,
                                         size=(4 *
                                               self.hidden_size)).astype(dtype)
        self.bias_hh = np.random.uniform(low=-std,
                                         high=std,
                                         size=(4 *
                                               self.hidden_size)).astype(dtype)
G
GaoWei8 已提交
63 64 65 66 67


weight = RandomWeight()


G
GaoWei8 已提交
68
class LayerMixin(object):
69

G
GaoWei8 已提交
70 71 72 73 74
    def __call__(self, *args, **kwargs):
        return self.forward(*args, **kwargs)


class LayerListMixin(LayerMixin):
75

G
GaoWei8 已提交
76 77 78 79 80 81 82 83 84 85 86
    def __init__(self, layers=None):
        self._layers = list(layers) if layers else []

    def append(self, layer):
        self._layers.append(layer)

    def __iter__(self):
        return iter(self._layers)


class LSTMCell(LayerMixin):
87

G
GaoWei8 已提交
88 89 90 91 92 93
    def __init__(self, input_size, hidden_size, bias=True):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.bias = bias
        self.dtype = np.float64
        self.parameters = dict()
G
GaoWei8 已提交
94 95
        self.weight_ih = weight.weight_ih
        self.weight_hh = weight.weight_hh
G
GaoWei8 已提交
96 97 98
        self.parameters['weight_ih'] = self.weight_ih
        self.parameters['weight_hh'] = self.weight_hh
        if bias:
G
GaoWei8 已提交
99 100
            self.bias_ih = weight.bias_ih
            self.bias_hh = weight.bias_hh
G
GaoWei8 已提交
101 102 103 104 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 130 131 132 133 134 135 136 137 138 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 168 169 170 171 172 173 174 175 176 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 206 207 208 209 210 211 212 213 214 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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
            self.parameters['bias_ih'] = self.bias_ih
            self.parameters['bias_hh'] = self.bias_hh
        else:
            self.bias_ih = None
            self.bias_hh = None

    def init_state(self, inputs):
        batch_size = inputs.shape[0]
        init_h = np.zeros((batch_size, self.hidden_size), dtype=inputs.dtype)
        init_c = np.zeros((batch_size, self.hidden_size), dtype=inputs.dtype)
        return init_h, init_c

    def forward(self, inputs, hx=None):
        if hx is None:
            hx = self.init_state(inputs)
        pre_hidden, pre_cell = hx
        gates = np.matmul(inputs, self.weight_ih.T)
        if self.bias_ih is not None:
            gates = gates + self.bias_ih
        gates += np.matmul(pre_hidden, self.weight_hh.T)
        if self.bias_hh is not None:
            gates = gates + self.bias_hh

        chunked_gates = np.split(gates, 4, -1)

        i = 1.0 / (1.0 + np.exp(-chunked_gates[0]))
        f = 1.0 / (1.0 + np.exp(-chunked_gates[1]))
        o = 1.0 / (1.0 + np.exp(-chunked_gates[3]))
        c = f * pre_cell + i * np.tanh(chunked_gates[2])
        h = o * np.tanh(c)

        return h, (h, c)


def sequence_mask(lengths, max_len=None):
    if max_len is None:
        max_len = np.max(lengths)
    else:
        assert max_len >= np.max(lengths)
    return np.arange(max_len) < np.expand_dims(lengths, -1)


def update_state(mask, new, old):
    if not isinstance(old, (tuple, list)):
        return np.where(mask, new, old)
    else:
        return tuple(map(lambda x, y: np.where(mask, x, y), new, old))


def rnn(cell,
        inputs,
        initial_states,
        sequence_length=None,
        time_major=False,
        is_reverse=False):
    if not time_major:
        inputs = np.transpose(inputs, [1, 0, 2])
    if is_reverse:
        inputs = np.flip(inputs, 0)

    if sequence_length is None:
        mask = None
    else:
        mask = np.transpose(sequence_mask(sequence_length), [1, 0])
        mask = np.expand_dims(mask, -1)
        if is_reverse:
            mask = np.flip(mask, 0)

    time_steps = inputs.shape[0]
    state = initial_states
    outputs = []
    for t in range(time_steps):
        x_t = inputs[t]
        if mask is not None:
            m_t = mask[t]
            y, new_state = cell(x_t, state)
            y = np.where(m_t, y, 0.)
            outputs.append(y)
            state = update_state(m_t, new_state, state)
        else:
            y, new_state = cell(x_t, state)
            outputs.append(y)
            state = new_state

    outputs = np.stack(outputs)
    final_state = state

    if is_reverse:
        outputs = np.flip(outputs, 0)
    if not time_major:
        outputs = np.transpose(outputs, [1, 0, 2])
    return outputs, final_state


def birnn(cell_fw,
          cell_bw,
          inputs,
          initial_states,
          sequence_length=None,
          time_major=False):
    states_fw, states_bw = initial_states
    outputs_fw, states_fw = rnn(cell_fw,
                                inputs,
                                states_fw,
                                sequence_length,
                                time_major=time_major)

    outputs_bw, states_bw = rnn(cell_bw,
                                inputs,
                                states_bw,
                                sequence_length,
                                time_major=time_major,
                                is_reverse=True)

    outputs = np.concatenate((outputs_fw, outputs_bw), -1)
    final_states = (states_fw, states_bw)
    return outputs, final_states


def flatten(nested):
    return list(_flatten(nested))


def _flatten(nested):
    for item in nested:
        if isinstance(item, (list, tuple)):
            for subitem in _flatten(item):
                yield subitem
        else:
            yield item


def unstack(array, axis=0):
    num = array.shape[axis]
    sub_arrays = np.split(array, num, axis)
    return [np.squeeze(sub_array, axis) for sub_array in sub_arrays]


def dropout(array, p=0.0):
    if p == 0.0:
        return array

    mask = (np.random.uniform(size=array.shape) < (1 - p)).astype(array.dtype)
    return array * (mask / (1 - p))


def split_states(states, bidirectional=False, state_components=1):
    if state_components == 1:
        states = unstack(states)
        if not bidirectional:
            return states
        else:
            return list(zip(states[::2], states[1::2]))
    else:
        assert len(states) == state_components
        states = tuple([unstack(item) for item in states])
        if not bidirectional:
            return list(zip(*states))
        else:
            states = list(zip(*states))
            return list(zip(states[::2], states[1::2]))


def concat_states(states, bidirectional=False, state_components=1):
    if state_components == 1:
        return np.stack(flatten(states))
    else:
        states = flatten(states)
        componnets = []
        for i in range(state_components):
            componnets.append(states[i::state_components])
        return [np.stack(item) for item in componnets]


class RNN(LayerMixin):
276

G
GaoWei8 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    def __init__(self, cell, is_reverse=False, time_major=False):
        super(RNN, self).__init__()
        self.cell = cell
        if not hasattr(self.cell, "call"):
            # for non-dygraph mode, `rnn` api uses cell.call
            self.cell.call = self.cell.forward
        self.is_reverse = is_reverse
        self.time_major = time_major

    def forward(self, inputs, initial_states=None, sequence_length=None):
        final_outputs, final_states = rnn(self.cell,
                                          inputs,
                                          initial_states=initial_states,
                                          sequence_length=sequence_length,
                                          time_major=self.time_major,
                                          is_reverse=self.is_reverse)
        return final_outputs, final_states


class BiRNN(LayerMixin):
297

G
GaoWei8 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    def __init__(self, cell_fw, cell_bw, time_major=False):
        super(BiRNN, self).__init__()
        self.cell_fw = cell_fw
        self.cell_bw = cell_bw
        self.time_major = time_major

    def forward(self,
                inputs,
                initial_states=None,
                sequence_length=None,
                **kwargs):
        if isinstance(initial_states, (list, tuple)):
            assert len(initial_states) == 2, \
                "length of initial_states should be 2 when it is a list/tuple"
        else:
            initial_states = [initial_states, initial_states]

        outputs, final_states = birnn(self.cell_fw, self.cell_bw, inputs,
                                      initial_states, sequence_length,
                                      self.time_major)
        return outputs, final_states


class RNNMixin(LayerListMixin):
322

G
GaoWei8 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    def forward(self, inputs, initial_states=None, sequence_length=None):
        batch_index = 1 if self.time_major else 0
        batch_size = inputs.shape[batch_index]
        dtype = inputs.dtype
        if initial_states is None:
            state_shape = (self.num_layers * self.num_directions, batch_size,
                           self.hidden_size)
            if self.state_components == 1:
                initial_states = np.zeros(state_shape, dtype)
            else:
                initial_states = tuple([
                    np.zeros(state_shape, dtype)
                    for _ in range(self.state_components)
                ])

        states = split_states(initial_states, self.num_directions == 2,
                              self.state_components)
        final_states = []

        for i, rnn_layer in enumerate(self):
            if i > 0:
                inputs = dropout(inputs, self.dropout)
            outputs, final_state = rnn_layer(inputs, states[i], sequence_length)
            final_states.append(final_state)
            inputs = outputs

        final_states = concat_states(final_states, self.num_directions == 2,
                                     self.state_components)
        return outputs, final_states


class LSTM(RNNMixin):
355

G
GaoWei8 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    def __init__(self,
                 input_size,
                 hidden_size,
                 num_layers=1,
                 direction="forward",
                 dropout=0.,
                 time_major=False):
        super(LSTM, self).__init__()

        if direction in ["forward", "backward"]:
            is_reverse = direction == "backward"
            cell = LSTMCell(input_size, hidden_size)
            self.append(RNN(cell, is_reverse, time_major))
            for i in range(1, num_layers):
                cell = LSTMCell(hidden_size, hidden_size)
                self.append(RNN(cell, is_reverse, time_major))
        elif direction == "bidirectional":
            cell_fw = LSTMCell(input_size, hidden_size)
            cell_bw = LSTMCell(input_size, hidden_size)
            self.append(BiRNN(cell_fw, cell_bw, time_major))
            for i in range(1, num_layers):
                cell_fw = LSTMCell(2 * hidden_size, hidden_size)
                cell_bw = LSTMCell(2 * hidden_size, hidden_size)
                self.append(BiRNN(cell_fw, cell_bw, time_major))
        else:
            raise ValueError(
                "direction should be forward, backward or bidirectional, "
                "received direction = {}".format(direction))

        self.input_size = input_size
        self.hidden_size = hidden_size
        self.dropout = dropout
        self.num_directions = 2 if direction == "bidirectional" else 1
        self.time_major = time_major
        self.num_layers = num_layers
        self.state_components = 2
P
phlrain 已提交
392 393


394 395
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
P
phlrain 已提交
396
class TestCUDNNLstmOp(OpTest):
397

G
GaoWei8 已提交
398 399 400 401 402 403 404 405
    def get_weight_names(self):
        weight_names = []
        for i in range(2 * self.num_layers):
            weight_names.append('weight{}'.format(i))
        for i in range(2 * self.num_layers):
            weight_names.append('bias{}'.format(i))
        return weight_names

P
phlrain 已提交
406 407
    def setUp(self):
        self.op_type = "cudnn_lstm"
R
ronnywang 已提交
408 409
        self.dtype = np.float32 if core.is_compiled_with_rocm() else np.float64
        self.sequence_length = None if core.is_compiled_with_rocm(
410
        ) else np.array([12, 11, 10, 9, 8], dtype=np.int32)
G
GaoWei8 已提交
411
        self.num_layers = 1
G
GaoWei8 已提交
412
        self.set_attrs()
P
phlrain 已提交
413

G
GaoWei8 已提交
414
        seq_length = 12
P
phlrain 已提交
415
        batch_size = 5
G
GaoWei8 已提交
416 417
        input_size = 21
        hidden_size = 21
P
phlrain 已提交
418

419 420 421 422
        input = np.random.uniform(low=-0.1,
                                  high=0.1,
                                  size=(seq_length, batch_size,
                                        input_size)).astype(self.dtype)
G
GaoWei8 已提交
423 424 425 426 427
        input[11][1:][:] = 0
        input[10][2:][:] = 0
        input[9][3:][:] = 0
        input[8][4:][:] = 0

G
GaoWei8 已提交
428
        weight.updata_weight(hidden_size, input_size, self.dtype)
429 430 431 432 433
        rnn1 = LSTM(input_size,
                    hidden_size,
                    num_layers=self.num_layers,
                    time_major=True,
                    direction="forward")
G
GaoWei8 已提交
434

435 436
        output, (last_hidden,
                 last_cell) = rnn1(input, sequence_length=self.sequence_length)
G
GaoWei8 已提交
437

G
GaoWei8 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        flat_w = []
        num = 0
        for i in range(self.num_layers):
            if i == 0:
                weight_ih = weight.weight_ih
            else:
                weight_ih = weight.weight_hh
            flat_w.append(("weight" + str(num), weight_ih))
            num += 1
        for i in range(self.num_layers):
            weight_hh = weight.weight_hh
            flat_w.append(("weight" + str(num), weight_hh))
            num += 1
        num = 0
        for i in range(self.num_layers):
            bias_ih = weight.bias_ih
            flat_w.append(("bias" + str(num), bias_ih))
            num += 1
        for i in range(self.num_layers):
            bias_hh = weight.bias_hh
            flat_w.append(("bias" + str(num), bias_hh))
            num += 1
460 461 462 463
        init_h = np.zeros(
            (self.num_layers, batch_size, hidden_size)).astype(self.dtype)
        init_c = np.zeros(
            (self.num_layers, batch_size, hidden_size)).astype(self.dtype)
G
GaoWei8 已提交
464 465
        state_out = np.ndarray((300)).astype("uint8")

R
ronnywang 已提交
466 467 468 469 470 471 472
        if core.is_compiled_with_rocm():
            for i in range(len(flat_w)):
                w = np.split(flat_w[i][1], 4, 0)
                w = [w[0], w[1], w[3], w[2]]
                w = np.concatenate(w)
                flat_w[i] = (flat_w[i][0], w)

P
phlrain 已提交
473
        self.inputs = {
G
GaoWei8 已提交
474
            'Input': input,
G
GaoWei8 已提交
475
            'WeightList': flat_w,
G
GaoWei8 已提交
476
            'InitH': init_h,
477 478
            'InitC': init_c,
            'SequenceLength': self.sequence_length
P
phlrain 已提交
479
        }
R
ronnywang 已提交
480 481 482 483 484 485 486
        if self.sequence_length is None:
            self.inputs = {
                'Input': input,
                'WeightList': flat_w,
                'InitH': init_h,
                'InitC': init_c,
            }
P
phlrain 已提交
487 488 489
        self.attrs = {
            'dropout_prob': 0.0,
            'is_bidirec': False,
G
GaoWei8 已提交
490
            'input_size': input_size,
P
phlrain 已提交
491
            'hidden_size': hidden_size,
G
GaoWei8 已提交
492
            'num_layers': self.num_layers,
P
phlrain 已提交
493
        }
P
phlrain 已提交
494 495
        self.outputs = {
            'Out': output,
G
GaoWei8 已提交
496 497 498 499
            "LastH": last_hidden,
            'LastC': last_cell,
            'Reserve': np.ndarray((400)).astype("uint8"),
            'StateOut': state_out
P
phlrain 已提交
500
        }
P
phlrain 已提交
501

G
GaoWei8 已提交
502 503 504
    def set_attrs(self):
        pass

P
phlrain 已提交
505
    def test_output_with_place(self):
506
        place = core.CUDAPlace(0)
R
ronnywang 已提交
507
        if core.is_compiled_with_rocm():
508 509 510
            self.check_output_with_place(place,
                                         atol=1e-5,
                                         no_check_set=['Reserve', 'StateOut'])
R
ronnywang 已提交
511
        else:
512 513
            self.check_output_with_place(place,
                                         no_check_set=['Reserve', 'StateOut'])
P
phlrain 已提交
514

P
phlrain 已提交
515
    def test_grad_with_place(self):
516
        place = core.CUDAPlace(0)
G
GaoWei8 已提交
517 518 519
        var_name_list = self.get_weight_names()
        for var_name in var_name_list:
            self.check_grad_with_place(
520
                place, set(['Input', var_name, 'InitH', 'InitC']),
G
GaoWei8 已提交
521
                ['Out', 'LastH', 'LastC'])
G
GaoWei8 已提交
522 523 524 525


@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
G
GaoWei8 已提交
526
class TestCUDNNlstmAPI(unittest.TestCase):
527

G
GaoWei8 已提交
528 529 530 531 532 533
    def test_lstm(self):
        seq_len = 20
        batch_size = 5
        hidden_size = 20
        dropout_prob = 0.0
        num_layers = 1
R
ronnywang 已提交
534
        dtype = 'float32' if core.is_compiled_with_rocm() else 'float64'
535 536 537
        input = fluid.data(name='input',
                           shape=[seq_len, batch_size, hidden_size],
                           dtype=dtype)
G
GaoWei8 已提交
538
        init_h = layers.fill_constant([num_layers, batch_size, hidden_size],
R
ronnywang 已提交
539
                                      dtype, 0.0)
G
GaoWei8 已提交
540
        init_c = layers.fill_constant([num_layers, batch_size, hidden_size],
R
ronnywang 已提交
541
                                      dtype, 0.0)
G
GaoWei8 已提交
542 543 544 545 546
        rnn_out, last_h, last_c = layers.lstm(input, init_h, init_c, seq_len,
                                              hidden_size, num_layers,
                                              dropout_prob, False)
        exe = fluid.Executor(fluid.CUDAPlace(0))
        exe.run(fluid.default_startup_program())
547 548 549 550
        input_i = np.random.uniform(low=-0.1,
                                    high=0.1,
                                    size=(seq_len, batch_size,
                                          hidden_size)).astype("float64")
G
GaoWei8 已提交
551 552 553
        out = exe.run(fluid.default_main_program(),
                      feed={'input': input_i},
                      fetch_list=[rnn_out, last_h, last_c, 'cudnn_lstm_0.w_0'])
G
GaoWei8 已提交
554 555 556 557 558


@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
class TestCUDNNlstmAPI(unittest.TestCase):
559

G
GaoWei8 已提交
560 561 562 563 564
    def test_lstm(self):
        seq_len = 20
        batch_size = 5
        hidden_size = 20
        dropout_prob = 0.0
G
GaoWei8 已提交
565
        num_layers = 2
R
ronnywang 已提交
566
        dtype = 'float32' if core.is_compiled_with_rocm() else 'float64'
567 568 569
        input = fluid.data(name='input',
                           shape=[seq_len, batch_size, hidden_size],
                           dtype=dtype)
G
GaoWei8 已提交
570
        init_h = layers.fill_constant([num_layers, batch_size, hidden_size],
R
ronnywang 已提交
571
                                      dtype, 0.0)
G
GaoWei8 已提交
572
        init_c = layers.fill_constant([num_layers, batch_size, hidden_size],
R
ronnywang 已提交
573
                                      dtype, 0.0)
G
GaoWei8 已提交
574 575
        rnn_out, last_h, last_c = layers.lstm(input, init_h, init_c, seq_len,
                                              hidden_size, num_layers,
G
GaoWei8 已提交
576
                                              dropout_prob, False, True)
G
GaoWei8 已提交
577 578
        exe = fluid.Executor(fluid.CUDAPlace(0))
        exe.run(fluid.default_startup_program())
579 580 581 582
        input_i = np.random.uniform(low=-0.1,
                                    high=0.1,
                                    size=(seq_len, batch_size,
                                          hidden_size)).astype(dtype)
G
GaoWei8 已提交
583 584 585 586
        out = exe.run(fluid.default_main_program(),
                      feed={'input': input_i},
                      fetch_list=[rnn_out, last_h, last_c, 'cudnn_lstm_0.w_0'])

P
phlrain 已提交
587 588 589

if __name__ == '__main__':
    unittest.main()