test_autograd.py 20.7 KB
Newer Older
Aarni Koskela's avatar
Aarni Koskela committed
1
from typing import Tuple
Tim Dettmers's avatar
Tim Dettmers committed
2

3
import pytest
Tim Dettmers's avatar
Tim Dettmers committed
4
5
import torch

6
import bitsandbytes as bnb
Aarni Koskela's avatar
Aarni Koskela committed
7
8
9
10
11
12
13
from tests.helpers import (
    BOOLEAN_TRIPLES,
    BOOLEAN_TUPLES,
    TRUE_FALSE,
    describe_dtype,
    get_test_dims,
    id_formatter,
14
)
Aarni Koskela's avatar
Aarni Koskela committed
15
16
17
18
19
20
21
22

TRANSPOSE_VALS = [(False, True), (False, False)]


@pytest.mark.parametrize("dim1", get_test_dims(16, 64, n=1), ids=id_formatter("dim1"))
@pytest.mark.parametrize("dim2", get_test_dims(32, 96, n=1), ids=id_formatter("dim2"))
@pytest.mark.parametrize("dim3", get_test_dims(32, 96, n=1), ids=id_formatter("dim3"))
@pytest.mark.parametrize("dim4", get_test_dims(32, 96, n=1), ids=id_formatter("dim4"))
Ruff's avatar
Ruff committed
23
24
25
26
27
@pytest.mark.parametrize(
    "funcs",
    [(torch.bmm, bnb.bmm_cublas), (torch.matmul, bnb.matmul_cublas)],
    ids=["func=bmm", "func=matmul"],
)
Aarni Koskela's avatar
Aarni Koskela committed
28
29
30
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16], ids=describe_dtype)
@pytest.mark.parametrize("req_grad", BOOLEAN_TUPLES, ids=id_formatter("req_grad"))
@pytest.mark.parametrize("transpose", BOOLEAN_TUPLES, ids=id_formatter("transpose"))
31
@pytest.mark.deprecated
Aarni Koskela's avatar
Aarni Koskela committed
32
def test_matmul(dim1, dim2, dim3, dim4, funcs, dtype, req_grad: Tuple[bool, bool], transpose: Tuple[bool, bool]):
33
34
    if dim2 > 0:
        dim2 = dim2 - (dim2 % 16)
Tim Dettmers's avatar
Tim Dettmers committed
35
36
    dim3 = dim3 - (dim3 % 16)
    dim4 = dim4 - (dim4 % 16)
Aarni Koskela's avatar
Aarni Koskela committed
37
    for i in range(25):
Tim Dettmers's avatar
Tim Dettmers committed
38
39
40
41
        # normal multiply
        if funcs[0] in [torch.mm, torch.matmul]:
            dimA = (dim2, dim3) if not transpose[0] else (dim3, dim2)
            dimB = (dim3, dim4) if not transpose[1] else (dim4, dim3)
42
43
            A = torch.randn(size=dimA, device="cuda", requires_grad=req_grad[0])
            B = torch.randn(size=dimB, device="cuda", requires_grad=req_grad[1])
Ruff's avatar
Ruff committed
44
            target = torch.randn(size=(dim2, dim4), device="cuda", requires_grad=req_grad[1])
Tim Dettmers's avatar
Tim Dettmers committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
            torch.nn.init.xavier_uniform_(B)

            if not transpose[0] and not transpose[1]:
                out_torch = funcs[0](A, B)
                out_bnb = funcs[1](A, B)
            elif not transpose[0] and transpose[1]:
                out_torch = funcs[0](A, B.t())
                out_bnb = funcs[1](A, B.t())
            elif transpose[0] and not transpose[1]:
                out_torch = funcs[0](A.t(), B)
                out_bnb = funcs[1](A.t(), B)
            elif transpose[0] and transpose[1]:
                out_torch = funcs[0](A.t(), B.t())
                out_bnb = funcs[1](A.t(), B.t())

            n = out_bnb.numel()
            idx = torch.isclose(out_bnb, out_torch, atol=0.01, rtol=0.1)
