test_sparse_attention_op.py 18.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   Copyright (c) 2021 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.

import unittest
import numpy as np
from op_test import OpTest
import paddle.fluid.core as core
19
from paddle.static import Program, program_guard
20
import paddle
21 22 23
import paddle.fluid as fluid
import paddle.fluid.framework as framework
import paddle.nn.functional as F
24 25
import os
import re
26
import copy
27 28 29 30 31 32 33 34 35 36 37 38 39 40


def get_cuda_version():
    result = os.popen("nvcc --version").read()
    regex = r'release (\S+),'
    match = re.search(regex, result)
    if match:
        num = str(match.group(1))
        integer, decimal = num.split('.')
        return int(integer) * 1000 + int(float(decimal) * 10)
    else:
        return -1


41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
def masked_fill(x):
    row, col = x.shape[0], x.shape[1]
    for i in range(row):
        for j in range(col):
            if x[i][j] == 0:
                x[i][j] = float('-inf')
    return x


def init_mask(x):
    row, col = x.shape[0], x.shape[1]
    for i in range(row):
        for j in range(col):
            if x[i][j] == 0 and (j < 0.8 * col):
                x[i][j] = 1
    return x


def softmax(x, kp_mask=None, attn_mask=None, bsz=None):
    if kp_mask is None and attn_mask is None:
        max = np.max(x, axis=1, keepdims=True)
        e_x = np.exp(x - max)
        sum = np.sum(e_x, axis=1, keepdims=True)
        f_x = e_x / sum
        return f_x
    else:
        # kp_mask
        current_kp_mask = kp_mask[bsz]
        row = current_kp_mask.shape[0]
        current_kp_mask = np.expand_dims(current_kp_mask, 0).repeat(row, axis=0)
        # attn_mask
        current_attn_mask = copy.deepcopy(attn_mask)
        current_attn_mask = masked_fill(current_attn_mask)
        current_kp_mask = masked_fill(current_kp_mask)
        x = x + current_kp_mask
        x = x + current_attn_mask
        max = np.max(x, axis=1, keepdims=True)
        e_x = np.exp(x - max)
        sum = np.sum(e_x, axis=1, keepdims=True)
        f_x = e_x / sum
        return f_x
82 83 84 85 86 87 88 89 90 91 92 93 94 95


def get_csr_value(mat, layout, nnz):
    row, col = mat.shape[0], mat.shape[1]
    value = np.zeros(nnz)
    ptr = 0
    for i in range(row):
        for j in range(col):
            if layout[i][j] == 1:
                value[ptr] = mat[i][j]
                ptr += 1
    return value


Z
zhangkaihuo 已提交
96 97 98
def ref_sparse_attention(
    q, k, v, offset, columns, kp_mask=None, attn_mask=None, bsz=None
):
99 100 101 102 103 104 105 106 107 108
    row, col, nnz = q.shape[0], q.shape[1], columns.shape[0]
    mat = np.zeros((row, row))
    for cur_row in range(row):
        start_ptr = int(offset[cur_row])
        end_ptr = int(offset[cur_row + 1])
        for ptr in range(start_ptr, end_ptr):
            cur_col = int(columns[ptr])
            mat[cur_row][cur_col] = 1
    a = np.dot(q, k.T) * mat
    a_value = get_csr_value(a, mat, nnz)
Z
zhangkaihuo 已提交
109
    scaling = float(col) ** -0.5
110 111 112 113 114
    a = scaling * a
    for i in range(row):
        for j in range(row):
            if mat[i][j] == 0:
                a[i][j] = float('-inf')
115 116 117 118 119
    # softmax
    if kp_mask is None and attn_mask is None:
        b = softmax(a)
    else:
        b = softmax(a, kp_mask=kp_mask, attn_mask=attn_mask, bsz=bsz)
120 121 122 123 124
    b_value = get_csr_value(b, mat, nnz)
    result = np.dot(b, v)
    return result, a_value, b_value


