logsoftmax.py 9.32 KB
Newer Older
gongchensu's avatar
gongchensu 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
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
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
130
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
189
190
191
192
193
194
195
196
197
198
199
200
201
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
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
import torch
import ctypes
from ctypes import c_uint64
from libinfiniop import (
    LIBINFINIOP,
    TestTensor,
    get_test_devices,
    check_error,
    test_operator,
    get_args,
    debug,
    get_tolerance,
    profile_operation,
    TestWorkspace,
    InfiniDtype,
    InfiniDtypeNames,
    InfiniDeviceNames,
    infiniopOperatorDescriptor_t,
)
from enum import Enum, auto

# ==============================================================================
#  Configuration (Internal Use Only)
# ==============================================================================
# These are not meant to be imported from other modules
_TEST_CASES_ = [
    # shape, x_stride, y_stride
    ((3, 3), None, None),
    ((32, 512), None, None),
    ((32, 512), (1024, 1), (1024, 1)),
    ((32, 5, 5), None, None),
    ((32, 20, 512), None, None),
    ((32, 20, 512), (20480, 512, 1), None),
    ((28, 15, 15), None, None),
    ((1, 1000), None, None),
    ((16, 50257), None, None),
    ((4, 8, 256), None, None),
    ((2, 16, 1024), None, None),
]

# Data types used for testing
_TENSOR_DTYPES = [InfiniDtype.F16, InfiniDtype.BF16, InfiniDtype.F32]

# Tolerance map for different data types
_TOLERANCE_MAP = {
    InfiniDtype.F16: {"atol": 1e-3, "rtol": 1e-2},
    InfiniDtype.BF16: {"atol": 5e-3, "rtol": 1e-2},
    InfiniDtype.F32: {"atol": 1e-5, "rtol": 1e-5},
}

# Mixed precision test cases - support y_dtype == x_dtype or y_dtype == F32
_MIXED_PRECISION_CASES = [
    (InfiniDtype.F16, InfiniDtype.F32),
    (InfiniDtype.BF16, InfiniDtype.F32),
    (InfiniDtype.F16, InfiniDtype.F16),
    (InfiniDtype.BF16, InfiniDtype.BF16),
    (InfiniDtype.F32, InfiniDtype.F32),
]


class Inplace(Enum):
    OUT_OF_PLACE = auto()
    INPLACE_X = auto()


_INPLACE = [
    Inplace.INPLACE_X,
    Inplace.OUT_OF_PLACE,
]

_TEST_CASES = [
    test_case + (inplace_item,)
    for test_case in _TEST_CASES_
    for inplace_item in _INPLACE
]

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


def logsoftmax(x):
    """PyTorch reference implementation of log_softmax"""
    return torch.nn.functional.log_softmax(x.to(torch.float32), dim=-1)


def test(
    handle,
    device,
    shape,
    x_stride=None,
    y_stride=None,
    inplace=Inplace.OUT_OF_PLACE,
    dtype=InfiniDtype.F16,
    sync=None,
):
    print(
        f"Testing LogSoftmax on {InfiniDeviceNames[device]} with shape:{shape} x_stride:{x_stride} y_stride:{y_stride} dtype:{InfiniDtypeNames[dtype]} inplace:{inplace}"
    )

    x = TestTensor(shape, x_stride, dtype, device)
    ans = logsoftmax(x.actual_tensor())

    # Convert answer to match input dtype for default behavior
    if dtype == InfiniDtype.F16:
        ans = ans.to(torch.float16)
    elif dtype == InfiniDtype.BF16:
        ans = ans.to(torch.bfloat16)
    elif dtype == InfiniDtype.F32:
        ans = ans.to(torch.float32)

    if inplace == Inplace.INPLACE_X:
        y = x
    else:
        y = TestTensor(shape, y_stride, dtype, device)  # Default: same dtype as input

    if sync is not None:
        sync()

    descriptor = infiniopOperatorDescriptor_t()
    status = LIBINFINIOP.infiniopCreateLogSoftmaxDescriptor(
        handle, ctypes.byref(descriptor), y.descriptor, x.descriptor
    )
    check_error(status)

    # Invalidate the shape and strides in the descriptor to prevent them from being directly used by the kernel
    x.destroy_desc()
    y.destroy_desc()

    workspace_size = c_uint64(0)
    status = LIBINFINIOP.infiniopGetLogSoftmaxWorkspaceSize(
        descriptor, ctypes.byref(workspace_size)
    )
    check_error(status)
    workspace = TestWorkspace(workspace_size.value, x.device)

    def lib_logsoftmax():
        check_error(
            LIBINFINIOP.infiniopLogSoftmax(
                descriptor,
                workspace.data(),
                workspace_size.value,
                y.data(),
                x.data(),
                None,
            )
        )

    lib_logsoftmax()

    if sync is not None:
        sync()

    # Use tolerance based on input dtype for numerical stability
    atol, rtol = get_tolerance(_TOLERANCE_MAP, dtype)

    # Always print debug info for failed cases
    actual = y.actual_tensor()
    max_diff = torch.max(torch.abs(actual - ans))
    is_close = torch.allclose(actual, ans, atol=atol, rtol=rtol)

    if DEBUG or not is_close:
        print(f"\n=== Debug Info ===")
        print(f"Shape: {shape}, Stride: {x_stride}, Dtype: {dtype}")
        print(f"Input tensor: {x.torch_tensor()}")
        print(f"Expected output: {ans}")
        print(f"Actual output: {actual}")
        print(f"Max diff: {max_diff}")
        print(f"Tolerance: atol={atol}, rtol={rtol}")
        print(f"Is close: {is_close}")
        print(f"First few values - Actual: {actual.flatten()[:5]}")
        print(f"First few values - Expected: {ans.flatten()[:5]}")
        if DEBUG:
            debug(actual, ans, atol=atol, rtol=rtol)

    assert is_close

    # Profiling workflow
    if PROFILE:
        # fmt: off
        profile_operation("PyTorch", lambda: logsoftmax(x.torch_tensor()), device, NUM_PRERUN, NUM_ITERATIONS)
        profile_operation("    lib", lambda: lib_logsoftmax(), device, NUM_PRERUN, NUM_ITERATIONS)
        # fmt: on

    check_error(LIBINFINIOP.infiniopDestroyLogSoftmaxDescriptor(descriptor))


