add.py 6.64 KB
Newer Older
PanZezhong's avatar
PanZezhong committed
1
import torch
PanZezhongQY's avatar
PanZezhongQY committed
2
import ctypes
PanZezhong's avatar
PanZezhong committed
3
4
from ctypes import POINTER, Structure, c_int32, c_void_p, c_uint64
from libinfiniop import (
PanZezhongQY's avatar
PanZezhongQY committed
5
6
    infiniopHandle_t,
    infiniopTensorDescriptor_t,
PanZezhong's avatar
PanZezhong committed
7
8
9
    open_lib,
    to_tensor,
    get_test_devices,
PanZezhongQY's avatar
PanZezhongQY committed
10
    check_error,
PanZezhong's avatar
PanZezhong committed
11
12
13
14
15
16
17
    rearrange_if_needed,
    test_operator,
    get_args,
    debug,
    get_tolerance,
    profile_operation,
    create_workspace,
PanZezhongQY's avatar
PanZezhongQY committed
18
19
)
from enum import Enum, auto
PanZezhong's avatar
PanZezhong committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

# ==============================================================================
#  Configuration (Internal Use Only)
# ==============================================================================
# These are not meant to be imported from other modules
_TEST_CASES_ = [
    # shape, a_stride, b_stride, c_stride
    ((13, 4), None, None, None),
    ((13, 4), (10, 1), (10, 1), (10, 1)),
    ((13, 4), (0, 1), None, None),
    ((13, 4, 4), None, None, None),
    ((13, 4, 4), (20, 4, 1), (20, 4, 1), (20, 4, 1)),
    ((13, 4, 4), (4, 0, 1), (0, 4, 1), None),
    ((16, 5632), None, None, None),
    ((16, 5632), (13312, 1), (13312, 1), (13312, 1)),
    ((4, 4, 5632), None, None, None),
    ((4, 4, 5632), (45056, 5632, 1), (45056, 5632, 1), (45056, 5632, 1)),
]
PanZezhongQY's avatar
PanZezhongQY committed
38
39
40
41
42
43
44
45


class Inplace(Enum):
    OUT_OF_PLACE = auto()
    INPLACE_A = auto()
    INPLACE_B = auto()


PanZezhong's avatar
PanZezhong committed
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
# Inplace options applied for each test case in _TEST_CASES_
_INPLACE = [
    Inplace.OUT_OF_PLACE,
    Inplace.INPLACE_A,
    Inplace.INPLACE_B,
]

# Form the test cases by appending each element of _INPLACE to each tuple in _TEST_CASES_
_TEST_CASES = [
    test_case + (inplace_item,)
    for test_case in _TEST_CASES_
    for inplace_item in _INPLACE
]

# Data types used for testing
_TENSOR_DTYPES = [torch.float16, torch.float32]

# Tolerance map for different data types
_TOLERANCE_MAP = {
    torch.float16: {"atol": 1e-4, "rtol": 1e-2},
}

DEBUG = False
PROFILE = False
NUM_PRERUN = 10
NUM_ITERATIONS = 1000


PanZezhongQY's avatar
PanZezhongQY committed
74
75
76
77
78
79
80
81
82
83
84
class AddDescriptor(Structure):
    _fields_ = [("device", c_int32)]


infiniopAddDescriptor_t = POINTER(AddDescriptor)


def add(x, y):
    return torch.add(x, y)


PanZezhong's avatar
PanZezhong committed
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
def process_tensors(c, c_strides, a, a_stride, b, b_stride, inplace):
    """
    rearrange the tensors if needed and apply the inplace config.
    if inplace is true and the output (i.e., c) is placed to the broadcasted input,
    the inplace config is ignored and out-of-place is used
    """
    original_c_strides = c_strides if c_strides else c.stride()

    def _rearrange(tensor, strides):
        if strides and 0 in strides:
            tensor.set_(tensor.untyped_storage(), 0, tensor.shape, strides)
            return tensor
        else:
            return rearrange_if_needed(tensor, strides)

    a, b, c = [
        _rearrange(tensor, stride)
        for tensor, stride in zip([a, b, c], [a_stride, b_stride, c_strides])
    ]
    c = (
        c
        if inplace == Inplace.OUT_OF_PLACE
        else (a if inplace == Inplace.INPLACE_A else b)
    )
    # if inplace is true and c has broadcasted config, reset it to the original unbroadcasted strides
    if 0 in c.stride():
        c.set_(c.untyped_storage(), 0, c.shape, original_c_strides)

    return a, b, c


PanZezhongQY's avatar
PanZezhongQY committed
116
117
118
119
def test(
    lib,
    handle,
    torch_device,
PanZezhong's avatar
PanZezhong committed
120
121
122
123
    shape,
    a_stride=None,
    b_stride=None,
    c_stride=None,
PanZezhongQY's avatar
PanZezhongQY committed
124
    inplace=Inplace.OUT_OF_PLACE,
PanZezhong's avatar
PanZezhong committed
125
126
    dtype=torch.float16,
    sync=None,
PanZezhongQY's avatar
PanZezhongQY committed
127
128
):
    print(
PanZezhong's avatar
PanZezhong committed
129
130
        f"Testing Add on {torch_device} with shape:{shape} a_stride:{a_stride} b_stride:{b_stride} c_stride:{c_stride} "
        f"dtype:{dtype} inplace:{inplace}"
PanZezhongQY's avatar
PanZezhongQY committed
131
132
    )

PanZezhong's avatar
PanZezhong committed
133
134
135
136
    a = torch.rand(shape, dtype=dtype).to(torch_device)
    b = torch.rand(shape, dtype=dtype).to(torch_device)
    c = torch.rand(shape, dtype=dtype).to(torch_device)
    a, b, c = process_tensors(c, c_stride, a, a_stride, b, b_stride, inplace)