Z
zhangkaihuo 已提交
125 126 127
def ref_batch_sparse_attention(
    q, k, v, offset, columns, kp_mask=None, attn_mask=None
):
128 129 130 131 132 133 134
    batch_size, num_heads, row, col = q.shape
    nnz = columns.shape[2]
    result = np.zeros((batch_size, num_heads, row, col))
    result_sdd = np.zeros((batch_size, num_heads, nnz))
    result_softmax = np.zeros((batch_size, num_heads, nnz))
    for i in range(batch_size):
        for j in range(num_heads):
Z
zhangkaihuo 已提交
135 136 137 138 139
            cur_q, cur_k, cur_v, = (
                q[i][j],
                k[i][j],
                v[i][j],
            )
140
            cur_offset, cur_columns = offset[i][j], columns[i][j]
141 142
            if kp_mask is None and attn_mask is None:
                cur_result, cur_sdd, cur_softmax = ref_sparse_attention(
Z
zhangkaihuo 已提交
143 144
                    cur_q, cur_k, cur_v, cur_offset, cur_columns
                )
145 146 147 148 149 150 151 152 153
            else:
                cur_result, cur_sdd, cur_softmax = ref_sparse_attention(
                    cur_q,
                    cur_k,
                    cur_v,
                    cur_offset,
                    cur_columns,
                    kp_mask=kp_mask,
                    attn_mask=attn_mask,
Z
zhangkaihuo 已提交
154 155
                    bsz=i,
                )
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
            result[i][j] = cur_result
            result_sdd[i][j], result_softmax[i][j] = cur_sdd, cur_softmax
    return result, result_sdd, result_softmax


def init_csr_format(batch_size, num_heads, rows, blocksize):
    block_num, block_last = rows / blocksize, rows % blocksize
    nnz_num = block_num * blocksize * blocksize + block_last * block_last
    offset = np.zeros(rows + 1)
    columns = np.zeros(int(nnz_num))
    mat = np.zeros((rows, rows))
    for i in range(0, rows, blocksize):
        for x in range(blocksize):
            for y in range(blocksize):
                p_x, p_y = i + x, i + y
                if (p_x < rows) and (p_y < rows):
                    mat[p_x][p_y] = 1
    p_offset, p_column, count = 0, 0, 0
    for i in range(rows):
        for j in range(rows):
            if mat[i][j] != 0:
                count += 1
                columns[p_column] = j
                p_column += 1
        p_offset += 1
        offset[p_offset] = count
    offset = np.expand_dims(np.expand_dims(offset, 0), 0)
    offset = offset.repeat(num_heads, axis=1)
    offset = offset.repeat(batch_size, axis=0)
    columns = np.expand_dims(np.expand_dims(columns, 0), 0)
    columns = columns.repeat(num_heads, axis=1)
    columns = columns.repeat(batch_size, axis=0)
    return offset, columns


@unittest.skipIf(
192
    not core.is_compiled_with_cuda() or get_cuda_version() < 11030,
Z
zhangkaihuo 已提交
193
    "core is not compiled with CUDA and cuda version need larger than or equal to 11.3",
194
)
195 196
class TestSparseAttentionOp(OpTest):
    def config(self):
197 198
        self.shape = (1, 1, 16, 16)
        self.blocksize = 4
199
        self.dtype = "float64"
200
        self.use_mask = True
201 202 203 204 205 206 207 208 209

    def setUp(self):
        paddle.enable_static()
        self.config()
        self.op_type = "sparse_attention"
        self.place = paddle.CUDAPlace(0)
        self.q = np.random.random(self.shape).astype(self.dtype)
        self.k = np.random.random(self.shape).astype(self.dtype)
        self.v = np.random.random(self.shape).astype(self.dtype)
210
        # init CSR tensor
Z
zhangkaihuo 已提交
211 212 213
        offset, columns = init_csr_format(
            self.shape[0], self.shape[1], self.shape[2], self.blocksize
        )
