attention.py 7.79 KB
Newer Older
1
from ctypes import c_uint64
PanZezhongQY's avatar
PanZezhongQY committed
2
3
4
import ctypes
import sys
import os
zhangyue's avatar
zhangyue committed
5
import torch
PanZezhongQY's avatar
PanZezhongQY committed
6
7

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
PanZezhong's avatar
PanZezhong committed
8
from libinfiniop import (
9
10
    LIBINFINIOP,
    TestTensor,
PanZezhong's avatar
PanZezhong committed
11
    get_test_devices,
12
    check_error,
PanZezhong's avatar
PanZezhong committed
13
    test_operator,
14
    get_args,
PanZezhong's avatar
PanZezhong committed
15
16
17
    debug,
    get_tolerance,
    profile_operation,
18
19
20
21
22
    TestWorkspace,
    InfiniDtype,
    InfiniDtypeNames,
    InfiniDeviceNames,
    infiniopOperatorDescriptor_t,
PanZezhongQY's avatar
PanZezhongQY committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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 causal_softmax(x):
    type = x.dtype
    mask = torch.tril(torch.ones_like(x), diagonal=-1).flip(dims=[-2, -1])
    y = x.clone()
    masked = torch.where(mask == 1, -torch.inf, y.to(torch.float32))
    return torch.nn.functional.softmax(masked, dim=-1).to(type)


def attention(q, k, v, k_cache, v_cache, pos):
    type = q.dtype

    n_q_head = q.shape[0]
    n_kv_head = k.shape[0]

    # Concatenate key and value caches
    k_cache = k_cache[:, :pos, :]  # (n_kv_head, pos, head_dim)
    v_cache = v_cache[:, :pos, :]  # (n_kv_head, pos, head_dim)
    k = torch.cat([k_cache, k], dim=1)  # (n_kv_head, total_seq_len, head_dim)
    v = torch.cat([v_cache, v], dim=1)  # (n_kv_head, total_seq_len, head_dim)

    total_seq_len = k.shape[1]

    head_dim = v.shape[-1]

    if n_q_head != n_kv_head:
        q = q.reshape(
            n_kv_head, -1, head_dim
        )  # (n_kv_head, n_group * seq_len, head_dim)

    # Scaled dot-product attention
    attn_scores = (
        torch.einsum("hqd,hkd->hqk", q.to(torch.float32), k.to(torch.float32))
        .to(type)
        .reshape(n_q_head, -1, total_seq_len)
    )  # (n_q_head, seq_len, total_seq_len)
    attn_scores = attn_scores / (head_dim**0.5)

    attn_weights = causal_softmax(attn_scores).reshape(
        n_kv_head, -1, total_seq_len
    )  # (n_kv_head, seq_len, total_seq_len)

    # Weighted sum of values
    attn_output = (
        torch.einsum(
            "hqk,hkd->hqd", attn_weights.to(torch.float32), v.to(torch.float32)
        )
        .to(type)
        .reshape(n_q_head, -1, head_dim)
        .permute(1, 0, 2)
    )  # ([seq_len, n_q_head, head_dim])

    return attn_output


def test(
    handle,
82
    device,
PanZezhongQY's avatar
PanZezhongQY committed
83
84
85
86
87
88
89
90
91
92
93
94
    n_q_head,
    n_kv_head,
    seq_len,
    head_dim,
    pos,
    k_cache_buf_len,
    v_cache_buf_len,
    q_stride=None,
    k_stride=None,
    v_stride=None,
    k_cache_stride=None,
    v_cache_stride=None,
95
    dtype=InfiniDtype.F16,
PanZezhong's avatar
PanZezhong committed
96
    sync=None,
PanZezhongQY's avatar
PanZezhongQY committed
97
98
):
    print(
99
100
        f"Testing Attention on {InfiniDeviceNames[device]} with n_q_head:{n_q_head} n_kv_head:{n_kv_head} seq_len:{seq_len} head_dim:{head_dim} pos:{pos} "
        f"dtype:{InfiniDtypeNames[dtype]} q_stride:{q_stride} k_stride:{k_stride} v_stride:{v_stride} k_cache_stride:{k_cache_stride} v_cache_stride:{v_cache_stride}"
PanZezhongQY's avatar
PanZezhongQY committed
101
102
    )

103
104
105
106
107
108
    out = TestTensor([seq_len, n_q_head, head_dim], None, dtype, device, mode="zeros")
    q = TestTensor([n_q_head, seq_len, head_dim], q_stride, dtype, device, scale=0.1)
    k = TestTensor([n_kv_head, seq_len, head_dim], k_stride, dtype, device, scale=0.1)
    v = TestTensor([n_kv_head, seq_len, head_dim], v_stride, dtype, device, scale=0.1)
    k_cache = TestTensor(
        [n_kv_head, k_cache_buf_len, head_dim], k_cache_stride, dtype, device, scale=0.1
PanZezhongQY's avatar
PanZezhongQY committed
109
    )
110
111
    v_cache = TestTensor(
        [n_kv_head, v_cache_buf_len, head_dim], v_cache_stride, dtype, device, scale=0.1
PanZezhongQY's avatar
PanZezhongQY committed
112
113
    )

114
115
116
117
118
119
120
121
122
123
124
    def torch_attention():
        return attention(
            q.torch_tensor(),
            k.torch_tensor(),
            v.torch_tensor(),
            k_cache.torch_tensor(),
            v_cache.torch_tensor(),
            pos,
        )

    ans = torch_attention()
PanZezhong's avatar
PanZezhong committed
125

126
127
    if sync is not None:
        sync()
PanZezhongQY's avatar
PanZezhongQY committed
128

129
    descriptor = infiniopOperatorDescriptor_t()
PanZezhongQY's avatar
PanZezhongQY committed
130
    check_error(
131
        LIBINFINIOP.infiniopCreateAttentionDescriptor(
PanZezhongQY's avatar
PanZezhongQY committed
132
133
            handle,
            ctypes.byref(descriptor),
134
135
136
137
138
139
            out.descriptor,
            q.descriptor,
            k.descriptor,
            v.descriptor,
            k_cache.descriptor,
            v_cache.descriptor,
PanZezhongQY's avatar
PanZezhongQY committed
140
141
142
143
144
            pos,
        )
    )

    # Invalidate the shape and strides in the descriptor to prevent them from being directly used by the kernel
145
146
    for tensor in [out, q, k, v, k_cache, v_cache]:
        tensor.destroy_desc()
PanZezhongQY's avatar
PanZezhongQY committed
147
148
149

    workspace_size = c_uint64(0)
    check_error(
150
151
152
        LIBINFINIOP.infiniopGetAttentionWorkspaceSize(
            descriptor, ctypes.byref(workspace_size)
        )
PanZezhongQY's avatar
PanZezhongQY committed
153
    )
154
    workspace = TestWorkspace(workspace_size.value, out.device)
PanZezhongQY's avatar
PanZezhongQY committed
155

PanZezhong's avatar
PanZezhong committed
156
157
    def lib_attention():
        check_error(
158
            LIBINFINIOP.infiniopAttention(
PanZezhong's avatar
PanZezhong committed
159
                descriptor,
160
                workspace.data(),
PanZezhong's avatar
PanZezhong committed
161
                workspace_size.value,
162
163
164
165
166
167
                out.data(),
                q.data(),
                k.data(),
                v.data(),
                k_cache.data(),
                v_cache.data(),
PanZezhong's avatar
PanZezhong committed
168
169
                None,
            )
PanZezhongQY's avatar
PanZezhongQY committed
170
171
        )

PanZezhong's avatar
PanZezhong committed
172
    lib_attention()
PanZezhongQY's avatar
PanZezhongQY committed
173

PanZezhong's avatar
PanZezhong committed
174
175
176
    # Validate results
    atol, rtol = get_tolerance(_TOLERANCE_MAP, dtype)
    if DEBUG:
177
178
        debug(out.actual_tensor(), ans, atol=atol, rtol=rtol)
    assert torch.allclose(out.actual_tensor(), ans, atol=atol, rtol=rtol)
PanZezhongQY's avatar
PanZezhongQY committed
179

PanZezhong's avatar
PanZezhong committed
180
181
182
    # Profiling workflow
    if PROFILE:
        # fmt: off
183
184
        profile_operation("PyTorch", lambda: torch_attention(), device, NUM_PRERUN, NUM_ITERATIONS)
        profile_operation("    lib", lambda: lib_attention(), device, NUM_PRERUN, NUM_ITERATIONS)
PanZezhong's avatar
PanZezhong committed
185
        # fmt: on
186
    check_error(LIBINFINIOP.infiniopDestroyAttentionDescriptor(descriptor))
PanZezhongQY's avatar
PanZezhongQY committed
187
188
189


if __name__ == "__main__":
190
    _TENSOR_DTYPES = [InfiniDtype.F16, InfiniDtype.F32]
PanZezhong's avatar
PanZezhong committed
191
192
193

    # Tolerance map for different data types
    _TOLERANCE_MAP = {
194
195
        InfiniDtype.F16: {"atol": 1e-4, "rtol": 1e-2},
        InfiniDtype.F32: {"atol": 1e-5, "rtol": 1e-3},
PanZezhong's avatar
PanZezhong committed
196
197
198
199
200
201
    }

    DEBUG = False
    PROFILE = False
    NUM_PRERUN = 10
    NUM_ITERATIONS = 1000
PanZezhongQY's avatar
PanZezhongQY committed
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
    test_cases = [
        # prefill
        (
            32,  # n_q_head
            4,  # n_kv_head
            5,  # seq_len
            64,  # head_dim
            0,  # pos
            2048,  # k_cache_buf_len
            2048,  # v_cache_buf_len
            [64, 2560, 1],  # q_stride
            [64, 2560, 1],  # k_stride
            [64, 2560, 1],  # v_stride
            [64, 11264, 1],  # k_cache_stride
            [64, 11264, 1],  # v_cache_stride
        ),
        # decode
        (
            32,  # n_q_head
            4,  # n_kv_head
            1,  # seq_len
            64,  # head_dim
            3,  # pos
            2048,  # k_cache_buf_len
            2048,  # v_cache_buf_len
            [64, 2560, 1],  # q_stride
            [64, 2560, 1],  # k_stride
            [64, 2560, 1],  # v_stride
            [64, 11264, 1],  # k_cache_stride
            [64, 11264, 1],  # v_cache_stride
        ),
        # for test
        (
            8,  # n_q_head
            4,  # n_kv_head
            2,  # seq_len
            16,  # head_dim
            1,  # pos
            8,  # k_cache_buf_len
            8,  # v_cache_buf_len
            None,  # q_stride
            None,  # k_stride
            None,  # v_stride
            None,  # k_cache_stride
            None,  # v_cache_stride
        ),
248
249
250
251
252
253
254
255
256
257
258
259
260
261
        (
            28,  # n_q_head
            28,  # n_kv_head
            15,  # seq_len
            128,  # head_dim
            0,  # pos
            2048,  # k_cache_buf_len
            2048,  # v_cache_buf_len
            [128, 10752, 1],  # q_stride
            [128, 10752, 1],  # k_stride
            [128, 10752, 1],  # v_stride
            [128, 3584, 1],  # k_cache_stride
            [128, 3584, 1],  # v_cache_stride
        ),
PanZezhongQY's avatar
PanZezhongQY committed
262
263
264
    ]
    args = get_args()

PanZezhong's avatar
PanZezhong committed
265
266
267
268
269
270
271
272
    # Configure testing options
    DEBUG = args.debug
    PROFILE = args.profile
    NUM_PRERUN = args.num_prerun
    NUM_ITERATIONS = args.num_iterations

    # Execute tests
    for device in get_test_devices(args):
273
        test_operator(device, test, test_cases, _TENSOR_DTYPES)
PanZezhongQY's avatar
PanZezhongQY committed
274
    print("\033[92mTest passed!\033[0m")