62
            assert (idx == 0).sum().item() < n * 0.0175
Tim Dettmers's avatar
Tim Dettmers committed
63
            idx = torch.isclose(out_bnb, out_torch, atol=0.035, rtol=0.2)
64
            assert (idx == 0).sum().item() < n * 0.001
Tim Dettmers's avatar
Tim Dettmers committed
65
66
67
68
69
70
71
72
73
74
75

            if any(req_grad):
                out_bnb.data.copy_(out_torch)
                torch.cuda.synchronize()
                loss_bnb = torch.nn.functional.mse_loss(out_bnb, target).mean()
                loss_bnb.backward()
                gradA1 = A.grad
                gradB1 = B.grad
                A.grad = None
                B.grad = None

Ruff's avatar
Ruff committed
76
                loss_torch = torch.nn.functional.mse_loss(out_torch, target).mean()
Tim Dettmers's avatar
Tim Dettmers committed
77
78
79
80
81
82
83
                loss_torch.backward()
                gradA2 = A.grad
                gradB2 = B.grad
                A.grad = None
                B.grad = None

            if req_grad[0]:
Ruff's avatar
Ruff committed
84
                torch.testing.assert_close(gradA1, gradA2, atol=0.015, rtol=0.1)
Tim Dettmers's avatar
Tim Dettmers committed
85
86
87
            if req_grad[1]:
                n = gradB1.numel()
                idx = torch.isclose(gradB1, gradB2, atol=0.06, rtol=0.3)
88
                assert (idx == 0).sum().item() < n * 0.1
Tim Dettmers's avatar
Tim Dettmers committed
89
                idx = torch.isclose(gradB1, gradB2, atol=0.10, rtol=0.3)
90
                assert (idx == 0).sum().item() < n * 0.02
Ruff's avatar
Ruff committed
91
                torch.testing.assert_close(gradB1, gradB2, atol=0.18, rtol=0.3)
Tim Dettmers's avatar
Tim Dettmers committed
92
93
94

        # batched matrix multiply
        if funcs[0] in [torch.bmm, torch.matmul]:
95
            A = torch.randn(
96
97
98
                size=(dim1, dim2, dim3),
                device="cuda",
                requires_grad=req_grad[0],
99
100
            )
            B = torch.randn(
101
102
103
                size=(dim1, dim3, dim4),
                device="cuda",
                requires_grad=req_grad[1],
104
105
            )
            target = torch.randn(
106
107
108
                size=(dim1, dim2, dim4),
                device="cuda",
                requires_grad=req_grad[1],
109
            )
Tim Dettmers's avatar
Tim Dettmers committed
110
111
112
113
114
115
116
            torch.nn.init.xavier_uniform_(B)

            out_torch = funcs[0](A, B)
            out_bnb = funcs[1](A, B)

            n = out_bnb.numel()
            idx = torch.isclose(out_bnb, out_torch, atol=0.01, rtol=0.1)
117
            assert (idx == 0).sum().item() < n * 0.01
Ruff's avatar
Ruff committed
118
            torch.testing.assert_close(out_bnb, out_torch, atol=0.027, rtol=0.2)
Tim Dettmers's avatar
Tim Dettmers committed
119
120
121
122
123
124
125
126
127
128
129

            if any(req_grad):
                out_bnb.data.copy_(out_torch)
                torch.cuda.synchronize()
                loss_bnb = torch.nn.functional.mse_loss(out_bnb, target).mean()
                loss_bnb.backward()
                gradA1 = A.grad
                gradB1 = B.grad
                A.grad = None
                B.grad = None

Ruff's avatar
Ruff committed
130
                loss_torch = torch.nn.functional.mse_loss(out_torch, target).mean()
Tim Dettmers's avatar
Tim Dettmers committed
131
132
133
134
135
136
137
                loss_torch.backward()
                gradA2 = A.grad
                gradB2 = B.grad
                A.grad = None
                B.grad = None

            if req_grad[0]:
