rearrange.py 5.68 KB
Newer Older
xgqdut2016's avatar
xgqdut2016 committed
1
import torch
PanZezhongQY's avatar
PanZezhongQY committed
2
import ctypes
3
from ctypes import POINTER, Structure, c_int32, c_void_p
xgqdut2016's avatar
xgqdut2016 committed
4
from libinfiniop import (
PanZezhongQY's avatar
PanZezhongQY committed
5
6
    infiniopHandle_t,
    infiniopTensorDescriptor_t,
xgqdut2016's avatar
xgqdut2016 committed
7
8
9
    open_lib,
    to_tensor,
    get_test_devices,
PanZezhongQY's avatar
PanZezhongQY committed
10
    check_error,
xgqdut2016's avatar
xgqdut2016 committed
11
    rearrange_if_needed,
12
    rearrange_tensor,
xgqdut2016's avatar
xgqdut2016 committed
13
14
15
16
17
    test_operator,
    get_args,
    debug,
    get_tolerance,
    profile_operation,
PanZezhongQY's avatar
PanZezhongQY committed
18
19
)

pwhMass's avatar
pwhMass committed
20
21
22
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
def row_major_strides(shape):
    """生成张量的行优先(C风格)stride
    
    Args:
        shape: 张量形状
    
    Returns:
        行优先strides列表
    """
    # 行优先 (C风格,从最后一维到第一维)
    stride = 1
    strides = [1]
    for dim in reversed(shape[1:]):
        stride *= dim
        strides.insert(0, stride)
    return strides

def column_major_strides(shape):
    """生成张量的列优先(Fortran风格)stride
    
    Args:
        shape: 张量形状
    
    Returns:
        列优先strides列表
    """
    # 列优先 (Fortran风格,从第一维到最后一维)
    stride = 1
    strides = [stride]
    for dim in shape[:-1]:
        stride *= dim
        strides.append(stride)
    return strides



xgqdut2016's avatar
xgqdut2016 committed
56
57
58
59
60
# ==============================================================================
#  Configuration (Internal Use Only)
# ==============================================================================
# These are not meant to be imported from other modules
_TEST_CASES = [
pwhMass's avatar
pwhMass committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    # (shape, x_stride, y_stride)
    (
        (100, 100),  # shape
        (1, 100),    # x_stride
        (100, 1)     # y_stride
    ),
    (
        (4, 4),      # shape
        (1, 4),      # x_stride
        (4, 1)       # y_stride
    ),
    (
        (4, 6, 64),  # shape
        (64, 4*64, 1), # x_stride
        (6*64, 64, 1)  # y_stride
    ),
    (
        (2000, 2000), # shape
        (1, 2000),    # x_stride
        (2000, 1)     # y_stride
    ),
    (
        (2001, 2001), # shape
        (1, 2001),    # x_stride
        (2001, 1)     # y_stride
    ),
87
88
89
90
91
    (
        (2, 2, 2, 4), # shape
        (16, 8, 4, 1), # x_stride
        (16, 8, 1, 2)  # y_stride
    ),
pwhMass's avatar
pwhMass committed
92
93
94
95
96
97
98
99
100
101
    (
        (3, 4, 7, 53, 9), # shape
        row_major_strides((3, 4, 7, 53, 9)), # x_stride
        column_major_strides((3, 4, 7, 53, 9)) # y_stride
    ),
    (
        (3, 4, 50, 50, 5, 7), # shape
        row_major_strides((3, 4, 50, 50, 5, 7)),  # x_stride
        column_major_strides((3, 4, 50, 50, 5, 7)) # y_stride
    ),
xgqdut2016's avatar
xgqdut2016 committed
102
103
104
105
106
107
108
]

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

# Tolerance map for different data types
_TOLERANCE_MAP = {
xgqdut2016's avatar
xgqdut2016 committed
109
110
    torch.float16: {"atol": 0, "rtol": 0},
    torch.float32: {"atol": 0, "rtol": 0},
xgqdut2016's avatar
xgqdut2016 committed
111
112
113
114
115
116
117
}

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

PanZezhongQY's avatar
PanZezhongQY committed
118

119
class RearrangeDescriptor(Structure):
PanZezhongQY's avatar
PanZezhongQY committed
120
121
122
    _fields_ = [("device", c_int32)]


123
infiniopRearrangeDescriptor_t = POINTER(RearrangeDescriptor)
PanZezhongQY's avatar
PanZezhongQY committed
124
125


126
127
128
129
130
131
132
def rearrange_torch(x, x_shape, y_stride):
    y_ = x.clone()
    y_.set_(y_.untyped_storage(), 0, x_shape, y_stride)
    y_[:] = x.view_as(y_)
    return y_


