gemm.py 10.1 KB
Newer Older
PanZezhongQY's avatar
PanZezhongQY committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from ctypes import POINTER, Structure, c_int32, c_uint64, c_void_p, c_float, c_bool
import ctypes
import sys
import os
import time

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from operatorspy import (
    open_lib,
    to_tensor,
    DeviceEnum,
    infiniopHandle_t,
    infiniopTensorDescriptor_t,
    create_handle,
    destroy_handle,
    check_error,
    rearrange_tensor,
)

from operatorspy.tests.test_utils import get_args
import torch

# constant for control whether profile the pytorch and lib functions
# NOTE: need to manually add synchronization function to the lib function,
#       e.g., cudaDeviceSynchronize() for CUDA
PROFILE = False
NUM_PRERUN = 10
NUM_ITERATIONS = 1000

30

PanZezhongQY's avatar
PanZezhongQY committed
31
32
33
34
35
36
37
class GEMMDescriptor(Structure):
    _fields_ = [("device", c_int32)]


infiniopGEMMDescriptor_t = POINTER(GEMMDescriptor)


38
39
40
def gemm(
    A, B, C=None, transA=False, transB=False, alpha=1.0, beta=0.0, dtype=torch.float32
):
PanZezhongQY's avatar
PanZezhongQY committed
41
42
    A = A.T if transA else A
    B = B.T if transB else B
43
44
45
46
    result = alpha * torch.matmul(
        A if dtype != torch.float16 else A.to(torch.float32),
        B if dtype != torch.float16 else B.to(torch.float32),
    ).to(dtype)
PanZezhongQY's avatar
PanZezhongQY committed
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
    if C is not None:
        result += beta * C if dtype != torch.float16 else C.to(torch.float32)
    if PROFILE:
        torch.cuda.synchronize()
    return result


def test(
    lib,
    handle,
    torch_device,
    alpha,
    beta,
    transA,
    transB,
    a_shape,
    b_shape,
    c_shape,
    y_shape,
    a_stride=None,
    b_stride=None,
    c_stride=None,
    y_stride=None,
    dtype=torch.float16,
):
    print(
73
        f"Testing GEMM on {torch_device} with transA: {transA} transB: {transB} "
PanZezhongQY's avatar
PanZezhongQY committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
        f"a_shape:{a_shape} b_shape:{b_shape} c_shape:{c_shape} y_shape:{y_shape} "
        f"a_stride:{a_stride} b_stride:{b_stride} c_stride:{c_stride} y_stride:{y_stride} dtype:{dtype}"
    )

    a = torch.rand(a_shape, dtype=dtype).to(torch_device)
    b = torch.rand(b_shape, dtype=dtype).to(torch_device)
    c = torch.rand(c_shape, dtype=dtype).to(torch_device) if c_shape else None
    y = torch.rand(y_shape, dtype=dtype).to(torch_device)

    if a_stride is not None:
        a = rearrange_tensor(a, a_stride)
    if b_stride is not None:
        b = rearrange_tensor(b, b_stride)
    if c_stride is not None and c is not None:
        c = rearrange_tensor(c, c_stride)
    if y_stride is not None:
        y = rearrange_tensor(y, y_stride)

    for i in range(NUM_PRERUN if PROFILE else 1):
        ans = gemm(a, b, c, transA, transB, alpha, beta, dtype)
    if PROFILE:
        start_time = time.time()
        for i in range(NUM_ITERATIONS):
            _ = gemm(a, b, c, transA, transB, alpha, beta, dtype)
        elapsed = (time.time() - start_time) / NUM_ITERATIONS
        print(f"pytorch time: {elapsed :6f}")

    a_tensor = to_tensor(a, lib)
    b_tensor = to_tensor(b, lib)
    c_tensor = to_tensor(c, lib) if c is not None else None
    y_tensor = to_tensor(y, lib)
    descriptor = infiniopGEMMDescriptor_t()
    check_error(
        lib.infiniopCreateGEMMDescriptor(
            handle,
            ctypes.byref(descriptor),
            y_tensor.descriptor,
            a_tensor.descriptor,
            b_tensor.descriptor,
            c_tensor.descriptor if c_tensor else None,
            alpha,
            beta,
            transA,
            transB,
        )
    )

    # Invalidate the shape and strides in the descriptor to prevent them from being directly used by the kernel
    a_tensor.descriptor.contents.invalidate()
    b_tensor.descriptor.contents.invalidate()
    if c_tensor is not None:
        c_tensor.descriptor.contents.invalidate()
    y_tensor.descriptor.contents.invalidate()

    workspace_size = ctypes.c_uint64(0)
    check_error(
130
        lib.infiniopGetGEMMWorkspaceSize(descriptor, ctypes.byref(workspace_size))
PanZezhongQY's avatar
PanZezhongQY committed
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
    )
    workspace = torch.zeros(int(workspace_size.value), dtype=torch.uint8).to(
        torch_device
    )
    workspace_ptr = ctypes.cast(workspace.data_ptr(), ctypes.POINTER(ctypes.c_uint8))

    for i in range(NUM_PRERUN if PROFILE else 1):
        check_error(
            lib.infiniopGEMM(
                descriptor,
                workspace_ptr,
                workspace_size,
                y_tensor.data,
                a_tensor.data,
                b_tensor.data,
                c_tensor.data if c_tensor else None,
                None,
            )
        )
    if PROFILE:
        start_time = time.time()
        for i in range(NUM_ITERATIONS):
            check_error(
                lib.infiniopGEMM(
                    descriptor,
                    workspace_ptr,
                    workspace_size,
                    y_tensor.data,
                    a_tensor.data,
                    b_tensor.data,
                    c_tensor.data if c_tensor else None,
                    None,
                )
            )
        elapsed = (time.time() - start_time) / NUM_ITERATIONS
        print(f"    lib time: {elapsed :6f}")

    assert torch.allclose(y, ans, atol=0, rtol=1e-2)
    check_error(lib.infiniopDestroyGEMMDescriptor(descriptor))