Ruff's avatar
Ruff committed
138
                torch.testing.assert_close(gradA1, gradA2, atol=0.015, rtol=0.1)
Tim Dettmers's avatar
Tim Dettmers committed
139
140
141
            if req_grad[1]:
                n = gradB1.numel()
                idx = torch.isclose(gradB1, gradB2, atol=0.06, rtol=0.3)
142
                assert (idx == 0).sum().item() < n * 0.1
Tim Dettmers's avatar
Tim Dettmers committed
143
                idx = torch.isclose(gradB1, gradB2, atol=0.10, rtol=0.3)
144
                assert (idx == 0).sum().item() < n * 0.02
Tim Dettmers's avatar
Tim Dettmers committed
145
146
147

        if funcs[0] in [torch.matmul]:
            dim1 = dim1 - (dim1 % 16)
148
            A = torch.randn(
149
150
151
                size=(dim1, dim2, dim3),
                device="cuda",
                requires_grad=req_grad[0],
152
            )
Tim Dettmers's avatar
Tim Dettmers committed
153
            dimB = (dim4, dim3) if transpose[1] else (dim3, dim4)
154
155
            B = torch.randn(size=dimB, device="cuda", requires_grad=req_grad[1])
            target = torch.randn(
156
157
158
                size=(dim1, dim2, dim4),
                device="cuda",
                requires_grad=req_grad[1],
159
            )
Tim Dettmers's avatar
Tim Dettmers committed
160
161
162
163
164
165
166
167
168
169
170
            torch.nn.init.xavier_uniform_(B)

            if transpose[1]:
                out_torch = funcs[0](A, B.t())
                out_bnb = funcs[1](A, B.t())
            else:
                out_torch = funcs[0](A, B)
                out_bnb = funcs[1](A, B)

            n = out_bnb.numel()
            idx = torch.isclose(out_bnb, out_torch, atol=0.01, rtol=0.1)
171
            assert (idx == 0).sum().item() < n * 0.0175
Tim Dettmers's avatar
Tim Dettmers committed
172
            idx = torch.isclose(out_bnb, out_torch, atol=0.035, rtol=0.2)
173
            assert (idx == 0).sum().item() < n * 0.001
Tim Dettmers's avatar
Tim Dettmers committed
174
175
176
177
178
179
180
181
182
183
184

            if any(req_grad):
                out_bnb.data.copy_(out_torch)
                torch.cuda.synchronize()
                loss_bnb = torch.nn.functional.mse_loss(out_bnb, target).mean()
                loss_bnb.backward()
                gradA1 = A.grad
                gradB1 = B.grad
                A.grad = None
                B.grad = None

Ruff's avatar
Ruff committed
185
                loss_torch = torch.nn.functional.mse_loss(out_torch, target).mean()
Tim Dettmers's avatar
Tim Dettmers committed
186
187
188
189
190
191
192
                loss_torch.backward()
                gradA2 = A.grad
                gradB2 = B.grad
                A.grad = None
                B.grad = None

            if req_grad[0]:
Ruff's avatar
Ruff committed
193
                torch.testing.assert_close(gradA1, gradA2, atol=0.015, rtol=0.1)
Tim Dettmers's avatar
Tim Dettmers committed
194
195
196
            if req_grad[1]:
                n = gradB1.numel()
                idx = torch.isclose(gradB1, gradB2, atol=0.06, rtol=0.3)
197
                assert (idx == 0).sum().item() < n * 0.1
Tim Dettmers's avatar
Tim Dettmers committed
198
                idx = torch.isclose(gradB1, gradB2, atol=0.10, rtol=0.3)
199
                assert (idx == 0).sum().item() < n * 0.02
Tim Dettmers's avatar
Tim Dettmers committed
200
201