PanZezhongQY's avatar
PanZezhongQY committed
133
134
135
136
def test(
    lib,
    handle,
    torch_device,
pwhMass's avatar
pwhMass committed
137
    shape,
PanZezhongQY's avatar
PanZezhongQY committed
138
139
    x_stride,
    y_stride,
140
    dtype=torch.float16,
141
    sync=None
PanZezhongQY's avatar
PanZezhongQY committed
142
143
):
    print(
pwhMass's avatar
pwhMass committed
144
        f"Testing Rerrange on {torch_device} with shape:{shape} x_stride:{x_stride} y_stride:{y_stride} dtype:{dtype}"
PanZezhongQY's avatar
PanZezhongQY committed
145
    )
xgqdut2016's avatar
xgqdut2016 committed
146

pwhMass's avatar
pwhMass committed
147
148
    x = torch.rand(shape, dtype=dtype).to(torch_device)
    y = torch.zeros(shape, dtype=dtype).to(torch_device)
xgqdut2016's avatar
xgqdut2016 committed
149

150
151
    rearrange_torch(x, shape, y_stride)

xgqdut2016's avatar
xgqdut2016 committed
152
153
154
155
    x, y = [
        rearrange_if_needed(tensor, stride)
        for tensor, stride in zip([x, y], [x_stride, y_stride])
    ]
pwhMass's avatar
pwhMass committed
156

xgqdut2016's avatar
xgqdut2016 committed
157
    x_tensor, y_tensor = [to_tensor(tensor, lib) for tensor in [x, y]]
158
159
160
    
    if sync is not None:
        sync()
xgqdut2016's avatar
xgqdut2016 committed
161

PanZezhongQY's avatar
PanZezhongQY committed
162
163
164
165
166
167
168
169
    descriptor = infiniopRearrangeDescriptor_t()
    check_error(
        lib.infiniopCreateRearrangeDescriptor(
            handle, ctypes.byref(descriptor), y_tensor.descriptor, x_tensor.descriptor
        )
    )

    # Invalidate the shape and strides in the descriptor to prevent them from being directly used by the kernel
xgqdut2016's avatar
xgqdut2016 committed
170
    for tensor in [x_tensor, y_tensor]:
pwhMass's avatar
pwhMass committed
171
        tensor.destroyDesc(lib)
xgqdut2016's avatar
xgqdut2016 committed
172
173
174

    def lib_rearrange():
        check_error(
xgqdut2016's avatar
xgqdut2016 committed
175
            lib.infiniopRearrange(descriptor, y_tensor.data, x_tensor.data, None)
xgqdut2016's avatar
xgqdut2016 committed
176
        )
xgqdut2016's avatar
xgqdut2016 committed
177

xgqdut2016's avatar
xgqdut2016 committed
178
    lib_rearrange()
xgqdut2016's avatar
xgqdut2016 committed
179

xgqdut2016's avatar
xgqdut2016 committed
180
181
182
183
184
185
186
187
188
    # Validate results
    atol, rtol = get_tolerance(_TOLERANCE_MAP, dtype)
    if DEBUG:
        debug(x, y, atol=atol, rtol=rtol)
    assert torch.allclose(x, y, atol=atol, rtol=rtol)

    # Profiling workflow
    if PROFILE:
        # fmt: off
189
        profile_operation("PyTorch", lambda: rearrange_torch(x, shape, y_stride), torch_device, NUM_PRERUN, NUM_ITERATIONS)
xgqdut2016's avatar
xgqdut2016 committed
190
191
        profile_operation("    lib", lambda: lib_rearrange(), torch_device, NUM_PRERUN, NUM_ITERATIONS)
        # fmt: on
PanZezhongQY's avatar
PanZezhongQY committed
192
193
194
195
196
197
198

    check_error(lib.infiniopDestroyRearrangeDescriptor(descriptor))


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

PanZezhongQY's avatar
PanZezhongQY committed
200
201
202
203
204
205
206
    lib.infiniopCreateRearrangeDescriptor.restype = c_int32
    lib.infiniopCreateRearrangeDescriptor.argtypes = [
        infiniopHandle_t,
        POINTER(infiniopRearrangeDescriptor_t),
        infiniopTensorDescriptor_t,
        infiniopTensorDescriptor_t,
    ]
xgqdut2016's avatar
xgqdut2016 committed
207

PanZezhongQY's avatar
PanZezhongQY committed
208
209
210
211
212
213
214
    lib.infiniopRearrange.restype = c_int32
    lib.infiniopRearrange.argtypes = [
        infiniopRearrangeDescriptor_t,
        c_void_p,
        c_void_p,
        c_void_p,
    ]
xgqdut2016's avatar
xgqdut2016 committed
215

PanZezhongQY's avatar
PanZezhongQY committed
216
217
    lib.infiniopDestroyRearrangeDescriptor.restype = c_int32
    lib.infiniopDestroyRearrangeDescriptor.argtypes = [infiniopRearrangeDescriptor_t]
xgqdut2016's avatar
xgqdut2016 committed
218

xgqdut2016's avatar
xgqdut2016 committed
219
220
221
222
223
224
225
226
227
228
    # 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):
        test_operator(lib, device, test, _TEST_CASES, _TENSOR_DTYPES)

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