def test_cpu(lib, test_cases):
    device = DeviceEnum.DEVICE_CPU
    handle = create_handle(lib, device)
    for (
        alpha,
        beta,
        transA,
        transB,
        a_shape,
        b_shape,
        c_shape,
        y_shape,
        a_stride,
        b_stride,
        c_stride,
        y_stride,
    ) in test_cases:
189
        # fmt: off
PanZezhongQY's avatar
PanZezhongQY committed
190
191
        test(lib, handle, "cpu", alpha, beta, transA, transB, a_shape, b_shape, c_shape, y_shape, a_stride, b_stride, c_stride, y_stride, dtype=torch.float16)
        test(lib, handle, "cpu", alpha, beta, transA, transB, a_shape, b_shape, c_shape, y_shape, a_stride, b_stride, c_stride, y_stride, dtype=torch.float32)
192
        # fmt: on
PanZezhongQY's avatar
PanZezhongQY committed
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    destroy_handle(lib, handle)


def test_cuda(lib, test_cases):
    device = DeviceEnum.DEVICE_CUDA
    handle = create_handle(lib, device)
    for (
        alpha,
        beta,
        transA,
        transB,
        a_shape,
        b_shape,
        c_shape,
        y_shape,
        a_stride,
        b_stride,
        c_stride,
        y_stride,
    ) in test_cases:
213
        # fmt: off
PanZezhongQY's avatar
PanZezhongQY committed
214
215
        test(lib, handle, "cuda", alpha, beta, transA, transB, a_shape, b_shape, c_shape, y_shape, a_stride, b_stride, c_stride, y_stride, dtype=torch.float16)
        test(lib, handle, "cuda", alpha, beta, transA, transB, a_shape, b_shape, c_shape, y_shape, a_stride, b_stride, c_stride, y_stride, dtype=torch.float32)
216
        # fmt: on
PanZezhongQY's avatar
PanZezhongQY committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    destroy_handle(lib, handle)