202
203
204
205
@pytest.mark.parametrize("dim1", [40], ids=id_formatter("dim1"))
@pytest.mark.parametrize("dim2", [64, 0], ids=id_formatter("dim2"))
@pytest.mark.parametrize("dim3", [32], ids=id_formatter("dim3"))
@pytest.mark.parametrize("dim4", [48], ids=id_formatter("dim4"))
Aarni Koskela's avatar
Aarni Koskela committed
206
@pytest.mark.parametrize("decomp", [0.0, 6.0], ids=id_formatter("decomp"))
Ruff's avatar
Ruff committed
207
208
209
210
211
@pytest.mark.parametrize(
    "funcs",
    [(torch.matmul, bnb.matmul), (torch.matmul, bnb.research.switchback_bnb)],
    ids=["func=matmul", "func=switchback_bnb"],
)
Aarni Koskela's avatar
Aarni Koskela committed
212
213
214
215
216
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float32], ids=describe_dtype)
@pytest.mark.parametrize("req_grad", BOOLEAN_TRIPLES, ids=id_formatter("req_grad"))
@pytest.mark.parametrize("transpose", TRANSPOSE_VALS, ids=id_formatter("transpose"))
@pytest.mark.parametrize("has_fp16_weights", TRUE_FALSE, ids=id_formatter("has_fp16_weights"))
@pytest.mark.parametrize("has_bias", TRUE_FALSE, ids=id_formatter("has_bias"))
Ruff's avatar
Ruff committed
217
def test_matmullt(dim1, dim2, dim3, dim4, funcs, dtype, req_grad, transpose, decomp, has_fp16_weights, has_bias):
Tim Dettmers's avatar
Tim Dettmers committed
218
219
    dimA = (dim2, dim3) if not transpose[0] else (dim3, dim2)
    dimB = (dim3, dim4) if not transpose[1] else (dim4, dim3)