214 215
        self.offset = offset.astype('int32')
        self.columns = columns.astype('int32')
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        # init mask tensor
        key_padding_mask_shape = (self.shape[0], self.shape[2])
        attn_mask_shape = (self.shape[2], self.shape[2])
        key_padding_mask = np.random.randint(0, 2, size=key_padding_mask_shape)
        attn_mask = np.random.randint(0, 2, size=attn_mask_shape)
        key_padding_mask = init_mask(key_padding_mask)
        attn_mask = init_mask(attn_mask)

        self.key_padding_mask = key_padding_mask.astype(self.dtype)
        self.attn_mask = attn_mask.astype(self.dtype)
        if self.use_mask == True:
            result, result_sdd, result_softmax = ref_batch_sparse_attention(
                self.q,
                self.k,
                self.v,
                self.offset,
                self.columns,
                kp_mask=self.key_padding_mask,
Z
zhangkaihuo 已提交
234 235
                attn_mask=self.attn_mask,
            )
236 237
        else:
            result, result_sdd, result_softmax = ref_batch_sparse_attention(
Z
zhangkaihuo 已提交
238 239
                self.q, self.k, self.v, self.offset, self.columns
            )
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

        if self.use_mask == True:
            self.inputs = {
                'Q': self.q,
                'K': self.k,
                'V': self.v,
                'Offset': self.offset,
                'Columns': self.columns,
                'KeyPaddingMask': self.key_padding_mask,
                'AttnMask': self.attn_mask,
            }
        else:
            self.inputs = {
                'Q': self.q,
                'K': self.k,
                'V': self.v,
                'Offset': self.offset,
                'Columns': self.columns,
            }
259 260
        self.outputs = {
            'Out': result.astype(self.dtype),
261
            'SparseDotSdd': result_sdd.astype(self.dtype),
Z
zhangkaihuo 已提交
262
            'Softmax': result_softmax.astype(self.dtype),
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
        }

    def test_check_output(self):
        self.check_output_with_place(self.place)

    def test_check_grad(self):
        self.check_grad_with_place(self.place, ['Q'], 'Out')
        self.check_grad_with_place(self.place, ['K'], 'Out')
        self.check_grad_with_place(self.place, ['V'], 'Out')


class TestSparseAttentionOpFp32Test(TestSparseAttentionOp):
    def config(self):
        self.shape = (1, 1, 8, 16)
        self.blocksize = 2
        self.dtype = "float32"
279
        self.use_mask = False
280 281 282 283 284 285 286


class TestSparseAttentionOpShapeTest(TestSparseAttentionOp):
    def config(self):
        self.shape = (2, 2, 32, 8)
        self.blocksize = 8
        self.dtype = "float64"
287
        self.use_mask = False
288 289


290
@unittest.skipIf(
291
    not core.is_compiled_with_cuda() or get_cuda_version() < 11030,
Z
zhangkaihuo 已提交
292
    "core is not compiled with CUDA and cuda version need larger than or equal to 11.3",
293 294 295 296 297 298 299
)
class TestSparseAttentionAPI(unittest.TestCase):
    def setUp(self):
        self.place = paddle.CUDAPlace(0)
        self.shape = (1, 1, 8, 4)
        self.blocksize = 2
        self.dtype = 'float64'
300
        self.use_mask = True