def test_bang(lib, test_cases):
    import torch_mlu

    device = DeviceEnum.DEVICE_BANG
    handle = create_handle(lib, device)

    for (
        alpha,
        beta,
        transA,
        transB,
        a_shape,
        b_shape,
        c_shape,
        y_shape,
        a_stride,
        b_stride,
        c_stride,
        y_stride,
    ) in test_cases:
240
        # fmt: off
PanZezhongQY's avatar
PanZezhongQY committed
241
242
        test(lib, handle, "mlu", alpha, beta, transA, transB, a_shape, b_shape, c_shape, y_shape, a_stride, b_stride, c_stride, y_stride, dtype=torch.float16)
        test(lib, handle, "mlu", alpha, beta, transA, transB, a_shape, b_shape, c_shape, y_shape, a_stride, b_stride, c_stride, y_stride, dtype=torch.float32)
243
        # fmt: on
PanZezhongQY's avatar
PanZezhongQY committed
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
355
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
    destroy_handle(lib, handle)


if __name__ == "__main__":
    test_cases = [
        # alpha, beta, transA, transB, a_shape, b_shape, c_shape, y_shape, a_stride, b_stride, c_stride, y_stride
        (
            1.0,
            1.0,
            False,
            False,
            (1, 2048),
            (2048, 2048),
            (1, 2048),
            (1, 2048),
            None,
            None,
            None,
            None,
        ),
        (
            1.0,
            1.0,
            True,
            True,
            (2048, 4),
            (2048, 2048),
            (4, 2048),
            (4, 2048),
            None,
            None,
            None,
            None,
        ),
        (
            1.0,
            1.0,
            False,
            True,
            (1, 2048),
            (1000, 2048),
            (1000),
            (1, 1000),
            None,
            None,
            None,
            None,
        ),
        (
            1.0,
            1.0,
            True,
            False,
            (2048, 4),
            (2048, 2048),
            (2048),
            (4, 2048),
            (4096, 1),
            (4096, 1),
            (2,),
            (4096, 1),
        ),
        (
            1.0,
            1.0,
            False,
            False,
            (3, 1, 2048),
            (3, 2048, 2048),
            (1,),
            (3, 1, 2048),
            None,
            None,
            None,
            None,
        ),
        (
            1.0,
            1.0,
            True,
            False,
            (2048, 4),
            (2048, 2048),
            None,
            (4, 2048),
            (4096, 1),
            (4096, 1),
            (2,),
            (4096, 1),
        ),
    ]
    args = get_args()
    lib = open_lib()

    lib.infiniopCreateGEMMDescriptor.restype = c_int32
    lib.infiniopCreateGEMMDescriptor.argtypes = [
        infiniopHandle_t,
        POINTER(infiniopGEMMDescriptor_t),
        infiniopTensorDescriptor_t,
        infiniopTensorDescriptor_t,
        infiniopTensorDescriptor_t,
        infiniopTensorDescriptor_t,
        c_float,
        c_float,
        c_bool,
        c_bool,
    ]

    lib.infiniopGetGEMMWorkspaceSize.restype = c_int32
    lib.infiniopGetGEMMWorkspaceSize.argtypes = [
        infiniopGEMMDescriptor_t,
        POINTER(c_uint64),
    ]

    lib.infiniopGEMM.restype = c_int32
    lib.infiniopGEMM.argtypes = [
        infiniopGEMMDescriptor_t,
        c_void_p,
        c_uint64,
        c_void_p,
        c_void_p,
        c_void_p,
        c_void_p,
        c_void_p,
    ]

    lib.infiniopDestroyGEMMDescriptor.restype = c_int32
    lib.infiniopDestroyGEMMDescriptor.argtypes = [
        infiniopGEMMDescriptor_t,
    ]

    if args.cpu:
        test_cpu(lib, test_cases)
    if args.cuda:
        test_cuda(lib, test_cases)
    if args.bang:
        test_bang(lib, test_cases)
    if not (args.cpu or args.cuda or args.bang):
        test_cpu(lib, test_cases)
    print("\033[92mTest passed!\033[0m")