220
    outlier_dim = torch.randint(0, dimA[1], size=(dimA[1] // 8,), device="cuda")
Tim Dettmers's avatar
Tim Dettmers committed
221
222
223
    if has_bias == False:
        req_grad = list(req_grad)
        req_grad[2] = False
Tim Dettmers's avatar
Tim Dettmers committed
224

Aarni Koskela's avatar
Aarni Koskela committed
225
    for i in range(3):
Tim Dettmers's avatar
Tim Dettmers committed
226
227
        # normal multiply
        if funcs[0] in [torch.mm, torch.matmul]:
Ruff's avatar
Ruff committed
228
            A = torch.randn(size=dimA, device="cuda", requires_grad=req_grad[0], dtype=dtype)
Tim Dettmers's avatar
Tim Dettmers committed
229
230
231
            if decomp == 6.0:
                with torch.no_grad():
                    A[:, outlier_dim] = 6.0
Ruff's avatar
Ruff committed
232
            B = torch.randn(size=dimB, device="cuda", requires_grad=req_grad[1], dtype=dtype)
233
            target = torch.randn(
234
235
236
237
                size=(dim2, dim4),
                device="cuda",
                requires_grad=req_grad[1],
                dtype=dtype,
238
            )
Tim Dettmers's avatar
Tim Dettmers committed
239
240
            bias = None
            bias2 = None
241
            if has_bias:
Ruff's avatar
Ruff committed
242
                bias = torch.randn(dim4, device="cuda", dtype=dtype, requires_grad=req_grad[2])
Tim Dettmers's avatar
Tim Dettmers committed
243
                bias2 = bias.clone()
Tim Dettmers's avatar
Tim Dettmers committed
244
245
246
247
248
249
250
            torch.nn.init.xavier_uniform_(B)
            B2 = B.clone()

            state = bnb.MatmulLtState()
            state.threshold = decomp
            state.has_fp16_weights = has_fp16_weights
            if not has_fp16_weights:
251
252
                if not transpose[0] and not transpose[1]:
                    B2 = B2.t().contiguous()
253
254

                state.CB, state.SCB, _ = bnb.functional.int8_vectorwise_quant(B2.to(torch.float16))
Tim Dettmers's avatar
Tim Dettmers committed
255
256
257
258
                B2 = state.CB

            if not transpose[0] and transpose[1]:
                out_torch = funcs[0](A, B.t())
Tim Dettmers's avatar
Tim Dettmers committed
259
                out_bnb = funcs[1](A, B2, state=state, bias=bias2)
Tim Dettmers's avatar
Tim Dettmers committed
260
261
            elif not transpose[0] and not transpose[1]:
                out_torch = funcs[0](A, B)
Tim Dettmers's avatar
Tim Dettmers committed
262
263
264
265
                out_bnb = funcs[1](A, B2.t(), state=state, bias=bias2)

            if has_bias:
                out_torch += bias
Tim Dettmers's avatar
Tim Dettmers committed
266

justheuristic's avatar
justheuristic committed
267
            assert out_bnb.dtype == A.dtype, f"bnb matmullt received {A.dtype} but returned {out_bnb.dtype}"
justheuristic's avatar
justheuristic committed
268

Tim Dettmers's avatar
Tim Dettmers committed
269
            n = out_bnb.numel()
270
271
            err = torch.abs(out_bnb - out_torch).mean().item()
            # print(f'abs error {err:.4f}')
justheuristic's avatar
justheuristic committed
272

Tim Dettmers's avatar
Tim Dettmers committed
273
            idx = torch.isclose(out_bnb, out_torch, atol=0.01, rtol=0.1)
justheuristic's avatar
justheuristic committed
274
            assert (idx == 0).sum().item() <= n * (0.0175 if dtype == torch.float16 else 0.021)
Tim Dettmers's avatar
Tim Dettmers committed
275
            idx = torch.isclose(out_bnb, out_torch, atol=0.035, rtol=0.2)
Tim Dettmers's avatar
Tim Dettmers committed
276
            assert (idx == 0).sum().item() <= n * 0.001
Tim Dettmers's avatar
Tim Dettmers committed
277
278
279
280
281

            if has_fp16_weights:
                if any(req_grad):
                    out_bnb.data.copy_(out_torch)
                    torch.cuda.synchronize()
Ruff's avatar
Ruff committed
282
                    loss_bnb = torch.nn.functional.mse_loss(out_bnb, target).mean()
Tim Dettmers's avatar
Tim Dettmers committed
283
284
285
286
287
                    loss_bnb.backward()
                    gradA1 = A.grad
                    gradB1 = B.grad
                    A.grad = None
                    B.grad = None
Tim Dettmers's avatar
Tim Dettmers committed
288
289
290
                    if has_bias:
                        gradBias1 = bias.grad
                        bias.grad = None
Tim Dettmers's avatar
Tim Dettmers committed
291

Ruff's avatar
Ruff committed
292
                    loss_torch = torch.nn.functional.mse_loss(out_torch, target).mean()
Tim Dettmers's avatar
Tim Dettmers committed
293
294
295
296
297
                    loss_torch.backward()
                    gradA2 = A.grad
                    gradB2 = B.grad
                    A.grad = None
                    B.grad = None
Tim Dettmers's avatar
Tim Dettmers committed
298
299
300
                    if has_bias:
                        gradBias2 = bias.grad
                        bias.grad = None
Tim Dettmers's avatar
Tim Dettmers committed
301
302

                if req_grad[0]:
Ruff's avatar
Ruff committed
303
                    torch.testing.assert_close(gradA1, gradA2, atol=0.015, rtol=0.1)
Tim Dettmers's avatar
Tim Dettmers committed
304
305
                if req_grad[1]:
                    n = gradB1.numel()
306
307
308
309
310
311
                    if dim2 > 0:
                        assert torch.abs(gradB1).sum() > 0.0
                        assert torch.abs(gradB2).sum() > 0.0
                    else:
                        assert torch.abs(gradB1).sum() == 0.0
                        assert torch.abs(gradB2).sum() == 0.0
312

Tim Dettmers's avatar
Tim Dettmers committed
313
                    idx = torch.isclose(gradB1, gradB2, atol=0.06, rtol=0.3)
314
                    assert (idx == 0).sum().item() <= n * 0.10
Tim Dettmers's avatar
Tim Dettmers committed
315
316

                    idx = torch.isclose(gradB1, gradB2, atol=0.10, rtol=0.3)
Tim Dettmers's avatar
Tim Dettmers committed
317
                    assert (idx == 0).sum().item() <= n * 0.02
318

Ruff's avatar
Ruff committed
319
                    torch.testing.assert_close(gradB1, gradB2, atol=0.18, rtol=0.3)
Tim Dettmers's avatar
Tim Dettmers committed
320
321

                if req_grad[2]:
322
                    torch.testing.assert_close(gradBias1, gradBias2)
Tim Dettmers's avatar
Tim Dettmers committed
323
324


Aarni Koskela's avatar
Aarni Koskela committed
325
326
327
328
329
330
331
332
333
334
@pytest.mark.parametrize("dim1", get_test_dims(16, 64, n=1), ids=id_formatter("dim1"))
@pytest.mark.parametrize("dim2", [*get_test_dims(32, 96, n=1), 0], ids=id_formatter("dim2"))
@pytest.mark.parametrize("dim3", get_test_dims(32, 96, n=1), ids=id_formatter("dim3"))
@pytest.mark.parametrize("dim4", get_test_dims(32, 96, n=1), ids=id_formatter("dim4"))
@pytest.mark.parametrize("funcs", [(torch.matmul, bnb.matmul_4bit)], ids=["func=matmul"])
@pytest.mark.parametrize("req_grad", BOOLEAN_TRIPLES, ids=id_formatter("req_grad"))
@pytest.mark.parametrize("transpose", TRANSPOSE_VALS, ids=id_formatter("transpose"))
@pytest.mark.parametrize("has_bias", TRUE_FALSE, ids=id_formatter("has_bias"))
@pytest.mark.parametrize("dtype", [torch.float16, torch.float32], ids=describe_dtype)
@pytest.mark.parametrize("compress_statistics", TRUE_FALSE, ids=id_formatter("compress_statistics"))
Ruff's avatar
Ruff committed
335
336
337
338
339
340
341
342
343
344
345
346
347
348
@pytest.mark.parametrize("quant_type", ["fp4", "nf4"], ids=id_formatter("quant_type"))
def test_matmul_4bit(
    dim1,
    dim2,
    dim3,
    dim4,
    funcs,
    dtype,
    req_grad,
    transpose,
    has_bias,
    compress_statistics,
    quant_type,
):
Tim Dettmers's avatar
Tim Dettmers committed
349
350
351
352
353
354
    dimA = (dim2, dim3) if not transpose[0] else (dim3, dim2)
    dimB = (dim3, dim4) if not transpose[1] else (dim4, dim3)
    if has_bias == False:
        req_grad = list(req_grad)
        req_grad[2] = False

Aarni Koskela's avatar
Aarni Koskela committed
355
    for i in range(3):
Tim Dettmers's avatar
Tim Dettmers committed
356
357
358
359
360
361
362
363
        # normal multiply
        if funcs[0] in [torch.mm, torch.matmul]:
            A = torch.randn(size=dimA, device="cuda", requires_grad=req_grad[0], dtype=dtype)
            B = torch.randn(size=dimB, device="cuda", requires_grad=req_grad[1], dtype=dtype)
            target = torch.randn(size=(dim2, dim4), device="cuda", requires_grad=req_grad[1], dtype=dtype)
            bias = None
            bias2 = None
            if has_bias:
Ruff's avatar
Ruff committed
364
                bias = torch.randn(dim4, device="cuda", dtype=dtype, requires_grad=req_grad[2])
Tim Dettmers's avatar
Tim Dettmers committed
365
366
367
                bias2 = bias.clone()
            torch.nn.init.xavier_uniform_(B)

Ruff's avatar
Ruff committed
368
369
370
371
372
            B2, quant_state = bnb.functional.quantize_4bit(
                B,
                compress_statistics=compress_statistics,
                quant_type=quant_type,
            )
Tim Dettmers's avatar
Tim Dettmers committed
373
374
375

            if not transpose[0] and transpose[1]:
                out_torch = funcs[0](A, B.t())
Tim Dettmers's avatar
Tim Dettmers committed
376
                out_bnb = funcs[1](A, B2.t(), quant_state, bias=bias2)
Tim Dettmers's avatar
Tim Dettmers committed
377
378
            elif not transpose[0] and not transpose[1]:
                out_torch = funcs[0](A, B)
Tim Dettmers's avatar
Tim Dettmers committed
379
                out_bnb = funcs[1](A, B2, quant_state, bias=bias2)
Tim Dettmers's avatar
Tim Dettmers committed
380
381
382
383
384
385
386
387
388

            if has_bias:
                out_torch += bias

            assert out_bnb.dtype == A.dtype, f"bnb matmullt received {A.dtype} but returned {out_bnb.dtype}"

            n = out_bnb.numel()
            err = torch.abs(out_bnb - out_torch).float().mean().item()
            if n > 0:
389
                assert err < 0.115
Tim Dettmers's avatar
Tim Dettmers committed
390

Ruff's avatar
Ruff committed
391
                # assert err < 0.20
Tim Dettmers's avatar
Tim Dettmers committed
392
393
394
395
396
397
398
399
400
401
402
403
404
            if any(req_grad):
                out_bnb.data.copy_(out_torch)
                torch.cuda.synchronize()
                loss_bnb = torch.nn.functional.mse_loss(out_bnb, target).mean()
                loss_bnb.backward()
                gradA1 = A.grad
                gradB1 = B.grad
                A.grad = None
                B.grad = None
                if has_bias:
                    gradBias1 = bias.grad
                    bias.grad = None

Ruff's avatar
Ruff committed
405
                loss_torch = torch.nn.functional.mse_loss(out_torch, target).mean()
Tim Dettmers's avatar
Tim Dettmers committed
406
407
408
409
410
411
412
413
414
415
                loss_torch.backward()
                gradA2 = A.grad
                gradB2 = B.grad
                A.grad = None
                B.grad = None
                if has_bias:
                    gradBias2 = bias.grad
                    bias.grad = None

                if req_grad[0]:
Ruff's avatar
Ruff committed
416
                    torch.testing.assert_close(gradA1, gradA2, atol=0.015, rtol=0.1)
Tim Dettmers's avatar
Tim Dettmers committed
417
418

                if req_grad[2]:
419
420
421
                    torch.testing.assert_close(gradBias1, gradBias2)


Aarni Koskela's avatar
Aarni Koskela committed
422
423
424
425
426
427
428
@pytest.mark.parametrize("dim1", get_test_dims(16, 64, n=1), ids=id_formatter("dim1"))
@pytest.mark.parametrize("dim2", [*get_test_dims(32, 96, n=1), 0], ids=id_formatter("dim2"))
@pytest.mark.parametrize("dim3", get_test_dims(32, 96, n=1), ids=id_formatter("dim3"))
@pytest.mark.parametrize("dim4", get_test_dims(32, 96, n=1), ids=id_formatter("dim4"))
@pytest.mark.parametrize("req_grad", BOOLEAN_TRIPLES, ids=id_formatter("req_grad"))
@pytest.mark.parametrize("transpose", TRANSPOSE_VALS, ids=id_formatter("transpose"))
@pytest.mark.parametrize("dtype", [torch.float16, torch.float32], ids=describe_dtype)
Ruff's avatar
Ruff committed
429
430
431
432
433
434
@pytest.mark.parametrize(
    "funcs",
    [(torch.matmul, bnb.research.matmul_fp8_mixed), (torch.matmul, bnb.research.matmul_fp8_global)],
    ids=["matmul_fp8_mixed", "matmul_fp8_global"],
)
def test_matmul_fp8(dim1, dim2, dim3, dim4, funcs, dtype, req_grad, transpose):
Tim Dettmers's avatar
Tim Dettmers committed
435
436
    dimA = (dim2, dim3) if not transpose[0] else (dim3, dim2)
    dimB = (dim3, dim4) if not transpose[1] else (dim4, dim3)
437
438
    req_grad = list(req_grad)
    req_grad[2] = False
Tim Dettmers's avatar
Tim Dettmers committed
439

Aarni Koskela's avatar
Aarni Koskela committed
440
    for i in range(3):
Tim Dettmers's avatar
Tim Dettmers committed
441
442
443
444
445
        # normal multiply
        if funcs[0] in [torch.mm, torch.matmul]:
            A = torch.randn(size=dimA, device="cuda", requires_grad=req_grad[0], dtype=dtype)
            B = torch.randn(size=dimB, device="cuda", requires_grad=req_grad[1], dtype=dtype)
            target = torch.randn(size=(dim2, dim4), device="cuda", requires_grad=req_grad[1], dtype=dtype)
446

Tim Dettmers's avatar
Tim Dettmers committed
447
448
            torch.nn.init.xavier_uniform_(B)

449
450
            fw_code = bnb.functional.create_fp8_map(True, 4, 3, 8).to(A.device)
            bw_code = bnb.functional.create_fp8_map(True, 5, 2, 8).to(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
451
452
453

            if not transpose[0] and transpose[1]:
                out_torch = funcs[0](A, B.t())
454
                out_bnb = funcs[1](A, B.t(), fw_code, bw_code)
Tim Dettmers's avatar
Tim Dettmers committed
455
456
            elif not transpose[0] and not transpose[1]:
                out_torch = funcs[0](A, B)
457
                out_bnb = funcs[1](A, B, fw_code, bw_code)
Tim Dettmers's avatar
Tim Dettmers committed
458
459
460
461
462
463

            assert out_bnb.dtype == A.dtype, f"bnb matmullt received {A.dtype} but returned {out_bnb.dtype}"

            n = out_bnb.numel()
            err = torch.abs(out_bnb - out_torch).float().mean().item()
            if n > 0:
464
                assert err < 0.115
Ruff's avatar
Ruff committed
465
                # assert err < 0.20
Tim Dettmers's avatar
Tim Dettmers committed
466
467
468
469
470
471
472
473
474
475
            if any(req_grad):
                out_bnb.data.copy_(out_torch)
                torch.cuda.synchronize()
                loss_bnb = torch.nn.functional.mse_loss(out_bnb, target).mean()
                loss_bnb.backward()
                gradA1 = A.grad
                gradB1 = B.grad
                A.grad = None
                B.grad = None

Ruff's avatar
Ruff committed
476
                loss_torch = torch.nn.functional.mse_loss(out_torch, target).mean()
Tim Dettmers's avatar
Tim Dettmers committed
477
478
479
480
481
482
483
                loss_torch.backward()
                gradA2 = A.grad
                gradB2 = B.grad
                A.grad = None
                B.grad = None

                if req_grad[0]:
Ruff's avatar
Ruff committed
484
                    torch.testing.assert_close(gradA1, gradA2, atol=0.015, rtol=0.1)
Tim Dettmers's avatar
Tim Dettmers committed
485

486
487
488
489
490
491
492
493
494
495
496
497
498
                if req_grad[1]:
                    n = gradB1.numel()
                    if dim2 > 0:
                        assert torch.abs(gradB1).sum() > 0.0
                        assert torch.abs(gradB2).sum() > 0.0
                    else:
                        assert torch.abs(gradB1).sum() == 0.0
                        assert torch.abs(gradB2).sum() == 0.0
                    idx = torch.isclose(gradB1, gradB2, atol=0.06, rtol=0.3)

                    assert (idx == 0).sum().item() <= n * 0.1
                    idx = torch.isclose(gradB1, gradB2, atol=0.10, rtol=0.3)
                    assert (idx == 0).sum().item() <= n * 0.02
Ruff's avatar
Ruff committed
499
                    grad_err = (gradB1 - gradB2).abs().mean()
500
                    assert grad_err.item() < 0.003
Ruff's avatar
Ruff committed
501
                    torch.testing.assert_close(gradB1, gradB2, atol=0.18, rtol=0.3)