PanZezhongQY's avatar
PanZezhongQY committed
137
138
139

    ans = add(a, b)

PanZezhong's avatar
PanZezhong committed
140
    a_tensor, b_tensor = [to_tensor(tensor, lib) for tensor in [a, b]]
141
142
143
144
145
    c_tensor = (
        to_tensor(c, lib)
        if inplace == Inplace.OUT_OF_PLACE
        else (a_tensor if inplace == Inplace.INPLACE_A else b_tensor)
    )
PanZezhong's avatar
PanZezhong committed
146
147
    if sync is not None:
        sync()
PanZezhongQY's avatar
PanZezhongQY committed
148

PanZezhong's avatar
PanZezhong committed
149
    descriptor = infiniopAddDescriptor_t()
PanZezhongQY's avatar
PanZezhongQY committed
150
151
152
153
154
155
156
157
158
159
160
    check_error(
        lib.infiniopCreateAddDescriptor(
            handle,
            ctypes.byref(descriptor),
            c_tensor.descriptor,
            a_tensor.descriptor,
            b_tensor.descriptor,
        )
    )

    # Invalidate the shape and strides in the descriptor to prevent them from being directly used by the kernel
PanZezhong's avatar
PanZezhong committed
161
162
    for tensor in [a_tensor, b_tensor, c_tensor]:
        tensor.destroyDesc(lib)
PanZezhongQY's avatar
PanZezhongQY committed
163

PanZezhong's avatar
PanZezhong committed
164
    workspace_size = c_uint64(0)
PanZezhongQY's avatar
PanZezhongQY committed
165
    check_error(
PanZezhong's avatar
PanZezhong committed
166
        lib.infiniopGetAddWorkspaceSize(descriptor, ctypes.byref(workspace_size))
PanZezhongQY's avatar
PanZezhongQY committed
167
    )
PanZezhong's avatar
PanZezhong committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    workspace = create_workspace(workspace_size.value, c.device)

    def lib_add():
        check_error(
            lib.infiniopAdd(
                descriptor,
                workspace.data_ptr() if workspace is not None else None,
                workspace_size.value,
                c_tensor.data,
                a_tensor.data,
                b_tensor.data,
                None,
            )
        )
PanZezhongQY's avatar
PanZezhongQY committed
182

PanZezhong's avatar
PanZezhong committed
183
    lib_add()
PanZezhongQY's avatar
PanZezhongQY committed
184

PanZezhong's avatar
PanZezhong committed
185
186
187
188
    atol, rtol = get_tolerance(_TOLERANCE_MAP, dtype)
    if DEBUG:
        debug(c, ans, atol=atol, rtol=rtol)
    assert torch.allclose(c, ans, atol=atol, rtol=rtol)
PanZezhongQY's avatar
PanZezhongQY committed
189

PanZezhong's avatar
PanZezhong committed
190
191
    # Profiling workflow
    if PROFILE:
192
        # fmt: off
PanZezhong's avatar
PanZezhong committed
193
194
        profile_operation("PyTorch", lambda: add(a, b), torch_device, NUM_PRERUN, NUM_ITERATIONS)
        profile_operation("    lib", lambda: lib_add(), torch_device, NUM_PRERUN, NUM_ITERATIONS)
195
        # fmt: on
PanZezhong's avatar
PanZezhong committed
196
    check_error(lib.infiniopDestroyAddDescriptor(descriptor))
PanZezhongQY's avatar
PanZezhongQY committed
197
198
199
200
201


if __name__ == "__main__":
    args = get_args()
    lib = open_lib()
PanZezhong's avatar
PanZezhong committed
202

PanZezhongQY's avatar
PanZezhongQY committed
203
204
205
206
207
208
209
210
    lib.infiniopCreateAddDescriptor.restype = c_int32
    lib.infiniopCreateAddDescriptor.argtypes = [
        infiniopHandle_t,
        POINTER(infiniopAddDescriptor_t),
        infiniopTensorDescriptor_t,
        infiniopTensorDescriptor_t,
        infiniopTensorDescriptor_t,
    ]
PanZezhong's avatar
PanZezhong committed
211
212
213
214
215
216
217

    lib.infiniopGetAddWorkspaceSize.restype = c_int32
    lib.infiniopGetAddWorkspaceSize.argtypes = [
        infiniopAddDescriptor_t,
        POINTER(c_uint64),
    ]

PanZezhongQY's avatar
PanZezhongQY committed
218
219
220
221
    lib.infiniopAdd.restype = c_int32
    lib.infiniopAdd.argtypes = [
        infiniopAddDescriptor_t,
        c_void_p,
PanZezhong's avatar
PanZezhong committed
222
223
        c_uint64,
        c_void_p,
PanZezhongQY's avatar
PanZezhongQY committed
224
225
226
227
        c_void_p,
        c_void_p,
        c_void_p,
    ]
PanZezhong's avatar
PanZezhong committed
228

PanZezhongQY's avatar
PanZezhongQY committed
229
230
231
232
233
    lib.infiniopDestroyAddDescriptor.restype = c_int32
    lib.infiniopDestroyAddDescriptor.argtypes = [
        infiniopAddDescriptor_t,
    ]

PanZezhong's avatar
PanZezhong committed
234
235
236
237
238
239
240
241
242
    # Configure testing options
    DEBUG = args.debug
    PROFILE = args.profile
    NUM_PRERUN = args.num_prerun
    NUM_ITERATIONS = args.num_iterations

    for device in get_test_devices(args):
        test_operator(lib, device, test, _TEST_CASES, _TENSOR_DTYPES)

PanZezhongQY's avatar
PanZezhongQY committed
243
    print("\033[92mTest passed!\033[0m")