def test_mixed_precision(
    handle,
    device,
    shape,
    x_stride=None,
    y_stride=None,
    inplace=Inplace.OUT_OF_PLACE,
    x_dtype=InfiniDtype.F16,
    y_dtype=InfiniDtype.F32,
    sync=None,
):
    print(
        f"Testing LogSoftmax (Mixed) on {InfiniDeviceNames[device]} with shape:{shape} x_stride:{x_stride} y_stride:{y_stride} x_dtype:{InfiniDtypeNames[x_dtype]} y_dtype:{InfiniDtypeNames[y_dtype]} inplace:{inplace}"
    )

    x = TestTensor(shape, x_stride, x_dtype, device)
    ans = logsoftmax(x.actual_tensor())

    # Convert answer to target dtype for comparison
    if y_dtype == InfiniDtype.F16:
        ans = ans.to(torch.float16)
    elif y_dtype == InfiniDtype.BF16:
        ans = ans.to(torch.bfloat16)
    elif y_dtype == InfiniDtype.F32:
        ans = ans.to(torch.float32)

    if inplace == Inplace.INPLACE_X:
        # For inplace operations, input and output must have the same dtype
        if x_dtype != y_dtype:
            print(
                f"Skipping inplace test: x_dtype ({InfiniDtypeNames[x_dtype]}) != y_dtype ({InfiniDtypeNames[y_dtype]})"
            )
            return
        y = x
    else:
        y = TestTensor(shape, y_stride, y_dtype, device)

    if sync is not None:
        sync()

    descriptor = infiniopOperatorDescriptor_t()
    check_error(
        LIBINFINIOP.infiniopCreateLogSoftmaxDescriptor(
            handle, ctypes.byref(descriptor), y.descriptor, x.descriptor
        )
    )

    # Invalidate the shape and strides in the descriptor to prevent them from being directly used by the kernel
    x.destroy_desc()
    y.destroy_desc()

    workspace_size = c_uint64(0)
    check_error(
        LIBINFINIOP.infiniopGetLogSoftmaxWorkspaceSize(
            descriptor, ctypes.byref(workspace_size)
        )
    )
    workspace = TestWorkspace(workspace_size.value, x.device)

    def lib_logsoftmax():
        check_error(
            LIBINFINIOP.infiniopLogSoftmax(
                descriptor,
                workspace.data(),
                workspace_size.value,
                y.data(),
                x.data(),
                None,
            )
        )

    lib_logsoftmax()

    if sync is not None:
        sync()

    # Use tolerance based on output dtype for mixed precision cases
    atol, rtol = get_tolerance(_TOLERANCE_MAP, y_dtype)

    # Ensure both tensors have the same dtype for comparison
    y_tensor = y.actual_tensor()
    if y_tensor.dtype != ans.dtype:
        y_tensor = y_tensor.to(ans.dtype)

    if DEBUG:
        debug(y_tensor, ans, atol=atol, rtol=rtol)
    assert torch.allclose(y_tensor, ans, atol=atol, rtol=rtol)

    # Profiling workflow
    if PROFILE:
        # fmt: off
        profile_operation("PyTorch", lambda: logsoftmax(x.torch_tensor()), device, NUM_PRERUN, NUM_ITERATIONS)
        profile_operation("    lib", lambda: lib_logsoftmax(), device, NUM_PRERUN, NUM_ITERATIONS)
        # fmt: on

    check_error(LIBINFINIOP.infiniopDestroyLogSoftmaxDescriptor(descriptor))


if __name__ == "__main__":
    args = get_args()

    # 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 standard cases (fp32 output)
        test_operator(device, test, _TEST_CASES, _TENSOR_DTYPES)

        # Test mixed precision cases
        from libinfiniop import create_handle, destroy_handle, get_sync_func

        handle = create_handle()
        sync = get_sync_func(device)
        try:
            for x_dtype, y_dtype in _MIXED_PRECISION_CASES:
                for shape, x_stride, y_stride, inplace in _TEST_CASES[
                    :5
                ]:  # Test subset for mixed precision
                    test_mixed_precision(
                        handle,
                        device,
                        shape,
                        x_stride,
                        y_stride,
                        inplace,
                        x_dtype,
                        y_dtype,
                        sync,
                    )
        finally:
            destroy_handle(handle)

    print("\033[92mTest passed!\033[0m")