301 302 303 304 305 306 307 308

    def test_static_graph(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            Q = paddle.static.data(name="Q", shape=self.shape, dtype=self.dtype)
            K = paddle.static.data(name="K", shape=self.shape, dtype=self.dtype)
            V = paddle.static.data(name="V", shape=self.shape, dtype=self.dtype)

Z
zhangkaihuo 已提交
309 310 311 312 313
            batch_size, num_heads, rows = (
                self.shape[0],
                self.shape[1],
                self.shape[2],
            )
314 315
            block_num = rows / self.blocksize
            block_last = rows % self.blocksize
Z
zhangkaihuo 已提交
316 317 318 319
            sparse_nnz_num = (
                block_num * self.blocksize * self.blocksize
                + block_last * block_last
            )
320 321 322
            offset_shape = (batch_size, num_heads, rows + 1)
            columns_shape = (batch_size, num_heads, int(sparse_nnz_num))

Z
zhangkaihuo 已提交
323 324 325 326 327 328
            offset = paddle.static.data(
                name="Offset", shape=offset_shape, dtype="int32"
            )
            columns = paddle.static.data(
                name="Columns", shape=columns_shape, dtype="int32"
            )
329 330 331 332 333 334
            key_padding_mask_shape = (self.shape[0], self.shape[2])
            attn_mask_shape = (self.shape[2], self.shape[2])
            if self.use_mask == True:
                key_padding_mask = paddle.static.data(
                    name="KeyPaddingMask",
                    shape=key_padding_mask_shape,
Z
zhangkaihuo 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348
                    dtype=self.dtype,
                )
                attn_mask = paddle.static.data(
                    name="AttnMask", shape=attn_mask_shape, dtype=self.dtype
                )
                Out = F.sparse_attention(
                    Q,
                    K,
                    V,
                    offset,
                    columns,
                    key_padding_mask=key_padding_mask,
                    attn_mask=attn_mask,
                )
349 350
            else:
                Out = F.sparse_attention(Q, K, V, offset, columns)
351 352 353 354

            Q_np = np.random.random(self.shape).astype(self.dtype)
            K_np = np.random.random(self.shape).astype(self.dtype)
            V_np = np.random.random(self.shape).astype(self.dtype)
Z
zhangkaihuo 已提交
355 356 357
            offset_np, columns_np = init_csr_format(
                self.shape[0], self.shape[1], self.shape[2], self.blocksize
            )
358 359 360
            offset_np = offset_np.astype('int32')
            columns_np = columns_np.astype('int32')

361
            # init mask tensor
Z
zhangkaihuo 已提交
362 363 364
            key_padding_mask_np = np.random.randint(
                0, 2, size=key_padding_mask_shape
            )
365 366 367 368 369 370
            attn_mask_np = np.random.randint(0, 2, size=attn_mask_shape)
            key_padding_mask_np = init_mask(key_padding_mask_np)
            attn_mask_np = init_mask(attn_mask_np)
            key_padding_mask_np = key_padding_mask_np.astype(self.dtype)
            attn_mask_np = attn_mask_np.astype(self.dtype)

371
            exe = fluid.Executor(self.place)
372
            if self.use_mask == True:
Z
zhangkaihuo 已提交
373 374 375 376 377 378 379 380 381 382 383 384
                fetches_result = exe.run(
                    feed={
                        "Q": Q_np,
                        "K": K_np,
                        "V": V_np,
                        "Offset": offset_np,
                        "Columns": columns_np,
                        'KeyPaddingMask': key_padding_mask_np,
                        'AttnMask': attn_mask_np,
                    },
                    fetch_list=[Out],
                )
385 386 387 388 389 390 391
                expected_result, __, __ = ref_batch_sparse_attention(
                    Q_np,
                    K_np,
                    V_np,
                    offset_np,
                    columns_np,
                    kp_mask=key_padding_mask_np,
Z
zhangkaihuo 已提交
392 393
                    attn_mask=attn_mask_np,
                )
394
            else:
Z
zhangkaihuo 已提交
395 396 397 398 399 400 401 402 403 404
                fetches_result = exe.run(
                    feed={
                        "Q": Q_np,
                        "K": K_np,
                        "V": V_np,
                        "Offset": offset_np,
                        "Columns": columns_np,
                    },
                    fetch_list=[Out],
                )
405
                expected_result, __, __ = ref_batch_sparse_attention(
Z
zhangkaihuo 已提交
406 407
                    Q_np, K_np, V_np, offset_np, columns_np
                )
408

Z
zhangkaihuo 已提交
409 410 411
            np.testing.assert_allclose(
                fetches_result[0], expected_result, rtol=1e-05, atol=1e-05
            )
412 413 414

    def test_dygraph(self):
        paddle.disable_static()
Z
zhangkaihuo 已提交
415 416 417
        offset, columns = init_csr_format(
            self.shape[0], self.shape[1], self.shape[2], self.blocksize
        )
418 419 420 421 422
        offset = offset.astype('int32')
        columns = columns.astype('int32')
        query = np.random.random(self.shape).astype(self.dtype)
        key = np.random.random(self.shape).astype(self.dtype)
        value = np.random.random(self.shape).astype(self.dtype)
423 424 425 426 427 428 429 430 431
        # init mask tensor
        key_padding_mask_shape = (self.shape[0], self.shape[2])
        attn_mask_shape = (self.shape[2], self.shape[2])
        key_padding_mask = np.random.randint(0, 2, size=key_padding_mask_shape)
        attn_mask = np.random.randint(0, 2, size=attn_mask_shape)
        key_padding_mask = init_mask(key_padding_mask)
        attn_mask = init_mask(attn_mask)
        key_padding_mask = key_padding_mask.astype(self.dtype)
        attn_mask = attn_mask.astype(self.dtype)
432 433 434 435 436 437

        paddle_query = paddle.to_tensor(query, place=self.place)
        paddle_key = paddle.to_tensor(key, place=self.place)
        paddle_value = paddle.to_tensor(value, place=self.place)
        paddle_offset = paddle.to_tensor(offset, place=self.place)
        paddle_colunmns = paddle.to_tensor(columns, place=self.place)
438 439 440 441
        paddle_kp_mask = paddle.to_tensor(key_padding_mask, place=self.place)
        paddle_attn_mask = paddle.to_tensor(attn_mask, place=self.place)

        if self.use_mask == True:
Z
zhangkaihuo 已提交
442 443 444 445 446 447 448 449 450
            paddle_result = F.sparse_attention(
                paddle_query,
                paddle_key,
                paddle_value,
                paddle_offset,
                paddle_colunmns,
                key_padding_mask=paddle_kp_mask,
                attn_mask=paddle_attn_mask,
            )
451 452 453 454 455 456 457 458

            numpy_result, __, __ = ref_batch_sparse_attention(
                query,
                key,
                value,
                offset,
                columns,
                kp_mask=key_padding_mask,
Z
zhangkaihuo 已提交
459 460
                attn_mask=attn_mask,
            )
461 462
            numpy_result = numpy_result.astype(self.dtype)
        else:
Z
zhangkaihuo 已提交
463 464 465 466 467 468 469
            paddle_result = F.sparse_attention(
                paddle_query,
                paddle_key,
                paddle_value,
                paddle_offset,
                paddle_colunmns,
            )
470

471
            numpy_result, __, __ = ref_batch_sparse_attention(
Z
zhangkaihuo 已提交
472 473
                query, key, value, offset, columns
            )
474
            numpy_result = numpy_result.astype(self.dtype)
475

Z
zhangkaihuo 已提交
476 477 478
        np.testing.assert_allclose(
            paddle_result.numpy(), numpy_result, rtol=1e-05, atol=1e-05
        )
479 480 481 482 483 484 485 486


class TestSparseAttentionAPITestFloat(TestSparseAttentionAPI):
    def setUp(self):
        self.place = paddle.CUDAPlace(0)
        self.shape = (2, 2, 8, 4)
        self.blocksize = 2
        self.dtype = 'float32'
487
        self.use_mask = False
488 489 490 491 492 493 494 495


class TestSparseAttentionAPITestShape1(TestSparseAttentionAPI):
    def setUp(self):
        self.place = paddle.CUDAPlace(0)
        self.shape = (2, 2, 64, 32)
        self.blocksize = 2
        self.dtype = 'float64'
496
        self.use_mask = False
497 498 499 500 501 502 503 504


class TestSparseAttentionAPITestShape2(TestSparseAttentionAPI):
    def setUp(self):
        self.place = paddle.CUDAPlace(0)
        self.shape = (2, 1, 64, 32)
        self.blocksize = 2
        self.dtype = 'float64'
505
        self.use_mask = False
506 507 508 509 510 511 512 513


class TestSparseAttentionAPITestShape3(TestSparseAttentionAPI):
    def setUp(self):
        self.place = paddle.CUDAPlace(0)
        self.shape = (4, 4, 128, 32)
        self.blocksize = 8
        self.dtype = 'float64'
514
        self.use_mask = False
515 516 517 518 519 520 521 522


class TestSparseAttentionAPITestShape4(TestSparseAttentionAPI):
    def setUp(self):
        self.place = paddle.CUDAPlace(0)
        self.shape = (3, 3, 35, 15)
        self.blocksize = 3
        self.dtype = 'float64'
523
        self.use_mask = False
524 525


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