test_fusible_ops.py 135 KB
Newer Older
1
# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
#
# See LICENSE for license information.

from __future__ import annotations

7
from collections.abc import Iterable
8
import functools
9
import io
10
import math
11
import random
12
from typing import Optional
13
14
15

import pytest
import torch
yuguo's avatar
yuguo committed
16
from torch.utils.cpp_extension import IS_HIP_EXTENSION
17
18

import transformer_engine
Tim Moon's avatar
Tim Moon committed
19
import transformer_engine.common.recipe
20
21
import transformer_engine.pytorch as te
import transformer_engine.pytorch.ops as te_ops
22
from transformer_engine.pytorch.ops.fused import (
Jan Bielak's avatar
Jan Bielak committed
23
    BackwardActivationBias,
24
    BackwardAddRMSNorm,
25
    BackwardLinearAdd,
Jan Bielak's avatar
Jan Bielak committed
26
    BackwardLinearScale,
27
    ForwardLinearBiasActivation,
28
    ForwardLinearBiasAdd,
Jan Bielak's avatar
Jan Bielak committed
29
    ForwardLinearScaleAdd,
30
)
31
32
from transformer_engine.pytorch import (
    QuantizedTensor,
33
34
    Float8CurrentScalingQuantizer,
    Float8Quantizer,
35
36
37
    MXFP8Quantizer,
    NVFP4Quantizer,
    is_bf16_available,
38
)
39
40
import transformer_engine_torch as tex

41
# Import utility functions
42
43
44
45
46
47
48
49
from utils import (
    assert_close,
    assert_close_grads,
    dtype_tols,
    make_recipe,
    quantization_tols,
    reset_rng_states,
)
50

yuguo's avatar
yuguo committed
51
52
53
54
55
56
57
58
if IS_HIP_EXTENSION:
    import os
    from functools import cache
    @cache
    def use_hipblaslt() -> bool:
        return (os.getenv("NVTE_USE_HIPBLASLT") is not None
                or os.getenv("NVTE_USE_ROCBLAS") is None )

59
# Check for supported quantization schemes
60
61
62
fp8_available, reason_for_no_fp8 = te.is_fp8_available(return_reason=True)
mxfp8_available, reason_for_no_mxfp8 = te.is_mxfp8_available(return_reason=True)
nvfp4_available, reason_for_no_nvfp4 = te.is_nvfp4_available(return_reason=True)
63
64
65

# Supported data types
_dtypes: list[torch.dtype] = [torch.float32, torch.float16]
66
if is_bf16_available():  # bf16 requires sm_80 or higher
67
68
69
70
71
    _dtypes.append(torch.bfloat16)

# Supported devices
_devices: list[torch.device] = [torch.device("cpu"), torch.device("cuda")]

72
73
74
75
76
77
# Supported quantization recipes
_quantization_list: list[Optional[str]] = [None]
if fp8_available:
    _quantization_list.extend(("fp8_delayed_scaling", "fp8_current_scaling"))
if mxfp8_available:
    _quantization_list.append("mxfp8")
78
79
if nvfp4_available:
    _quantization_list.append("nvfp4")
80

81

82
83
84
85
86
def maybe_skip_quantization(
    quantization: Optional[str],
    *,
    dims: Optional[Iterable[int] | int] = None,
    device: Optional[torch.device | str] = None,
87
    dtype: Optional[torch.dtype] = None,
88
) -> None:
89
    """Skip test case if a quantization scheme is not supported"""
90
91
92
93
94

    # Don't skip if there is no quantization
    if quantization is None:
        return

95
96
97
    # Check if quantization scheme is supported on device
    if device is not None and torch.device(device).type != "cuda":
        pytest.skip("Quantization is only supported on CUDA devices")
98
    if quantization in ("fp8", "fp8_delayed_scaling", "fp8_current_scaling") and not fp8_available:
99
100
101
        pytest.skip(reason_for_no_fp8)
    if quantization == "mxfp8" and not mxfp8_available:
        pytest.skip(reason_for_no_mxfp8)
102
103
    if quantization == "nvfp4" and not nvfp4_available:
        pytest.skip(reason_for_no_nvfp4)
104

105
    # Check dims
106
107
108
    if dims is not None:
        if not isinstance(dims, Iterable):
            dims = (dims,)
109
        if quantization in ("fp8", "fp8_delayed_scaling", "fp8_current_scaling"):
110
111
112
113
114
            if math.prod(dims[:-1]) % 16 != 0 or dims[-1] % 16 != 0:
                pytest.skip("FP8 GEMMs require dims that are divisible by 16")
        elif quantization == "mxfp8":
            if math.prod(dims[:-1]) % 32 != 0 or dims[-1] % 32 != 0:
                pytest.skip("MXFP8 GEMMs require dims that are divisible by 32")
115
116
117
        elif quantization == "nvfp4":
            if math.prod(dims[:-1]) % 16 != 0 or dims[-1] % 16 != 0:
                pytest.skip("NVFP4 GEMMs require dims that are divisible by 16")
118

119
120
121
122
    # Check dtype
    if dtype is not None:
        if quantization == "nvfp4" and dtype != torch.bfloat16:
            pytest.skip("NVFP4 quantization is only supported with BF16 data")
123
124


125
126
127
@torch.no_grad()
def make_reference_and_test_tensors(
    shape: int | Iterable[int],
128
129
130
    *,
    min: float = 0.0,
    max: float = 1.0,
131
    quantization: Optional[str] = None,
132
133
134
135
    ref_dtype: torch.dtype = torch.float64,
    ref_device: torch.device = "cpu",
    test_dtype: torch.dtype = torch.float32,
    test_device: torch.device = "cuda",
136
    test_is_quantized: bool = False,
137
138
139
140
141
142
143
144
    requires_grad: bool = True,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Construct tensors with the same values

    The reference tensor is intended for use in plain PyTorch
    operations in high precision. The test tensor is intended for use
    in Transformer Engine operations.

145
146
147
    If a quantization scheme is provided, the tensor values are
    quantized so that they are representable.

148
    """
149
150

    # Random reference tensor
151
152
    ref = torch.empty(shape, dtype=ref_dtype, device=ref_device)
    ref.uniform_(min, max)
153
154

    # Construct test tensor from reference tensor
155
    test = ref.to(device=test_device, dtype=test_dtype)
156
157
158
159
160
161
    if quantization is None:
        if test_is_quantized:
            raise ValueError("Quantization scheme not provided")
        if test.data_ptr() == ref.data_ptr():
            test = test.clone()
    elif quantization in ("fp8", "fp8_delayed_scaling"):
162
163
164
165
166
167
        quantizer = Float8Quantizer(
            scale=torch.ones(1, dtype=torch.float32, device=test_device).squeeze(),
            amax=torch.zeros(1, dtype=torch.float32, device=test_device),
            fp8_dtype=tex.DType.kFloat8E4M3,
        )
        test = quantizer(test)
168
169
170
171
172
173
174
175
    elif quantization == "fp8_current_scaling":
        quantizer = Float8CurrentScalingQuantizer(
            fp8_dtype=tex.DType.kFloat8E4M3,
            device=test_device,
        )
        test = quantizer(test)
    elif quantization == "mxfp8":
        test = MXFP8Quantizer(fp8_dtype=tex.DType.kFloat8E4M3)(test)
176
177
178
179
180
181
182
183
    elif quantization == "nvfp4":
        test = NVFP4Quantizer(
            with_rht=False,
            with_post_rht_amax=False,
            with_2d_quantization=False,
            stochastic_rounding=False,
            with_random_sign_mask=False,
        )(test)
184
185
186
187
188
189
    else:
        raise ValueError(f"Unsupported quantization scheme ({quantization})")
    if isinstance(test, QuantizedTensor) and not test_is_quantized:
        test = test.dequantize()

    # Make sure reference and test tensors match each other
190
    ref.copy_(test)
191

192
193
194
195
196
    ref.requires_grad_(requires_grad)
    test.requires_grad_(requires_grad)
    return ref, test


197
class TestSequentialContainer:
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
    """Tests for sequential container"""

    def test_modules(self) -> None:
        """Check that list of modules can be manipulated as expected"""

        # Construct sequential container
        modules = [
            te_ops.Identity(),
            te_ops.Identity(),
            torch.nn.Identity(),
            te_ops.Identity(),
        ]
        model = te_ops.Sequential(*modules)

        # Length
        assert len(model) == len(modules)

        # Iterator
        for module1, module2 in zip(model, modules):
            assert module1 is module2

        # Index by int
        for i, module in enumerate(modules):
            assert model[i] is module
            assert model[i - len(modules)] is module

        # Index by slice
        model_subset = model[1:-1]
        modules_subset = modules[1:-1]
        assert isinstance(model_subset, te_ops.Sequential)
        for module1, module2 in zip(model_subset, modules_subset):
            assert module1 is module2

        # Set element
        new_module = torch.nn.Identity()
        idx = 1
        modules[idx] = new_module
        model[idx] = new_module
        for module1, module2 in zip(model, modules):
            assert module1 is module2

        # Delete element
        idx = 1
        del modules[idx]
        del model[idx]
        for module1, module2 in zip(model, modules):
            assert module1 is module2

        # Append
        new_module = torch.nn.Identity()
        modules.append(new_module)
        model.append(new_module)
        for module1, module2 in zip(model, modules):
            assert module1 is module2

        # Extend
        new_modules = [te_ops.Identity(), te_ops.Identity()]
        modules.extend(new_modules)
        model.extend(new_modules)
        for module1, module2 in zip(model, modules):
            assert module1 is module2

        # Insert
        new_module = te_ops.Identity()
        idx = 2
        modules.insert(idx, new_module)
        model.insert(idx, new_module)
        for module1, module2 in zip(model, modules):
            assert module1 is module2

        # Pop
        idx = 2
        assert model.pop(idx) is modules.pop(idx)
        for module1, module2 in zip(model, modules):
            assert module1 is module2

        # Out-of-place add
        new_modules = [torch.nn.Identity(), te_ops.Identity()]
        added_modules = modules + new_modules
        added_model = model + te_ops.Sequential(*new_modules)
        for module1, module2 in zip(model, modules):
            assert module1 is module2
        for module1, module2 in zip(added_model, added_modules):
            assert module1 is module2

        # In-place add
        new_modules = [te_ops.Identity(), torch.nn.Identity()]
        modules += new_modules
        model += te_ops.Sequential(*new_modules)
        for module1, module2 in zip(model, modules):
            assert module1 is module2

    def test_module_groups(self) -> None:
        """Check that modules are grouped together correctly"""
        model = te_ops.Sequential(
            te_ops.Identity(),
            te_ops.Identity(),
            torch.nn.Identity(),
            torch.nn.Identity(),
            te_ops.Identity(),
            torch.nn.Identity(),
            te_ops.Identity(),
            te_ops.Identity(),
            te_ops.Identity(),
        )
        model(torch.zeros(1))
        assert len(model._module_groups) == 6

Jan Bielak's avatar
Jan Bielak committed
306
307
308
309
310
311
312
313
    def test_extra_tensors(self, size: int = 16) -> None:
        """Check that extra inputs are distributed properly between module groups
        and that extra outputs are properly collected"""

        # Construct sequential container
        bias = te_ops.Bias(size=size, device="cpu")
        with torch.no_grad():
            bias.bias.copy_(torch.rand((size,)))
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
        model = te_ops.Sequential(  #                 | Inputs  | Outputs
            torch.nn.Identity(),  #                   | x1      | x1
            te_ops.MakeExtraOutput(in_place=True),  # | x1      | x1 [x1]
            bias,  #                                  | x1      | h1 (= x1 + b)
            te_ops.MakeExtraOutput(in_place=True),  # | h1      | h1 [h1]
            te_ops.AddExtraInput(in_place=True),  #   | h1 [x2] | x2 (= x2 + h1)
            te_ops.MakeExtraOutput(in_place=True),  # | x2      | x2 [x2]
            torch.nn.Identity(),  #                   | x2      | x2
            bias,  #                                  | x2      | h2 (= x2 + b)
            te_ops.AddExtraInput(in_place=True),  #   | h2 [x3] | x3 (= x3 + h2)
            te_ops.MakeExtraOutput(in_place=True),  # | x3      | x3 [x3]
            te_ops.AddExtraInput(in_place=True),  #   | x3 [x4] | x4 (= x4 + x3)
            torch.nn.Identity(),  #                   | x4      | x4
            te_ops.Identity(),  #                     | x4      | x4
            te_ops.MakeExtraOutput(in_place=True),  # | x4      | x4 [x4]
            te_ops.Identity(),  #                     | x4      | x4
Jan Bielak's avatar
Jan Bielak committed
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
        )

        # Create input tensors
        x1 = torch.rand((size,))
        x2 = torch.rand((size,))
        x3 = torch.rand((size,))
        x4 = torch.rand((size,))

        # Save original input tensor values
        x1_orig = x1.clone()
        x2_orig = x2.clone()
        x3_orig = x3.clone()
        x4_orig = x4.clone()

        # Run forward
        ys = model(x1, x2, x3, x4)

        # Check whether outputs match (x4, x1, h1, x2, x3, x4)
        assert len(ys) == 6
        assert ys[0].data_ptr() == x4.data_ptr()
        assert ys[1].data_ptr() == x1.data_ptr()
        assert ys[2].data_ptr() not in [x.data_ptr() for x in (x1, x2, x3, x4)]
        assert ys[3].data_ptr() == x2.data_ptr()
        assert ys[4].data_ptr() == x3.data_ptr()
        assert ys[5].data_ptr() == x4.data_ptr()

        # Check whether tensors have correct values
        b = bias.bias
        h1 = ys[2]
        torch.testing.assert_close(x1, x1_orig)
        torch.testing.assert_close(h1, x1_orig + b)
        torch.testing.assert_close(x2, x2_orig + h1)
        torch.testing.assert_close(x3, x3_orig + x2 + b)
        torch.testing.assert_close(x4, x4_orig + x3)

365
366
367
368
369
370

class TestFuser:
    """Tests for operation fusion infrastructure"""

    @staticmethod
    def setup_class(cls) -> None:
371
        reset_rng_states()
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392

    @pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8)
    def test_fp8_scale_update(
        self,
        size: int = 16,
        dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
    ):
        """Test FP8 scaling factors with delayed scaling recipe"""

        # FP8 recipe
        margin = 2
        fp8_format = transformer_engine.common.recipe.Format.HYBRID
        recipe = transformer_engine.common.recipe.DelayedScaling(
            margin=margin,
            fp8_format=fp8_format,
            amax_history_len=8,
            amax_compute_algo="max",
        )

        # Construct model
393
        with te.quantized_model_init(recipe=recipe):
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
            model = te_ops.basic.BasicLinear(
                size,
                size,
                device=device,
                dtype=dtype,
            )

        # Training steps
        w_vals = [2, 5, 3, 11]
        x_vals = [7, 3, 5]
        dy_vals = [1, 2, 1]
        with torch.no_grad():
            model.weight.fill_(w_vals[0])
        for step in range(3):

            # Data tensors
            x = torch.full(
                (size, size),
                x_vals[step],
                dtype=dtype,
                device=device,
                requires_grad=True,
            )
            dy = torch.full(
                (size, size),
                dy_vals[step],
                dtype=dtype,
                device=device,
            )

            # Training step
425
            with te.autocast(recipe=recipe):
426
427
428
429
430
431
432
433
434
435
436
437
                y = model(x)
            y.backward(dy)
            with torch.no_grad():
                model.weight.fill_(w_vals[step + 1])

            # Check that output tensors match expected
            tols = dict(rtol=0, atol=0)
            y_val_ref = w_vals[step] * x_vals[step] * size
            dx_val_ref = w_vals[step] * dy_vals[step] * size
            torch.testing.assert_close(
                y,
                torch.full_like(y, y_val_ref),
438
                **quantization_tols("fp8_delayed_scaling"),
439
440
441
442
            )
            torch.testing.assert_close(
                x.grad,
                torch.full_like(x.grad, dx_val_ref),
443
                **quantization_tols("fp8_delayed_scaling"),
444
445
446
            )

            # Check that scaling factors match expected
447
            w_amax_ref = max(w_vals[: step + 1])
448
449
450
451
452
            x_amax_ref = max(x_vals[: step + 1])
            dy_amax_ref = max(dy_vals[: step + 1])
            w_scale_ref = (fp8_format.value.max_fwd / w_amax_ref) / (2**margin)
            x_scale_ref = (fp8_format.value.max_fwd / x_amax_ref) / (2**margin)
            dy_scale_ref = (fp8_format.value.max_bwd / dy_amax_ref) / (2**margin)
453
454
455
            w_scale = model.get_quantizer("forward", 1).scale
            x_scale = model.get_quantizer("forward", 0).scale
            dy_scale = model.get_quantizer("backward", 0).scale
456
457
458
459
            torch.testing.assert_close(w_scale, torch.full_like(w_scale, w_scale_ref))
            torch.testing.assert_close(x_scale, torch.full_like(x_scale, x_scale_ref))
            torch.testing.assert_close(dy_scale, torch.full_like(dy_scale, dy_scale_ref))

460
461
    @pytest.mark.parametrize("init_dtype", _dtypes)
    @pytest.mark.parametrize("final_dtype", _dtypes)
462
    @pytest.mark.parametrize("quantization", _quantization_list)
463
464
465
    def test_dtype_cast(
        self,
        *,
466
        size: int = 32,
467
468
469
        init_dtype: torch.dtype,
        final_dtype: torch.dtype,
        device: torch.device = "cuda",
470
        quantization: Optional[str],
471
472
473
474
    ) -> None:
        """Check dtype cast functions"""

        # Skip invalid configurations
475
        in_shape = (size, size)
476
        with_quantization = quantization is not None
477
478
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=init_dtype)
        maybe_skip_quantization(quantization, dtype=final_dtype)
479
480
481
482
483
484
485
486
487

        # Random data
        dtype = torch.float32
        if torch.float16 in (init_dtype, final_dtype):
            dtype = torch.float16
        if torch.bfloat16 in (init_dtype, final_dtype):
            dtype = torch.bfloat16
        w_ref, w_test = make_reference_and_test_tensors(
            (size, size),
488
            quantization=quantization,
489
490
491
492
493
            test_dtype=dtype,
            test_device=device,
        )

        # Construct operation
494
        with te.quantized_model_init(enabled=with_quantization, recipe=make_recipe(quantization)):
495
496
497
498
499
500
501
502
503
504
505
506
507
508
            op = te_ops.Linear(size, size, bias=False, device=device, dtype=init_dtype)
        with torch.no_grad():
            op.weight.copy_(w_test)
            del w_test

        # Cast operation dtype
        if final_dtype == torch.float32:
            op.float()
        elif final_dtype == torch.float16:
            op.half()
        elif final_dtype == torch.bfloat16:
            op.bfloat16()

        # Check weights
509
        assert isinstance(op.weight, QuantizedTensor) == with_quantization
510
511
        assert op.weight.dtype == final_dtype
        w_test = op.weight.to(dtype=torch.float64, device="cpu")
512
        torch.testing.assert_close(w_test, w_ref, **dtype_tols(dtype))
513
514
515

        # Check forward and backward pass
        x = torch.zeros(
516
            in_shape,
517
518
519
520
521
522
523
524
525
526
527
528
            dtype=init_dtype,
            device=device,
            requires_grad=True,
        )
        y = op(x)
        y.backward(torch.zeros_like(y))
        assert y.dtype == final_dtype
        assert x.grad.dtype == init_dtype
        assert op.weight.grad.dtype == final_dtype

    @pytest.mark.parametrize("model_dtype", _dtypes)
    @pytest.mark.parametrize("autocast_dtype", _dtypes)
529
    @pytest.mark.parametrize("quantization", _quantization_list)
530
531
532
    def test_pyt_autocast(
        self,
        *,
533
        size: int = 32,
534
535
536
        model_dtype: torch.dtype,
        autocast_dtype: torch.dtype,
        device: torch.device = "cuda",
537
538
        quantization: Optional[str],
        quantized_weights: bool = False,
539
540
541
542
543
    ) -> None:
        """Test with PyTorch autocast"""
        device = torch.device(device)

        # Skip invalid configurations
544
        in_shape = (size, size)
545
        quantized_compute = quantization is not None
546
547
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=model_dtype)
        maybe_skip_quantization(quantization, dtype=autocast_dtype)
548
549

        # Construct operation
550
        recipe = make_recipe(quantization)
551
        with te.quantized_model_init(enabled=quantized_weights, recipe=recipe):
552
553
554
555
            op = te_ops.Linear(size, size, bias=False, device=device, dtype=model_dtype)

        # Check forward and backward pass
        x = torch.zeros(
556
            in_shape,
557
558
559
560
            dtype=model_dtype,
            device=device,
            requires_grad=True,
        )
561
        with te.autocast(enabled=quantized_compute, recipe=recipe):
562
563
564
565
566
567
568
569
            with torch.autocast(device_type=device.type, dtype=autocast_dtype):
                y = op(x)
        y.backward(torch.zeros_like(y))
        assert y.dtype == autocast_dtype
        assert x.grad.dtype == model_dtype
        assert op.weight.grad.dtype == model_dtype

        # Check forward and backward pass (swapped context order)
570
        if quantized_compute:
571
572
573
            x.grad = None
            op.weight.grad = None
            with torch.autocast(device_type=device.type, dtype=autocast_dtype):
574
                with te.autocast(enabled=quantized_compute, recipe=recipe):
575
576
577
578
579
580
                    y = op(x)
            y.backward(torch.zeros_like(y))
            assert y.dtype == autocast_dtype
            assert x.grad.dtype == model_dtype
            assert op.weight.grad.dtype == model_dtype

581
582
583
584
585
586

class TestBasicOps:
    """Tests for individual operations"""

    @staticmethod
    def setup_class(cls) -> None:
587
        reset_rng_states()
588
589
590

    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("device", ("cuda", "cpu"))
591
    @pytest.mark.parametrize("quantization", _quantization_list)
592
593
594
    def test_identity(
        self,
        *,
595
        in_shape: Iterable[int] = (32, 32),
596
597
        dtype: torch.dtype,
        device: torch.device,
598
        quantization: Optional[str],
599
600
601
    ) -> None:

        # Skip invalid configurations
602
        with_quantization = quantization is not None
603
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
604
605
606
607

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
608
            quantization=quantization,
609
610
            test_dtype=dtype,
            test_device=device,
611
            test_is_quantized=with_quantization,
612
613
614
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
615
            quantization=quantization,
616
617
            test_dtype=dtype,
            test_device=device,
618
            test_is_quantized=with_quantization,
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = x_ref
        dx_ref = dy_ref

        # Implementation with fusible operation
        op = te_ops.Identity()
        y_test = op(x_test)
        y_test.backward(dy_test)

        # Check results
        tols = dict(rtol=0, atol=0)  # Identity is exact
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, dx_ref, **tols)

        # Make sure we are not trivially passing the test
        with pytest.raises(AssertionError):
            torch.testing.assert_close(y_test, -y_ref, **tols)
        with pytest.raises(AssertionError):
            torch.testing.assert_close(dx_test, -dx_ref, **tols)

    @pytest.mark.parametrize(
        "shapes",
        (
            ((1, 2, 3, 4), (2, 12)),
            ((5, 4, 3, 2), (-1, 6)),
            ((30,), (2, 3, -1)),
            ((6, 7), (3, -1, 7)),
        ),
    )
    @pytest.mark.parametrize("dtype", _dtypes)
654
    @pytest.mark.parametrize("quantization", (None, "fp8_current_scaling"))
655
656
657
658
659
    def test_reshape(
        self,
        *,
        shapes: tuple[Iterable[int], Iterable[int]],
        dtype: torch.dtype,
660
661
        device: torch.device = "cuda",
        memory_format: torch.memory_format = torch.contiguous_format,
662
        quantization: Optional[str],
663
664
665
666
667
668
    ) -> None:
        in_shape, out_shape = shapes

        # Skip invalid configurations
        if memory_format == torch.channels_last and len(in_shape) != 4:
            pytest.skip("torch.channels_last only supports 4D tensors")
669
        maybe_skip_quantization(quantization, device=device, dtype=dtype)
670
        with_quantization = quantization is not None
671
672
673
674

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
675
            quantization=quantization,
676
677
            test_dtype=dtype,
            test_device=device,
678
            test_is_quantized=with_quantization,
679
680
681
682
683
        )
        x_test = x_test.contiguous(memory_format=memory_format)
        x_test = x_test.detach().requires_grad_()
        dy_ref, dy_test = make_reference_and_test_tensors(
            x_ref.reshape(out_shape).size(),
684
            quantization=quantization,
685
686
            test_dtype=dtype,
            test_device=device,
687
            test_is_quantized=with_quantization,
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = x_ref.reshape(out_shape)
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = te_ops.Reshape(out_shape)
        y_test = op(x_test)
        y_test.backward(dy_test)

        # Check results
        tols = dict(rtol=0, atol=0)  # Reshape is exact
        y_test = y_test.to(
            dtype=torch.float64,
            device="cpu",
            memory_format=torch.contiguous_format,
        )
        dx_test = x_test.grad.to(
            dtype=torch.float64,
            device="cpu",
            memory_format=torch.contiguous_format,
        )
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)

    @pytest.mark.parametrize("size", (1, 7, 32))
716
    @pytest.mark.parametrize("in_shape", ((-1,), (1, 3, -1), (4, 3, 8, -1)))
717
718
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("device", _devices)
719
    @pytest.mark.parametrize("quantization", _quantization_list)
720
721
722
723
724
725
726
    def test_bias(
        self,
        *,
        size: int,
        in_shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device,
727
        quantization: Optional[str],
728
729
730
731
732
733
    ) -> None:

        # Make input and bias shapes consistent
        in_shape = list(in_shape)[:-1] + [size]

        # Skip invalid configurations
734
        with_quantization = quantization is not None
735
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
736
737
738
739

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
740
            quantization=quantization,
741
742
            test_dtype=dtype,
            test_device=device,
743
            test_is_quantized=with_quantization,
744
745
746
747
748
749
750
751
        )
        b_ref, b_test = make_reference_and_test_tensors(
            size,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
752
            quantization=quantization,
753
754
            test_dtype=dtype,
            test_device=device,
755
            test_is_quantized=with_quantization,
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = x_ref + b_ref.reshape([1] * (len(in_shape) - 1) + [size])
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = te_ops.Bias(size, device=device, dtype=dtype)
        with torch.no_grad():
            op.bias.copy_(b_test)
            del b_test
        y_test = op(x_test)
        y_test.backward(dy_test)

        # Check results
        tols = dtype_tols(dtype)
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        db_test = op.bias.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(db_test, b_ref.grad, **tols)

780
    @pytest.mark.parametrize("quantization", _quantization_list)
Tim Moon's avatar
Tim Moon committed
781
782
    @pytest.mark.parametrize("cast_forward", (False, True))
    @pytest.mark.parametrize("cast_backward", (False, True))
783
    def test_quantize(
784
785
        self,
        *,
786
        in_shape: Iterable[int] = (32, 32),
Tim Moon's avatar
Tim Moon committed
787
        dtype: torch.dtype = torch.bfloat16,
788
        device: torch.device = "cuda",
789
        quantization: str,
Tim Moon's avatar
Tim Moon committed
790
791
        cast_forward: bool,
        cast_backward: bool,
792
    ) -> None:
793
794
795
        """Quantize"""

        # Skip invalid configurations
796
        with_quantization = quantization is not None
797
        maybe_skip_quantization(quantization, device=device, dtype=dtype)
798
799
        if quantization == "mxfp8":
            maybe_skip_quantization(quantization, dims=in_shape)
Tim Moon's avatar
Tim Moon committed
800
801
802
803

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
804
            quantization=quantization,
Tim Moon's avatar
Tim Moon committed
805
806
            test_dtype=dtype,
            test_device=device,
807
            requires_grad=True,
Tim Moon's avatar
Tim Moon committed
808
809
810
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
811
            quantization=quantization,
Tim Moon's avatar
Tim Moon committed
812
813
814
815
816
817
818
819
820
821
822
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = x_ref
        dx_ref = dy_ref

        # Implementation with fusible operation
        op = te_ops.Quantize(forward=cast_forward, backward=cast_backward)
823
        recipe = make_recipe(quantization)
824
        with te.autocast(enabled=with_quantization, recipe=recipe):
Tim Moon's avatar
Tim Moon committed
825
826
827
828
            y_test = op(x_test)
        y_test.backward(dy_test)

        # Check tensor types
829
830
831
        if with_quantization:
            assert isinstance(y_test, QuantizedTensor) == cast_forward
            assert isinstance(x_test.grad, QuantizedTensor) == cast_backward
Tim Moon's avatar
Tim Moon committed
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846

        # Check values
        tols = dict(rtol=0, atol=0)
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, dx_ref, **tols)

    def _test_basic_linear(
        self,
        *,
        weight_shape: tuple[int, int] = (32, 32),
        in_shape: Iterable[int] = (32, -1),
        dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
847
848
849
850
851
852
853
        quantization: Optional[str] = None,
        quantized_compute: bool = False,
        quantized_input: bool = False,
        quantized_weight: bool = False,
        quantized_output: bool = False,
        quantized_grad_output: bool = False,
        quantized_grad_input: bool = False,
Tim Moon's avatar
Tim Moon committed
854
855
856
        accumulate_into_main_grad: bool = False,
    ) -> None:
        """Helper function for tests with GEMM"""
857
858
859
860
861
862
863

        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = list(in_shape)[:-1] + [in_features]
        out_shape = in_shape[:-1] + [out_features]

        # Skip invalid configurations
864
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
865
        maybe_skip_quantization(quantization, dims=out_shape)
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
        quantization_needed = any(
            (
                quantized_compute,
                quantized_input,
                quantized_weight,
                quantized_output,
                quantized_grad_output,
                quantized_grad_input,
            )
        )
        if quantization is None and quantization_needed:
            pytest.skip("Quantization scheme is not specified")
        if quantization is not None and not quantization_needed:
            pytest.skip("Quantization scheme is not used")
        if quantization in ("fp8", "fp8_delayed_scaling", "fp8_current_scaling"):
            if quantized_output and not quantized_compute:
                pytest.skip("FP8 output is only supported with FP8 GEMMs")
            if quantized_grad_input and not quantized_compute:
                pytest.skip("FP8 grad input is only supported with FP8 GEMMs")
885
886
887
        if quantization not in (None, "fp8"):
            if quantized_output or quantized_grad_input:
                pytest.skip("Recipe does not support quantized GEMM output")
yuguo's avatar
yuguo committed
888
889
890
        if ( IS_HIP_EXTENSION and not use_hipblaslt() and
            accumulate_into_main_grad and dtype != torch.float32 and not quantized_compute):
            pytest.skip("Parameters combination is not supported by ROCBLAS")
891
892
893
894

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
895
            quantization=quantization,
896
897
            test_dtype=dtype,
            test_device=device,
898
            test_is_quantized=quantized_input,
899
900
901
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (out_features, in_features),
902
            quantization=quantization,
903
904
905
906
907
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
908
            quantization=quantization,
909
910
            test_dtype=dtype,
            test_device=device,
911
            test_is_quantized=quantized_grad_output,
912
913
914
915
916
917
918
919
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.linear(x_ref, w_ref)
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
920
        recipe = make_recipe(quantization)
921
        with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
922
923
924
925
926
927
928
            op = te_ops.BasicLinear(
                in_features,
                out_features,
                device=device,
                dtype=dtype,
                accumulate_into_main_grad=accumulate_into_main_grad,
            )
929
930
931
932
933
            forward = te_ops.Sequential(
                te_ops.Quantize(forward=quantized_input, backward=quantized_grad_input),
                op,
                te_ops.Quantize(forward=quantized_output, backward=quantized_grad_output),
            )
934
935
936
937
        with torch.no_grad():
            op.weight.copy_(w_test)
            del w_test
            op.weight.main_grad = torch.full_like(op.weight, 0.5, dtype=torch.float32)
938
        with te.autocast(enabled=quantized_compute, recipe=recipe):
Tim Moon's avatar
Tim Moon committed
939
            y_test = forward(x_test)
940
941
942
943
944
945
        y_test.backward(dy_test)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM
946
        if quantized_compute or quantized_output or quantized_grad_input:
947
            tols = quantization_tols(quantization)
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        if accumulate_into_main_grad:
            if op.weight.grad is not None:
                torch.testing.assert_close(
                    op.weight.grad,
                    torch.zeros_like(op.weight.grad),
                    rtol=0,
                    atol=0,
                )
            dw_test = op.weight.main_grad.to(dtype=torch.float64, device="cpu") - 0.5
        else:
            dw_test = op.weight.grad.to(dtype=torch.float64, device="cpu")
            torch.testing.assert_close(
                op.weight.main_grad,
                torch.full_like(op.weight.main_grad, 0.5),
                rtol=0,
                atol=0,
            )
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)

973
974
    @pytest.mark.parametrize("weight_shape", ((64, 32), (3, 5)))
    @pytest.mark.parametrize("in_shape", ((-1,), (5, 1, -1), (4, 2, 4, -1)))
Tim Moon's avatar
Tim Moon committed
975
    @pytest.mark.parametrize("dtype", _dtypes)
976
    @pytest.mark.parametrize("quantization", _quantization_list)
Tim Moon's avatar
Tim Moon committed
977
978
979
980
981
982
983
    @pytest.mark.parametrize("accumulate_into_main_grad", (False, True))
    def test_basic_linear(
        self,
        *,
        weight_shape: tuple[int, int],
        in_shape: Iterable[int],
        dtype: torch.dtype,
984
        quantization: Optional[str],
Tim Moon's avatar
Tim Moon committed
985
986
987
988
989
990
991
        accumulate_into_main_grad: bool,
    ) -> None:
        """GEMM"""
        self._test_basic_linear(
            weight_shape=weight_shape,
            in_shape=in_shape,
            dtype=dtype,
992
993
            quantization=quantization,
            quantized_compute=quantization is not None,
Tim Moon's avatar
Tim Moon committed
994
995
996
997
            accumulate_into_main_grad=accumulate_into_main_grad,
        )

    @pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8)
998
    @pytest.mark.parametrize("quantization", _quantization_list)
999
1000
1001
1002
1003
1004
1005
    @pytest.mark.parametrize("quantized_compute", (False, True))
    @pytest.mark.parametrize("quantized_input", (False, True))
    @pytest.mark.parametrize("quantized_weight", (False, True))
    @pytest.mark.parametrize("quantized_output", (False, True))
    @pytest.mark.parametrize("quantized_grad_output", (False, True))
    @pytest.mark.parametrize("quantized_grad_input", (False, True))
    def test_basic_linear_quantized(
Tim Moon's avatar
Tim Moon committed
1006
1007
        self,
        *,
1008
1009
1010
1011
1012
1013
1014
        quantization: str,
        quantized_compute: bool,
        quantized_input: bool,
        quantized_weight: bool,
        quantized_output: bool,
        quantized_grad_output: bool,
        quantized_grad_input: bool,
Tim Moon's avatar
Tim Moon committed
1015
1016
    ) -> None:
        """GEMM with FP8 inputs and outputs"""
1017
1018
        if quantization is None:
            pytest.skip("Skipping case without quantization")
Tim Moon's avatar
Tim Moon committed
1019
1020
        self._test_basic_linear(
            dtype=torch.bfloat16,
1021
1022
1023
1024
1025
1026
1027
            quantization=quantization,
            quantized_compute=quantized_compute,
            quantized_input=quantized_input,
            quantized_weight=quantized_weight,
            quantized_output=quantized_output,
            quantized_grad_output=quantized_grad_output,
            quantized_grad_input=quantized_grad_input,
Tim Moon's avatar
Tim Moon committed
1028
1029
        )

1030
    @pytest.mark.parametrize("bias", (False, True))
1031
1032
    @pytest.mark.parametrize("quantization", _quantization_list)
    @pytest.mark.parametrize("quantized_compute", (False, True))
1033
    @pytest.mark.parametrize("quantized_weight", (False, True))
1034
1035
    @pytest.mark.parametrize("input_requires_grad", (False, True))
    @pytest.mark.parametrize("weight_requires_grad", (False, True))
1036
1037
1038
1039
    def test_linear(
        self,
        *,
        bias: bool,
1040
1041
        weight_shape: tuple[int, int] = (32, 32),
        in_shape: Iterable[int] = (32, -1),
1042
1043
        dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
1044
        quantization: Optional[str],
1045
        quantized_compute: bool,
1046
        quantized_weight: bool,
1047
1048
        input_requires_grad: bool,
        weight_requires_grad: bool,
1049
1050
1051
1052
1053
1054
1055
1056
1057
    ) -> None:
        """GEMM + bias"""

        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = list(in_shape)[:-1] + [in_features]
        out_shape = in_shape[:-1] + [out_features]

        # Skip invalid configurations
1058
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
1059
        maybe_skip_quantization(quantization, dims=out_shape)
1060
1061
1062
1063
        if quantization is None and (quantized_compute or quantized_weight):
            pytest.skip("Quantization scheme is not specified")
        if quantization is not None and not (quantized_compute or quantized_weight):
            pytest.skip("Quantization scheme is not used")
1064
1065
1066
1067

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
1068
            quantization=quantization,
1069
1070
1071
1072
1073
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (out_features, in_features),
1074
            quantization=quantization,
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
            test_dtype=dtype,
            test_device=device,
        )
        b_ref, b_test = None, None
        if bias:
            b_ref, b_test = make_reference_and_test_tensors(
                out_features,
                test_dtype=dtype,
                test_device=device,
            )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
1087
            quantization=quantization,
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.linear(x_ref, w_ref, bias=b_ref)
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
1098
        recipe = make_recipe(quantization)
1099
        with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
            op = te_ops.Linear(
                in_features,
                out_features,
                bias=bias,
                device=device,
                dtype=dtype,
            )
        with torch.no_grad():
            op.weight.copy_(w_test)
            if bias:
                op.bias.copy_(b_test)
            del w_test
            del b_test
1113
1114
            for param in op.parameters():
                param.requires_grad_(requires_grad=weight_requires_grad)
1115
        with te.autocast(enabled=quantized_compute, recipe=recipe):
1116
            y_test = op(x_test)
1117
1118
        if input_requires_grad or weight_requires_grad:
            y_test.backward(dy_test)
1119
1120
1121
1122
1123

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM
1124
        if quantized_compute:
1125
            tols = quantization_tols(quantization)
1126
1127
1128
1129

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
1130
1131
1132
1133
1134
1135
1136
1137
1138
        if input_requires_grad:
            dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
            torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        if weight_requires_grad:
            dw_test = op.weight.grad.to(dtype=torch.float64, device="cpu")
            torch.testing.assert_close(dw_test, w_ref.grad, **tols)
            if bias:
                db_test = op.bias.grad.to(dtype=torch.float64, device="cpu")
                torch.testing.assert_close(db_test, b_ref.grad, **tols)
1139

1140
1141
    @pytest.mark.parametrize("weight_shape", ((7, 2), (32,)))
    @pytest.mark.parametrize("in_shape", ((-1,), (6, 16, -1)))
Tim Moon's avatar
Tim Moon committed
1142
1143
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("zero_centered_gamma", (False, True))
1144
    @pytest.mark.parametrize("quantization", _quantization_list)
Tim Moon's avatar
Tim Moon committed
1145
1146
1147
1148
1149
1150
1151
1152
1153
    def test_layer_norm(
        self,
        *,
        weight_shape: Iterable[int],
        in_shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device = "cuda",
        eps: float = 0.3,
        zero_centered_gamma: bool,
1154
        quantization: Optional[str],
Tim Moon's avatar
Tim Moon committed
1155
1156
1157
1158
1159
1160
1161
    ) -> None:
        """Layer norm"""

        # Make input and weight shapes consistent
        in_shape = list(in_shape)[:-1] + list(weight_shape)

        # Skip invalid configurations
1162
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
Tim Moon's avatar
Tim Moon committed
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            weight_shape,
            test_dtype=dtype,
            test_device=device,
        )
        b_ref, b_test = make_reference_and_test_tensors(
            weight_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.layer_norm(
            x_ref,
            weight_shape,
            weight=(w_ref + 1 if zero_centered_gamma else w_ref),
            bias=b_ref,
            eps=eps,
        )
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = te_ops.LayerNorm(
            weight_shape,
            eps=eps,
            device=device,
            dtype=dtype,
            zero_centered_gamma=zero_centered_gamma,
        )
        with torch.no_grad():
            op.weight.copy_(w_test)
            op.bias.copy_(b_test)
            del w_test
            del b_test
1210
1211
        quantized_compute = quantization is not None
        recipe = make_recipe(quantization)
Tim Moon's avatar
Tim Moon committed
1212
1213
        forward = te_ops.Sequential(
            op,
1214
            te_ops.Quantize(forward=quantized_compute, backward=False),
Tim Moon's avatar
Tim Moon committed
1215
        )
1216
        with te.autocast(enabled=quantized_compute, recipe=recipe):
Tim Moon's avatar
Tim Moon committed
1217
1218
1219
1220
1221
            y_test = forward(x_test)
        y_test.backward(dy_test)

        # Expected numerical error
        tols = dtype_tols(dtype)
1222
        if quantized_compute:
1223
            tols = quantization_tols(quantization)
Tim Moon's avatar
Tim Moon committed
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = op.weight.grad.to(dtype=torch.float64, device="cpu")
        db_test = op.bias.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)
        torch.testing.assert_close(db_test, b_ref.grad, **tols)

    def test_layer_norm_autocast(
        self,
        *,
        weight_shape: Iterable[int] = (32,),
        in_shape: Iterable[int] = (32,),
        dtype: torch.dtype = torch.float16,
        autocast_dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
        eps: float = 0.3,
    ) -> None:
        """Layer norm with PyTorch autocast"""

        # Make input and weight shapes consistent
        in_shape = list(in_shape)[:-1] + list(weight_shape)

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=autocast_dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            weight_shape,
            test_dtype=dtype,
            test_device=device,
        )
        b_ref, b_test = make_reference_and_test_tensors(
            weight_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=autocast_dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.layer_norm(
            x_ref,
            weight_shape,
            weight=w_ref,
            bias=b_ref,
            eps=eps,
        )
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = te_ops.LayerNorm(
            weight_shape,
            eps=eps,
            device=device,
            dtype=dtype,
        )
        with torch.no_grad():
            op.weight.copy_(w_test)
            op.bias.copy_(b_test)
            del w_test
            del b_test
        with torch.autocast(device, dtype=autocast_dtype):
            y_test = op(x_test)
        y_test.backward(dy_test)

        # Check results
        assert y_test.dtype == autocast_dtype
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = op.weight.grad.to(dtype=torch.float64, device="cpu")
        db_test = op.bias.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **dtype_tols(autocast_dtype))
        torch.testing.assert_close(dx_test, x_ref.grad, **dtype_tols(autocast_dtype))
        torch.testing.assert_close(dw_test, w_ref.grad, **dtype_tols(dtype))
        torch.testing.assert_close(db_test, b_ref.grad, **dtype_tols(dtype))

1310
1311
    @pytest.mark.parametrize("weight_shape", ((19,), (64,)))
    @pytest.mark.parametrize("in_shape", ((-1,), (6, 16, -1)))
Tim Moon's avatar
Tim Moon committed
1312
1313
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("zero_centered_gamma", (False, True))
1314
    @pytest.mark.parametrize("quantization", _quantization_list)
Tim Moon's avatar
Tim Moon committed
1315
1316
1317
1318
1319
1320
1321
1322
1323
    def test_rmsnorm(
        self,
        *,
        weight_shape: Iterable[int],
        in_shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device = "cuda",
        eps: float = 0.3,
        zero_centered_gamma: bool,
1324
        quantization: Optional[str],
Tim Moon's avatar
Tim Moon committed
1325
1326
1327
1328
1329
1330
1331
    ) -> None:
        """Layer norm"""

        # Make input and weight shapes consistent
        in_shape = list(in_shape)[:-1] + list(weight_shape)

        # Skip invalid configurations
1332
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
Tim Moon's avatar
Tim Moon committed
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            weight_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        inner_dims = tuple(range(len(in_shape) - len(weight_shape), len(in_shape)))
        var_ref = x_ref.square().sum(dim=inner_dims, keepdim=True) / math.prod(weight_shape)
        if zero_centered_gamma:
            y_ref = x_ref / torch.sqrt(eps + var_ref) * (1 + w_ref)
        else:
            y_ref = x_ref / torch.sqrt(eps + var_ref) * w_ref
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = te_ops.RMSNorm(
            weight_shape,
            eps=eps,
            device=device,
            dtype=dtype,
            zero_centered_gamma=zero_centered_gamma,
        )
        with torch.no_grad():
            op.weight.copy_(w_test)
            del w_test
1372
1373
        quantized_compute = quantization is not None
        recipe = make_recipe(quantization)
Tim Moon's avatar
Tim Moon committed
1374
1375
        forward = te_ops.Sequential(
            op,
1376
            te_ops.Quantize(forward=quantized_compute, backward=False),
Tim Moon's avatar
Tim Moon committed
1377
        )
1378
        with te.autocast(enabled=quantized_compute, recipe=recipe):
Tim Moon's avatar
Tim Moon committed
1379
1380
1381
1382
1383
            y_test = forward(x_test)
        y_test.backward(dy_test)

        # Expected numerical error
        tols = dtype_tols(dtype)
1384
        if quantized_compute:
1385
            tols = quantization_tols(quantization)
Tim Moon's avatar
Tim Moon committed
1386
1387
1388
1389
1390
1391
1392
1393
1394

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = op.weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)

1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
    @pytest.mark.parametrize("in_shape", ((32,), (6, 16, 64), (32, 64)))
    @pytest.mark.parametrize("dtype", _dtypes)
    def test_l2normalization(
        self,
        *,
        in_shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device = "cuda",
        eps: float = 1e-6,
    ) -> None:
        """L2 Normalization"""

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        # L2 norm: x / ||x||_2 = x / sqrt(sum(x^2) + eps)
        l2_norm_squared = x_ref.pow(2).sum(dim=-1, keepdim=True)
        rsqrt_norm = torch.rsqrt(l2_norm_squared + eps)
        y_ref = x_ref * rsqrt_norm
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = te_ops.L2Normalization(
            eps=eps,
        )
        y_test = op(x_test)
        y_test.backward(dy_test)

        # Expected numerical error
        tols = dtype_tols(dtype)

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")

        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
Tim Moon's avatar
Tim Moon committed
1443

1444
    @pytest.mark.parametrize("in_place", (True, False))
1445
1446
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("device", ("cuda", "cpu"))
1447
    @pytest.mark.parametrize("quantization", _quantization_list)
1448
    def test_add_extra_input(
1449
1450
        self,
        *,
1451
        in_shape: Iterable[int] = (32, 32),
1452
        in_place: bool,
1453
1454
        dtype: torch.dtype,
        device: torch.device,
1455
        quantization: Optional[str],
1456
    ) -> None:
Tim Moon's avatar
Tim Moon committed
1457
1458
1459
1460
1461
        """Add two tensors

        Join in compute graph.

        """
1462
1463

        # Skip invalid configurations
1464
        with_quantization = quantization is not None
1465
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
1466
1467
1468
1469

        # Random data
        x1_ref, x1_test = make_reference_and_test_tensors(
            in_shape,
1470
            quantization=quantization,
1471
1472
            test_dtype=dtype,
            test_device=device,
1473
            test_is_quantized=with_quantization,
1474
1475
1476
        )
        x2_ref, x2_test = make_reference_and_test_tensors(
            in_shape,
1477
            quantization=quantization,
1478
1479
            test_dtype=dtype,
            test_device=device,
1480
            test_is_quantized=with_quantization,
1481
1482
1483
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
1484
            quantization=quantization,
1485
1486
            test_dtype=dtype,
            test_device=device,
1487
            test_is_quantized=with_quantization,
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = x2_ref.detach()
        y_ref += x1_ref
        dx1_ref = dy_ref
        dx2_ref = dy_ref

        # Implementation with fusible operation
1498
        op = te_ops.AddExtraInput(in_place=in_place)
1499
1500
1501
1502
1503
        y_test = op(x1_test, x2_test)
        y_test.backward(dy_test)

        # Check results
        tols = dtype_tols(dtype)
1504
1505
1506
1507
1508
        if in_place:
            if quantization in ("fp8_delayed_scaling", "fp8_current_scaling", "mxfp8"):
                tols = dtype_tols(x1_test._fp8_dtype)
            elif quantization == "nvfp4":
                tols = dtype_tols(x1_test._fp4_dtype)
1509
1510
1511
1512
1513
1514
1515
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx1_test = x1_test.grad.to(dtype=torch.float64, device="cpu")
        dx2_test = x2_test.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx1_test, dx1_ref, rtol=0, atol=0)
        torch.testing.assert_close(dx2_test, dx2_ref, rtol=0, atol=0)

1516
    @pytest.mark.parametrize("in_place", (True, False))
1517
1518
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("device", ("cuda", "cpu"))
1519
    @pytest.mark.parametrize("quantization", _quantization_list)
1520
1521
1522
    def test_make_extra_output(
        self,
        *,
1523
        in_shape: Iterable[int] = (32, 32),
1524
        in_place: bool,
1525
1526
        dtype: torch.dtype,
        device: torch.device,
1527
        quantization: Optional[str],
1528
    ) -> None:
Tim Moon's avatar
Tim Moon committed
1529
1530
1531
1532
1533
        """Output tensor twice

        Split in compute graph.

        """
1534
1535

        # Skip invalid configurations
1536
        with_quantization = quantization is not None
1537
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
1538
1539
1540
1541

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
1542
            quantization=quantization,
1543
1544
            test_dtype=dtype,
            test_device=device,
1545
            test_is_quantized=with_quantization,
1546
1547
1548
        )
        dy1_ref, dy1_test = make_reference_and_test_tensors(
            in_shape,
1549
            quantization=quantization,
1550
1551
            test_dtype=dtype,
            test_device=device,
1552
            test_is_quantized=with_quantization,
1553
1554
1555
1556
            requires_grad=False,
        )
        dy2_ref, dy2_test = make_reference_and_test_tensors(
            in_shape,
1557
            quantization=quantization,
1558
1559
            test_dtype=dtype,
            test_device=device,
1560
            test_is_quantized=with_quantization,
1561
1562
1563
1564
1565
1566
1567
1568
1569
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y1_ref = x_ref
        y2_ref = x_ref
        (y1_ref * dy1_ref + y2_ref * dy2_ref).sum().backward()

        # Implementation with fusible operation
1570
        op = te_ops.MakeExtraOutput(in_place=in_place)
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
        y1_test, y2_test = op(x_test)
        (y1_test * dy1_test + y2_test * dy2_test).sum().backward()

        # Check results
        tols = dtype_tols(dtype)
        y1_test = y1_test.to(dtype=torch.float64, device="cpu")
        y2_test = y2_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y1_test, y1_ref, rtol=0, atol=0)
        torch.testing.assert_close(y2_test, y2_ref, rtol=0, atol=0)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)

1583
1584
    @pytest.mark.parametrize(
        "activation",
Kim, Jin (Jay@SKT)'s avatar
Kim, Jin (Jay@SKT) committed
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
        (
            "gelu",
            "geglu",
            "qgelu",
            "qgeglu",
            "relu",
            "reglu",
            "glu",
            "srelu",
            "sreglu",
            "silu",
            "swiglu",
        ),
1598
    )
1599
    @pytest.mark.parametrize("out_shape", ((37,), (2, 13), (32, 1, 32)))
1600
    @pytest.mark.parametrize("dtype", _dtypes)
1601
    @pytest.mark.parametrize("quantization", _quantization_list)
1602
    @pytest.mark.parametrize("cache_quantized_input", (False, True))
1603
1604
1605
1606
1607
1608
1609
    def test_activation(
        self,
        *,
        activation: str,
        out_shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device = "cuda",
1610
        quantization: Optional[str],
1611
        cache_quantized_input: bool,
1612
1613
1614
1615
1616
    ) -> None:
        """Activation functions"""

        # Tensor dimensions
        in_shape = list(out_shape)
Kim, Jin (Jay@SKT)'s avatar
Kim, Jin (Jay@SKT) committed
1617
        if activation in ("geglu", "glu", "qgeglu", "reglu", "sreglu", "swiglu"):
1618
1619
1620
            in_shape[-1] *= 2

        # Skip invalid configurations
1621
        quantized_compute = quantization is not None
1622
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
1623
        if cache_quantized_input:
1624
            maybe_skip_quantization("fp8_current_scaling", device=device)
1625
1626
1627
1628

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
1629
            quantization="fp8_current_scaling" if cache_quantized_input else None,
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref: torch.Tensor
        if activation == "gelu":
            y_ref = torch.nn.functional.gelu(x_ref, approximate="tanh")
        elif activation == "geglu":
            x1, x2 = x_ref.chunk(2, dim=-1)
            y_ref = torch.nn.functional.gelu(x1, approximate="tanh") * x2
1647
1648
1649
1650
1651
1652
1653
        elif activation == "qgelu":
            y_ref = x_ref * torch.sigmoid(1.702 * x_ref)
        elif activation == "qgeglu":
            x1, x2 = x_ref.chunk(2, dim=-1)
            y_ref = x1 * torch.sigmoid(1.702 * x1) * x2
        elif activation == "relu":
            y_ref = torch.nn.functional.relu(x_ref)
1654
1655
1656
        elif activation == "reglu":
            x1, x2 = x_ref.chunk(2, dim=-1)
            y_ref = torch.nn.functional.relu(x1) * x2
Kim, Jin (Jay@SKT)'s avatar
Kim, Jin (Jay@SKT) committed
1657
1658
1659
1660
1661
1662
1663
        elif activation == "sigmoid":
            y_ref = torch.nn.functional.sigmoid(x_ref)
        elif activation == "glu":
            x = x_ref.reshape(*in_shape[:-1], 2, in_shape[-1] // 2)
            x = x.flip(-2)  # PyTorch GLU swaps gate and linear unit
            x = x.reshape(in_shape)
            y_ref = torch.nn.functional.glu(x)
1664
1665
1666
1667
1668
1669
1670
        elif activation == "srelu":
            y_ref = torch.nn.functional.relu(x_ref) ** 2
        elif activation == "sreglu":
            x1, x2 = x_ref.chunk(2, dim=-1)
            y_ref = torch.nn.functional.relu(x1) ** 2 * x2
        elif activation == "silu":
            y_ref = torch.nn.functional.silu(x_ref)
1671
1672
1673
1674
1675
1676
1677
1678
        elif activation == "swiglu":
            x1, x2 = x_ref.chunk(2, dim=-1)
            y_ref = torch.nn.functional.silu(x1) * x2
        else:
            raise ValueError(f"Unexpected activation function ({activation})")
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
1679
        recipe = make_recipe(quantization)
1680
1681
1682
        make_op = dict(
            gelu=te_ops.GELU,
            geglu=te_ops.GEGLU,
Kim, Jin (Jay@SKT)'s avatar
Kim, Jin (Jay@SKT) committed
1683
            glu=te_ops.GLU,
1684
1685
1686
            qgelu=te_ops.QGELU,
            qgeglu=te_ops.QGEGLU,
            relu=te_ops.ReLU,
1687
            reglu=te_ops.ReGLU,
1688
1689
1690
            srelu=te_ops.SReLU,
            sreglu=te_ops.SReGLU,
            silu=te_ops.SiLU,
1691
1692
1693
            swiglu=te_ops.SwiGLU,
        )[activation]
        forward = te_ops.Sequential(
1694
            te_ops.Quantize(forward=False, backward=quantized_compute),
1695
            make_op(cache_quantized_input=cache_quantized_input),
1696
            te_ops.Quantize(forward=quantized_compute, backward=False),
1697
        )
1698
        with te.autocast(enabled=quantized_compute, recipe=recipe):
1699
1700
1701
1702
1703
            y_test = forward(x_test)
        y_test.backward(dy_test)

        # Expected numerical error
        tols = dtype_tols(dtype)
1704
1705
1706
1707
        if quantized_compute:
            tols = quantization_tols(quantization)
        elif cache_quantized_input:
            tols = quantization_tols("fp8_current_scaling")
1708
1709
1710
1711
1712
1713
1714
1715

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)

    @pytest.mark.parametrize("dtype", _dtypes)
1716
    @pytest.mark.parametrize("quantization", _quantization_list)
1717
1718
    @pytest.mark.parametrize("quantize_forward", (False, True))
    @pytest.mark.parametrize("quantize_backward", (False, True))
1719
1720
1721
    def test_swiglu(
        self,
        *,
1722
        out_shape: Iterable[int] = (32, 32),
1723
1724
        dtype: torch.dtype,
        device: torch.device = "cuda",
1725
1726
1727
        quantization: Optional[str],
        quantize_forward: bool,
        quantize_backward: bool,
1728
        glu_interleave_size: Optional[int] = None,
1729
1730
1731
1732
1733
1734
1735
    ):

        # Tensor dimensions
        in_shape = list(out_shape)
        in_shape[-1] *= 2

        # Skip invalid configurations
1736
1737
1738
        quantized_compute = quantization is not None
        if not quantized_compute and (quantize_forward or quantize_backward):
            pytest.skip("Quantization scheme has not been provided")
1739
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
        x = x_ref
        if glu_interleave_size is not None:
            x = x.reshape(
                *in_shape[:-1],
                in_shape[-1] // (2 * glu_interleave_size),
                2,
                glu_interleave_size,
            )
            x = x.transpose(-3, -2)
            x = x.reshape(in_shape)
        x1, x2 = x.chunk(2, dim=-1)
1766
1767
1768
1769
        y_ref = torch.nn.functional.silu(x1) * x2
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
1770
        recipe = make_recipe(quantization)
1771
        forward = te_ops.Sequential(
1772
            te_ops.Quantize(forward=False, backward=quantize_backward),
1773
            te_ops.SwiGLU(glu_interleave_size=glu_interleave_size),
1774
            te_ops.Quantize(forward=quantize_forward, backward=False),
1775
        )
1776
        with te.autocast(enabled=quantized_compute, recipe=recipe):
1777
1778
1779
1780
1781
            y_test = forward(x_test)
        y_test.backward(dy_test)

        # Expected numerical error
        tols = dtype_tols(dtype)
1782
        if quantized_compute:
1783
            tols = quantization_tols(quantization)
1784
1785

        # Check results
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
        assert_close(y_test, y_ref, **tols)
        assert_close_grads(x_test, x_ref, **tols)

    def test_interleaved_swiglu(self):
        """SwiGLU with block interleaved input format"""
        self.test_swiglu(
            out_shape=(32, 192),
            dtype=torch.float32,
            quantization=None,
            quantize_forward=False,
            quantize_backward=False,
            glu_interleave_size=32,
        )
1799

1800
1801
1802
1803
1804
1805
1806
1807
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("quantization", _quantization_list)
    @pytest.mark.parametrize("quantize_forward", (False, True))
    @pytest.mark.parametrize("quantize_backward", (False, True))
    def test_clamped_swiglu(
        self,
        *,
        out_shape: Iterable[int] = (32, 32),
1808
        glu_interleave_size: Optional[int] = None,
1809
1810
1811
1812
1813
1814
1815
1816
        dtype: torch.dtype,
        device: torch.device = "cuda",
        quantization: Optional[str],
        quantize_forward: bool,
        quantize_backward: bool,
        limit: float = 0.75,
        alpha: float = 1.702,
    ):
1817
        """SwiGLU variant used in GPT-OSS"""
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
        # Tensor dimensions
        in_shape = list(out_shape)
        in_shape[-1] *= 2

        # Skip invalid configurations
        quantized_compute = quantization is not None
        if not quantized_compute and (quantize_forward or quantize_backward):
            pytest.skip("Quantization scheme has not been provided")
        maybe_skip_quantization(quantization, dims=in_shape, device=device)

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
        x = x_ref
        if glu_interleave_size is not None:
            x = x.reshape(
                *in_shape[:-1],
                in_shape[-1] // (2 * glu_interleave_size),
                2,
                glu_interleave_size,
            )
            x = x.transpose(-3, -2)
            x = x.reshape(in_shape)
        x_glu, x_linear = x.chunk(2, dim=-1)
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
        x_glu = x_glu.clamp(min=None, max=limit)
        x_linear = x_linear.clamp(min=-limit, max=limit)
        out_glu = x_glu * torch.sigmoid(alpha * x_glu)
        y_ref = out_glu * (x_linear + 1)
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        recipe = make_recipe(quantization)

        forward = te_ops.Sequential(
            te_ops.Quantize(forward=False, backward=quantize_backward),
1864
1865
1866
1867
1868
            te_ops.ClampedSwiGLU(
                limit=limit,
                alpha=alpha,
                glu_interleave_size=glu_interleave_size,
            ),
1869
1870
            te_ops.Quantize(forward=quantize_forward, backward=False),
        )
1871
        with te.autocast(enabled=quantized_compute, recipe=recipe):
1872
1873
1874
1875
1876
1877
1878
1879
1880
            y_test = forward(x_test)

        y_test.backward(dy_test)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if quantized_compute and quantization == "nvfp4":
            tols = dtype_tols(tex.DType.kFloat4E2M1)
        elif quantized_compute:
1881
1882
1883
            tols = dtype_tols(tex.DType.kFloat8E4M3)

        # Check results
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
        assert_close(y_test, y_ref, **tols)
        assert_close_grads(x_test, x_ref, **tols)

    def test_interleaved_clamped_swiglu(self):
        """GPT-OSS SwiGLU with block interleaved input format"""
        self.test_clamped_swiglu(
            out_shape=(32, 192),
            dtype=torch.float32,
            quantization=None,
            quantize_forward=False,
            quantize_backward=False,
            glu_interleave_size=32,
        )
1897

1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
    @pytest.mark.parametrize("scale", (1, 0, -2.5, 3.5))
    @pytest.mark.parametrize("shape", ((), (1, 13), (4, 4, 2)))
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("device", _devices)
    def test_constant_scale(
        self,
        *,
        scale: float,
        shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device,
    ):

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = scale * x_ref
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = te_ops.ConstantScale(scale)
        y_test = op(x_test)
        y_test.backward(dy_test)

        # Check results
        tols = dtype_tols(dtype)
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)

vasunvidia's avatar
vasunvidia committed
1940
    @pytest.mark.parametrize("prob", (0.0625, 0.5, 0.75))
1941
    @pytest.mark.parametrize("is_training", (True, False))
vasunvidia's avatar
vasunvidia committed
1942
1943
    @pytest.mark.parametrize("quantization", (None, "fp8_current_scaling"))
    @pytest.mark.parametrize("shape", ((101,), (2, 4, 16), (128, 128)))
1944
1945
1946
1947
1948
1949
    @pytest.mark.parametrize("dtype", _dtypes)
    def test_dropout(
        self,
        *,
        prob: float,
        is_training: bool,
vasunvidia's avatar
vasunvidia committed
1950
        quantization: Optional[str],
1951
1952
1953
1954
1955
        shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device = "cuda",
    ):

vasunvidia's avatar
vasunvidia committed
1956
1957
        # Skip invalid configurations
        quantized_input = quantization is not None
1958
        maybe_skip_quantization(quantization, dims=shape, device=device, dtype=dtype)
vasunvidia's avatar
vasunvidia committed
1959

1960
        # Random data
vasunvidia's avatar
vasunvidia committed
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
        # Note: Shift values to make sure inputs are non-zero
        x_ref, x_test = make_reference_and_test_tensors(
            shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
            test_is_quantized=quantized_input,
        )
        with torch.no_grad():
            x_test += 1
            x_ref.copy_(x_test)
        dy_ref, dy_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )
1978
1979
1980
1981
1982
1983
1984

        # Apply dropout
        op = te_ops.Dropout(prob)
        if is_training:
            op.train()
        else:
            op.eval()
vasunvidia's avatar
vasunvidia committed
1985
1986
        y_test = op(x_test)
        y_test.backward(dy_test)
1987
1988

        # Check values
vasunvidia's avatar
vasunvidia committed
1989
1990
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
1991
        if is_training:
vasunvidia's avatar
vasunvidia committed
1992
1993
1994
1995
            tols = dtype_tols(dtype)
            mask = ((y_test != 0) / (1 - prob)).to(dtype=dtype)
            torch.testing.assert_close(y_test, x_ref * mask, **tols)
            torch.testing.assert_close(dx_test, dy_ref * mask, **tols)
1996
        else:
vasunvidia's avatar
vasunvidia committed
1997
1998
            torch.testing.assert_close(y_test, x_ref, rtol=0, atol=0)
            torch.testing.assert_close(dx_test, dy_ref, rtol=0, atol=0)
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009

        # Hypothesis testing for number of zeros
        # Note: A Bernoulli random variable with probability p has
        # mean p and standard deviation sqrt(p*(1-p)). By the central
        # limit theorem, the mean of n iid Bernoulli variables
        # converges to a normal random variable with mean p and
        # standard deviation sqrt(p*(1-p)/n). If the observed mean is
        # below the 0.5th or above the 99.5th percentiles, then the
        # p-value is less than 1% and we assume that the dropout
        # distribution is incorrect.
        if is_training:
vasunvidia's avatar
vasunvidia committed
2010
2011
2012
2013
2014
            prob_observed = 1 - torch.count_nonzero(y_test).item() / y_test.numel()
            z_score = (prob_observed - prob) / math.sqrt(prob * (1 - prob) / y_test.numel())
            assert (
                abs(z_score) < 2.5758
            ), f"Number of zeros is outside 99% confidence interval ({prob=}, {prob_observed=})"
2015

2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
    @pytest.mark.parametrize("bias", (False, True))
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("quantization", _quantization_list)
    @pytest.mark.parametrize("quantized_compute", (False, True))
    @pytest.mark.parametrize("quantized_weight", (False, True))
    @pytest.mark.parametrize("input_requires_grad", (False, True))
    @pytest.mark.parametrize("weight_requires_grad", (False, True))
    def test_grouped_linear(
        self,
        *,
        group_size: int = 4,
        bias: bool,
        weight_shape: tuple[int, int] = (128, 128),
        split_alignment: int = 128,
        dtype: torch.dtype,
        device: torch.device = "cuda",
        quantization: Optional[str],
        quantized_compute: bool,
        quantized_weight: bool,
        input_requires_grad: bool,
        weight_requires_grad: bool,
    ) -> None:
        """Grouped GEMM"""

        # Split sizes
        split_sizes = [split_alignment * i for i in range(group_size)]
        random.shuffle(split_sizes)
        split_sizes = torch.tensor(split_sizes, dtype=torch.int, device=device)

        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = (split_sizes.sum().item(), in_features)
        out_shape = (in_shape[0], out_features)

        # Skip invalid configurations
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
        maybe_skip_quantization(quantization, dims=out_shape)
        if quantization is None and (quantized_compute or quantized_weight):
            pytest.skip("Quantization scheme is not specified")
        if quantization is not None and not (quantized_compute or quantized_weight):
            pytest.skip("Quantization scheme is not used")
        if quantization is not None and dtype not in (torch.bfloat16, torch.float16):
            pytest.skip("Quantized group GEMM is only supported with BF16/FP16")

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
            requires_grad=input_requires_grad,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )
        ws_ref, ws_test = [], []
        bs_ref, bs_test = [], []
        for _ in range(group_size):
            w_ref, w_test = make_reference_and_test_tensors(
                (out_features, in_features),
                quantization=quantization,
                test_dtype=dtype,
                test_device=device,
                requires_grad=weight_requires_grad,
            )
            b_ref, b_test = None, None
            if bias:
                b_ref, b_test = make_reference_and_test_tensors(
                    out_features,
                    test_dtype=dtype,
                    test_device=device,
                    requires_grad=weight_requires_grad,
                )
            ws_ref.append(w_ref)
            ws_test.append(w_test)
            bs_ref.append(b_ref)
            bs_test.append(b_test)

        # Plain PyTorch implementation
        xs_ref = torch.split(x_ref, split_sizes.tolist())
        ys_ref = []
        for x, w, b in zip(xs_ref, ws_ref, bs_ref):
            ys_ref.append(torch.nn.functional.linear(x, w, bias=b))
        y_ref = torch.cat(ys_ref)
        if input_requires_grad or weight_requires_grad:
            y_ref.backward(dy_ref)

        # Construct fusible operation
        recipe = make_recipe(quantization)
        with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
            op = te_ops.GroupedLinear(
                group_size,
                in_features,
                out_features,
                bias=bias,
                device=device,
                dtype=dtype,
            )
        with torch.no_grad():
            for group_idx in range(group_size):
                getattr(op, f"weight{group_idx}").copy_(ws_test[group_idx])
                if bias:
                    getattr(op, f"bias{group_idx}").copy_(bs_test[group_idx])
            del ws_test, bs_test
            for param in op.parameters():
                param.requires_grad_(requires_grad=weight_requires_grad)

        # Forward and backward pass with op
        with te.autocast(enabled=quantized_compute, recipe=recipe):
            y_test = op(x_test, split_sizes)
        if input_requires_grad or weight_requires_grad:
            y_test.backward(dy_test)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM
        if quantized_compute:
            tols = quantization_tols(quantization)

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        if input_requires_grad:
            dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
            torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        else:
            assert x_test.grad is None
        for group_idx in range(group_size):
            w_test = getattr(op, f"weight{group_idx}")
            if weight_requires_grad:
                dw_test = w_test.grad.to(dtype=torch.float64, device="cpu")
                torch.testing.assert_close(dw_test, ws_ref[group_idx].grad, **tols)
            else:
                assert w_test.grad is None
            if bias:
                b_test = getattr(op, f"bias{group_idx}")
                if weight_requires_grad:
                    db_test = b_test.grad.to(dtype=torch.float64, device="cpu")
                    torch.testing.assert_close(db_test, bs_ref[group_idx].grad, **tols)
                else:
                    assert b_test.grad is None

    @pytest.mark.parametrize("in_shape", ((71, 192), (5, 7, 128)))
    @pytest.mark.parametrize("input_requires_grad", (False, True))
    @pytest.mark.parametrize("scales_requires_grad", (False, True))
    def test_scaled_swiglu(
        self,
        *,
        in_shape: Iterable[int],
        glu_interleave_size: Optional[int] = None,
        dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
        input_requires_grad: bool,
        scales_requires_grad: bool,
    ) -> None:
        """SwiGLU with post-scale"""

        # Tensor dims
        out_shape = list(in_shape)
        out_shape[-1] //= 2

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=input_requires_grad,
        )
        scales_ref, scales_test = make_reference_and_test_tensors(
            in_shape[:-1],
            test_dtype=dtype,
            test_device=device,
            requires_grad=scales_requires_grad,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        x = x_ref
        if glu_interleave_size is not None:
            x = x.reshape(
                -1,
                in_shape[-1] // (2 * glu_interleave_size),
                2,
                glu_interleave_size,
            )
            x = x.transpose(1, 2)
            x = x.reshape(in_shape)
        x1, x2 = x.chunk(2, dim=-1)
        y = torch.nn.functional.silu(x1) * x2
        y_ref = scales_ref.unsqueeze(-1) * y
        if input_requires_grad or scales_requires_grad:
            y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = te_ops.ScaledSwiGLU(glu_interleave_size=glu_interleave_size)
        y_test = op(x_test, scales_test)
        if input_requires_grad or scales_requires_grad:
            y_test.backward(dy_test)

        # Check results
        tols = dtype_tols(dtype)
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        assert_close(y_test, y_ref, **tols)
        assert_close_grads(x_test, x_ref, **tols)
        assert_close_grads(scales_test, scales_ref, **tols)

    def test_interleaved_scaled_swiglu(self):
        """SwiGLU with post-scale and block interleaved input format"""
        self.test_scaled_swiglu(
            in_shape=(32, 192),
            glu_interleave_size=32,
            input_requires_grad=True,
            scales_requires_grad=True,
        )

2241
2242
2243
2244
2245
2246

class TestFusedOps:
    """Tests for fused operations"""

    @staticmethod
    def setup_class(cls) -> None:
2247
        reset_rng_states()
2248

2249
2250
    @pytest.mark.parametrize("weight_shape", ((32, 64), (3, 5)))
    @pytest.mark.parametrize("in_shape", ((-1,), (1, 7, -1), (8, 2, 10, -1)))
2251
    @pytest.mark.parametrize("dtype", _dtypes)
2252
    @pytest.mark.parametrize("quantization", _quantization_list)
2253
    @pytest.mark.parametrize("quantized_weight", (False, True))
2254
    def test_forward_linear_bias_activation(
2255
2256
2257
2258
2259
2260
2261
        self,
        *,
        bias: bool = True,
        weight_shape: tuple[int, int],
        in_shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device = "cuda",
2262
2263
        quantization: Optional[str],
        quantized_weight: bool,
2264
    ) -> None:
2265
        """Forward GEMM + bias + activation"""
2266
2267
2268
2269
2270
2271
2272

        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = list(in_shape)[:-1] + [in_features]
        out_shape = in_shape[:-1] + [out_features]

        # Skip invalid configurations
2273
        quantized_compute = quantization is not None
2274
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
2275
        maybe_skip_quantization(quantization, dims=out_shape)
2276
2277
2278
2279
2280
2281
2282
2283
        if dtype not in (torch.float16, torch.bfloat16):
            pytest.skip(
                "FP8 fused linear-bias-activation is only supported with FP16 or BF16 output"
            )

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
2284
            quantization=quantization,
2285
2286
2287
2288
2289
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (out_features, in_features),
2290
            quantization=quantization,
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
            test_dtype=dtype,
            test_device=device,
        )
        b_ref, b_test = None, None
        if bias:
            b_ref, b_test = make_reference_and_test_tensors(
                out_features,
                test_dtype=dtype,
                test_device=device,
            )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
2303
            quantization=quantization,
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.linear(x_ref, w_ref, bias=b_ref)
        y_ref.backward(dy_ref)

        # Implementation with fusible operations
2314
        recipe = make_recipe(quantization)
2315
        with te.quantized_model_init(enabled=quantized_compute, recipe=recipe):
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
            model = te_ops.Sequential(
                te_ops.Linear(
                    in_features,
                    out_features,
                    bias=bias,
                    device=device,
                    dtype=dtype,
                ),
            )
        with torch.no_grad():
            model[0].weight.copy_(w_test)
            if bias:
                model[0].bias.copy_(b_test)
            del w_test
            del b_test
2331
        with te.autocast(enabled=quantized_compute, recipe=recipe):
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
            y_test = model(x_test)
        y_test.backward(dy_test)

        # Check that forward operations have been fused
        forward_ops = model._module_groups[0]._forward_ops
        assert len(forward_ops) == 1
        assert isinstance(forward_ops[0][0], ForwardLinearBiasActivation)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM
2344
        if quantized_compute:
2345
            tols = quantization_tols(quantization)
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = model[0].weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)
        if bias:
            db_test = model[0].bias.grad.to(dtype=torch.float64, device="cpu")
            torch.testing.assert_close(db_test, b_ref.grad, **tols)

2358
2359
    @pytest.mark.parametrize("bias", (False, True))
    @pytest.mark.parametrize("dtype", _dtypes)
2360
    @pytest.mark.parametrize("quantization", _quantization_list)
2361
2362
2363
2364
    def test_forward_linear_bias_add(
        self,
        *,
        bias: bool,
2365
2366
        weight_shape: tuple[int, int] = (32, 32),
        in_shape: Iterable[int] = (32, -1),
2367
2368
        dtype: torch.dtype,
        device: torch.device = "cuda",
2369
2370
        quantization: Optional[str],
        quantized_weight: bool = False,
2371
2372
2373
2374
2375
2376
2377
2378
2379
    ) -> None:
        """Forward GEMM + bias + add"""

        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = list(in_shape)[:-1] + [in_features]
        out_shape = in_shape[:-1] + [out_features]

        # Skip invalid configurations
2380
        quantized_compute = quantization is not None
2381
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
2382
2383
        maybe_skip_quantization(quantization, dims=out_shape)
        if quantized_compute and dtype not in (torch.float16, torch.bfloat16):
2384
2385
2386
2387
2388
            pytest.skip("FP8 GEMM is only supported with FP8, FP16, or BF16 output")

        # Random data
        x1_ref, x1_test = make_reference_and_test_tensors(
            in_shape,
2389
            quantization=quantization,
2390
2391
2392
2393
2394
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (out_features, in_features),
2395
            quantization=quantization,
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
            test_dtype=dtype,
            test_device=device,
        )
        b_ref, b_test = None, None
        if bias:
            b_ref, b_test = make_reference_and_test_tensors(
                out_features,
                test_dtype=dtype,
                test_device=device,
            )
        x2_ref, x2_test = make_reference_and_test_tensors(
            out_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
2413
            quantization=quantization,
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.linear(x1_ref, w_ref, bias=b_ref) + x2_ref
        y_ref.backward(dy_ref)

        # Implementation with fusible operations
2424
        recipe = make_recipe(quantization)
2425
        with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
2426
2427
2428
2429
2430
2431
2432
2433
            model = te_ops.Sequential(
                te_ops.Linear(
                    in_features,
                    out_features,
                    bias=bias,
                    device=device,
                    dtype=dtype,
                ),
2434
                te_ops.AddExtraInput(in_place=True),
2435
2436
2437
2438
2439
2440
2441
            )
        with torch.no_grad():
            model[0].weight.copy_(w_test)
            if bias:
                model[0].bias.copy_(b_test)
            del w_test
            del b_test
2442
        with te.autocast(enabled=quantized_compute, recipe=recipe):
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
            y_test = model(x1_test, x2_test)
        y_test.backward(dy_test)

        # Check that forward operations have been fused
        forward_ops = model._module_groups[0]._forward_ops
        assert len(forward_ops) == 1
        assert isinstance(forward_ops[0][0], ForwardLinearBiasAdd)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM
2455
        if quantized_compute:
2456
            tols = quantization_tols(quantization)
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx1_test = x1_test.grad.to(dtype=torch.float64, device="cpu")
        dx2_test = x2_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = model[0].weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx1_test, x1_ref.grad, **tols)
        torch.testing.assert_close(dx2_test, x2_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)
        if bias:
            db_test = model[0].bias.grad.to(dtype=torch.float64, device="cpu")
            torch.testing.assert_close(db_test, b_ref.grad, **tols)

Jan Bielak's avatar
Jan Bielak committed
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
    @pytest.mark.parametrize("scale", (1, 0, -2.5, 3.5))
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("quantization", _quantization_list)
    def test_forward_linear_scale_add(
        self,
        *,
        scale: float,
        weight_shape: tuple[int, int] = (32, 32),
        in_shape: Iterable[int] = (32, -1),
        dtype: torch.dtype,
        device: torch.device = "cuda",
        quantization: Optional[str],
        quantized_weight: bool = False,
    ) -> None:
        """Forward GEMM + scale + add"""
zhaochao's avatar
zhaochao committed
2486
2487
        if IS_HIP_EXTENSION and scale != 1:
            pytest.skip("alpha must be 1.0 for hip")
Jan Bielak's avatar
Jan Bielak committed
2488
2489
2490
2491
2492
2493
2494
        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = list(in_shape)[:-1] + [in_features]
        out_shape = in_shape[:-1] + [out_features]

        # Skip invalid configurations
        quantized_compute = quantization is not None
2495
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
Jan Bielak's avatar
Jan Bielak committed
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
        maybe_skip_quantization(quantization, dims=out_shape)
        if quantized_compute and dtype not in (torch.float16, torch.bfloat16):
            pytest.skip("FP8 GEMM is only supported with FP8, FP16, or BF16 output")

        # Random data
        x1_ref, x1_test = make_reference_and_test_tensors(
            in_shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (out_features, in_features),
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
        )
        x2_ref, x2_test = make_reference_and_test_tensors(
            out_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.linear(x1_ref, w_ref) * scale + x2_ref
        y_ref.backward(dy_ref)

        # Implementation with fusible operations
        recipe = make_recipe(quantization)
2532
        with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
Jan Bielak's avatar
Jan Bielak committed
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
            model = te_ops.Sequential(
                te_ops.Linear(
                    in_features,
                    out_features,
                    bias=False,
                    device=device,
                    dtype=dtype,
                ),
                te_ops.ConstantScale(scale),
                te_ops.AddExtraInput(in_place=True),
                te_ops.Quantize(),
            )
        with torch.no_grad():
            model[0].weight.copy_(w_test)
            del w_test
2548
        with te.autocast(enabled=quantized_compute, recipe=recipe):
Jan Bielak's avatar
Jan Bielak committed
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
            y_test = model(x1_test, x2_test)
        y_test.backward(dy_test)

        # Check that forward operations have been fused
        forward_ops = model._module_groups[0]._forward_ops
        assert len(forward_ops) == 2
        assert isinstance(forward_ops[0][0], ForwardLinearScaleAdd)
        assert isinstance(forward_ops[1][0], te_ops.Quantize)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM
        if quantized_compute:
2563
            tols = quantization_tols(quantization)
Jan Bielak's avatar
Jan Bielak committed
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx1_test = x1_test.grad.to(dtype=torch.float64, device="cpu")
        dx2_test = x2_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = model[0].weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx1_test, x1_ref.grad, **tols)
        torch.testing.assert_close(dx2_test, x2_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)

2575
2576
2577
2578
    @pytest.mark.parametrize("activation", ("relu", "gelu"))
    @pytest.mark.parametrize("out_shape", ((32, 32), (32, 1, 32), (8, 2, 2, 32)))
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("quantization", _quantization_list)
Jan Bielak's avatar
Jan Bielak committed
2579
    def test_backward_activation_bias(
2580
2581
2582
2583
2584
2585
2586
2587
        self,
        *,
        activation: str,
        out_shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device = "cuda",
        quantization: Optional[str],
    ) -> None:
Jan Bielak's avatar
Jan Bielak committed
2588
        """Backward dact + dbias + quantize"""
2589
2590
2591
2592
2593
2594
2595

        # Tensor dimensions
        in_shape = list(out_shape)
        hidden_size = in_shape[-1]

        # Skip invalid configurations
        with_quantization = quantization is not None
2596
        maybe_skip_quantization(quantization, device=device, dtype=dtype)
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
        if quantization == "mxfp8" and (len(in_shape) < 2 or in_shape[-1] % 32 != 0):
            pytest.skip("Unsupported tensor size for MXFP8")

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
        )
        b_ref, b_test = make_reference_and_test_tensors(
            hidden_size,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = x_ref + b_ref.reshape([1] * (len(in_shape) - 1) + [hidden_size])
        if activation == "gelu":
            y_ref = torch.nn.functional.gelu(y_ref, approximate="tanh")
        elif activation == "relu":
            y_ref = torch.nn.functional.relu(y_ref)
        else:
            raise ValueError(f"Unexpected activation function ({activation})")
        y_ref.backward(dy_ref)

        # Implementation with fusible operations
        recipe = make_recipe(quantization)
        act_type = te_ops.GELU if activation == "gelu" else te_ops.ReLU
        model = te_ops.Sequential(
            te_ops.Quantize(forward=False, backward=True),
            te_ops.Bias(hidden_size, device=device, dtype=dtype),
            act_type(),
        )
        with torch.no_grad():
            model[1].bias.copy_(b_test)
            del b_test
2639
        with te.autocast(enabled=with_quantization, recipe=recipe):
2640
2641
2642
2643
2644
            y_test = model(x_test)
        y_test.backward(dy_test)

        # Check that backward operations have been fused
        backward_ops = model._module_groups[0]._backward_ops
2645
        if with_quantization:
2646
            assert len(backward_ops) == 2
2647
2648
            assert isinstance(backward_ops[0][0], te_ops.Quantize)
            assert isinstance(backward_ops[1][0], BackwardActivationBias)
2649
2650
        else:
            assert len(backward_ops) == 3
2651
            assert isinstance(backward_ops[0][0], te_ops.Quantize)
2652
            assert isinstance(backward_ops[1][0], te_ops.Bias)
2653
            assert isinstance(backward_ops[2][0], act_type)
2654
2655
2656
2657

        # Expected numerical error
        tols = dtype_tols(dtype)
        if with_quantization:
2658
            tols = quantization_tols(quantization)
2659

2660
        # Check results
2661
2662
2663
2664
2665
2666
2667
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        db_test = model[1].bias.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(db_test, b_ref.grad, **tols)

2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
    @pytest.mark.parametrize("weight_shape", ((19,), (64,)))
    @pytest.mark.parametrize("in_shape", ((-1,), (6, 16, -1)))
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("zero_centered_gamma", (False, True))
    def test_backward_add_rmsnorm(
        self,
        *,
        weight_shape: Iterable[int],
        in_shape: Iterable[int],
        dtype: torch.dtype,
        device: torch.device = "cuda",
        eps: float = 0.3,
        zero_centered_gamma: bool,
    ) -> None:
        """Fused backward RMNorm + add"""

        # Make input and weight shapes consistent
        in_shape = list(in_shape)[:-1] + list(weight_shape)

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            weight_shape,
            test_dtype=dtype,
            test_device=device,
        )
        dy1_ref, dy1_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )
        dy2_ref, dy2_test = make_reference_and_test_tensors(
            in_shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        inner_dims = tuple(range(len(in_shape) - len(weight_shape), len(in_shape)))
        var_ref = x_ref.square().sum(dim=inner_dims, keepdim=True) / math.prod(weight_shape)
        if zero_centered_gamma:
            y1_ref = x_ref / torch.sqrt(eps + var_ref) * (1 + w_ref)
        else:
            y1_ref = x_ref / torch.sqrt(eps + var_ref) * w_ref
        y2_ref = x_ref
        (y1_ref * dy1_ref + y2_ref * dy2_ref).sum().backward()

        # Implementation with fusible operations
        model = te_ops.Sequential(
            te_ops.MakeExtraOutput(),
            te_ops.RMSNorm(
                weight_shape,
                eps=eps,
                device=device,
                dtype=dtype,
                zero_centered_gamma=zero_centered_gamma,
            ),
        )
        with torch.no_grad():
            model[1].weight.copy_(w_test)
            del w_test
        y1_test, y2_test = model(x_test)
        (y1_test * dy1_test + y2_test * dy2_test).sum().backward()

        # Check that backward operations have been fused
        backward_ops = model._module_groups[0]._backward_ops
        assert len(backward_ops) == 1
        assert isinstance(backward_ops[0][0], BackwardAddRMSNorm)

        # Expected numerical error
        tols = dtype_tols(dtype)

        # Check results
        y1_test = y1_test.to(dtype=torch.float64, device="cpu")
        y2_test = y2_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = model[1].weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y1_test, y1_ref, **tols)
        torch.testing.assert_close(y2_test, y2_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)

2756
    @pytest.mark.parametrize("dtype", _dtypes)
2757
    @pytest.mark.parametrize("quantization", _quantization_list)
2758
2759
2760
    def test_backward_linear_add(
        self,
        *,
2761
2762
        weight_shape: tuple[int, int] = (32, 32),
        in_shape: Iterable[int] = (32, -1),
2763
2764
        dtype: torch.dtype,
        device: torch.device = "cuda",
2765
2766
        quantization: Optional[str],
        quantized_weight: bool = False,
2767
2768
2769
2770
2771
2772
2773
2774
2775
    ) -> None:
        """Backward dgrad GEMM + add"""

        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = list(in_shape)[:-1] + [in_features]
        out_shape = in_shape[:-1] + [out_features]

        # Skip invalid configurations
2776
        quantized_compute = quantization is not None
2777
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
2778
2779
        maybe_skip_quantization(quantization, dims=out_shape)
        if quantized_compute and dtype not in (torch.float16, torch.bfloat16):
2780
2781
2782
2783
2784
            pytest.skip("FP8 GEMM is only supported with FP8, FP16, or BF16 output")

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
2785
            quantization=quantization,
2786
2787
2788
2789
2790
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (out_features, in_features),
2791
            quantization=quantization,
2792
2793
2794
2795
2796
            test_dtype=dtype,
            test_device=device,
        )
        dy1_ref, dy1_test = make_reference_and_test_tensors(
            out_shape,
2797
            quantization=quantization,
2798
2799
2800
2801
2802
2803
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )
        dy2_ref, dy2_test = make_reference_and_test_tensors(
            out_shape,
2804
            quantization=quantization,
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y1_ref = torch.nn.functional.linear(x_ref, w_ref)
        y2_ref = x_ref
        (y1_ref * dy1_ref + y2_ref * dy2_ref).sum().backward()

        # Implementation with fusible operations
2816
        recipe = make_recipe(quantization)
2817
        with te.quantized_model_init(enabled=quantized_weight):
2818
            model = te_ops.Sequential(
2819
                te_ops.MakeExtraOutput(in_place=True),
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
                te_ops.Linear(
                    in_features,
                    out_features,
                    bias=False,
                    device=device,
                    dtype=dtype,
                ),
            )
        with torch.no_grad():
            model[1].weight.copy_(w_test)
            del w_test
2831
        with te.autocast(enabled=quantized_compute, recipe=recipe):
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
            y1_test, y2_test = model(x_test)
        (y1_test * dy1_test + y2_test * dy2_test).sum().backward()

        # Check that backward operations have been fused
        backward_ops = model._module_groups[0]._backward_ops
        assert len(backward_ops) == 1
        assert isinstance(backward_ops[0][0], BackwardLinearAdd)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM
2844
        if quantized_compute:
2845
            tols = quantization_tols(quantization)
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855

        # Check results
        y1_test = y1_test.to(dtype=torch.float64, device="cpu")
        y2_test = y2_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = model[1].weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y1_test, y1_ref, **tols)
        torch.testing.assert_close(y2_test, y2_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)
2856

Jan Bielak's avatar
Jan Bielak committed
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
    @pytest.mark.parametrize("scale", (1, 0, -2.5, 3.5))
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("quantization", _quantization_list)
    def test_backward_linear_scale(
        self,
        *,
        scale: float,
        weight_shape: tuple[int, int] = (32, 32),
        in_shape: Iterable[int] = (32, -1),
        dtype: torch.dtype,
        device: torch.device = "cuda",
        quantization: Optional[str],
        quantized_weight: bool = False,
    ) -> None:
        """Backward dgrad GEMM + scale"""
zhaochao's avatar
zhaochao committed
2872
2873
        if IS_HIP_EXTENSION and scale != 1:
            pytest.skip("alpha must be 1.0 for hip")
Jan Bielak's avatar
Jan Bielak committed
2874
2875
2876
2877
2878
2879
2880
        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = list(in_shape)[:-1] + [in_features]
        out_shape = in_shape[:-1] + [out_features]

        # Skip invalid configurations
        quantized_compute = quantization is not None
2881
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
Jan Bielak's avatar
Jan Bielak committed
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
        maybe_skip_quantization(quantization, dims=out_shape)
        if quantized_compute and dtype not in (torch.float16, torch.bfloat16):
            pytest.skip("FP8 GEMM is only supported with FP8, FP16, or BF16 output")

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (out_features, in_features),
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.linear(x_ref, w_ref) * scale
        y_ref.backward(dy_ref)

        # Implementation with fusible operations
        recipe = make_recipe(quantization)
2913
        with te.quantized_model_init(enabled=quantized_weight):
Jan Bielak's avatar
Jan Bielak committed
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
            model = te_ops.Sequential(
                te_ops.Linear(
                    in_features,
                    out_features,
                    bias=False,
                    device=device,
                    dtype=dtype,
                ),
                te_ops.ConstantScale(scale),
            )
        with torch.no_grad():
            model[0].weight.copy_(w_test)
            del w_test
2927
        with te.autocast(enabled=quantized_compute, recipe=recipe):
Jan Bielak's avatar
Jan Bielak committed
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
            y_test = model(x_test)
        (y_test * dy_test).sum().backward()

        # Check that backward operations have been fused
        backward_ops = model._module_groups[0]._backward_ops
        assert len(backward_ops) == 1
        assert isinstance(backward_ops[0][0], BackwardLinearScale)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM
        if quantized_compute:
2941
            tols = quantization_tols(quantization)
Jan Bielak's avatar
Jan Bielak committed
2942
2943
2944
2945
2946
2947
2948
2949

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = model[0].weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)
2950
2951
2952
2953
2954
2955
2956


class TestCheckpointing:
    """Tests for checkpointing"""

    @staticmethod
    def setup_class(cls) -> None:
2957
        reset_rng_states()
2958

2959
    @pytest.mark.parametrize("quantization", _quantization_list)
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
    @pytest.mark.parametrize("quantized_weight", (False, True))
    def test_linear(
        self,
        *,
        pre_checkpoint_steps: int = 2,
        post_checkpoint_steps: int = 2,
        weight_shape: tuple[int, int] = (32, 32),
        in_shape: Iterable[int] = (32, -1),
        dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
        quantization: Optional[str],
        quantized_weight: bool,
    ) -> None:
        """Check checkpointing with linear op"""

        # Make input and weight shapes consistent
        out_features, in_features = weight_shape
        in_shape = list(in_shape)[:-1] + [in_features]
        out_shape = in_shape[:-1] + [out_features]

        # Skip invalid configurations
        quantized_compute = quantization is not None
2982
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
2983
2984
2985
2986
        maybe_skip_quantization(quantization, dims=out_shape)

        # Construct model
        recipe = make_recipe(quantization)
2987
        with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
            model_save = te_ops.Sequential(
                te_ops.Linear(in_features, out_features, device=device, dtype=dtype)
            )
        optim_save = torch.optim.SGD(model_save.parameters(), lr=0.25)

        # Warmup training steps
        for _ in range(pre_checkpoint_steps):
            x = torch.randn(in_shape, dtype=dtype, device=device, requires_grad=True)
            dy = torch.randn(out_shape, dtype=dtype, device=device)
            optim_save.zero_grad()
2998
            with te.autocast(enabled=quantized_compute, recipe=recipe):
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
                y = model_save(x)
            y.backward(dy)
            optim_save.step()

        # Save checkpoint
        byte_stream = io.BytesIO()
        torch.save(
            {"model": model_save.state_dict(), "optim": optim_save.state_dict()},
            byte_stream,
        )
        checkpoint_bytes = byte_stream.getvalue()
        del byte_stream

        # Synthetic data for evaluation
        xs_save = [
            torch.randn(in_shape, dtype=dtype, device=device, requires_grad=True)
            for _ in range(post_checkpoint_steps)
        ]
        with torch.no_grad():
            xs_load = [x.clone().requires_grad_() for x in xs_save]
        dys = [
            torch.randn(out_shape, dtype=dtype, device=device) for _ in range(post_checkpoint_steps)
        ]

        # Training steps with original model
        ys_save = []
        for i in range(post_checkpoint_steps):
            optim_save.zero_grad()
3027
            with te.autocast(enabled=quantized_compute, recipe=recipe):
3028
3029
3030
3031
3032
3033
                y = model_save(xs_save[i])
            y.backward(dys[i])
            optim_save.step()
            ys_save.append(y)

        # Load checkpoint
3034
        with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
            model_load = te_ops.Sequential(
                te_ops.Linear(in_features, out_features, device=device, dtype=dtype)
            )
        optim_load = torch.optim.SGD(model_load.parameters(), lr=0.25)
        state_dict = torch.load(io.BytesIO(checkpoint_bytes), weights_only=False)
        model_load.load_state_dict(state_dict["model"])
        optim_load.load_state_dict(state_dict["optim"])

        # Training steps with loaded model
        ys_load = []
        for i in range(post_checkpoint_steps):
            optim_load.zero_grad()
3047
            with te.autocast(enabled=quantized_compute, recipe=recipe):
3048
3049
3050
3051
3052
3053
3054
3055
                y = model_load(xs_load[i])
            y.backward(dys[i])
            optim_load.step()
            ys_load.append(y)

        # Check that original and loaded model match exactly
        tols = {"rtol": 0, "atol": 0}
        for param_load, param_save in zip(model_load.parameters(), model_save.parameters()):
3056
3057
3058
3059
3060
            torch.testing.assert_close(  # Force dequantization by casting to FP64
                param_load.to(dtype=torch.float64, device="cpu"),
                param_save.to(dtype=torch.float64, device="cpu"),
                **tols,
            )
3061
3062
3063
3064
3065
            torch.testing.assert_close(param_load.grad, param_save.grad, **tols)
        for y_load, y_save in zip(ys_load, ys_save):
            torch.testing.assert_close(y_load, y_save, **tols)
        for x_load, x_save in zip(xs_load, xs_save):
            torch.testing.assert_close(x_load.grad, x_save.grad, **tols)
3066
3067
3068
3069
3070
3071
3072


class TestSequentialModules:
    """Test for larger Sequentials with modules commonly used together"""

    @staticmethod
    def setup_class(cls) -> None:
3073
        reset_rng_states()
3074

Jan Bielak's avatar
Jan Bielak committed
3075
    @pytest.mark.parametrize("requires_grad", (False, True))
3076
3077
3078
3079
3080
3081
3082
3083
    @pytest.mark.parametrize("bias", (False, True))
    @pytest.mark.parametrize("quantized_compute", (False, True))
    @pytest.mark.parametrize("quantized_weight", (False, True))
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("quantization", _quantization_list)
    def test_layernorm_mlp(
        self,
        *,
Jan Bielak's avatar
Jan Bielak committed
3084
        requires_grad: bool,
3085
3086
3087
3088
3089
3090
        bias: bool,
        quantized_compute: bool,
        quantized_weight: bool,
        dtype: torch.dtype,
        quantization: Optional[str],
        device: torch.device = "cuda",
3091
3092
        hidden_size: int = 256,
        sequence_length: int = 48,
3093
        batch_size: int = 4,
3094
        ffn_hidden_size: int = 384,
3095
3096
        layernorm_epsilon: float = 1e-5,
    ) -> None:
3097
        """LayerNorm/RMSNorm + Linear + SwiGLU + Linear"""
3098
3099
3100
3101
3102
3103

        # Make input shape
        in_shape = (sequence_length, batch_size, hidden_size)
        ffn_shape = in_shape[:-1] + (ffn_hidden_size,)

        # Skip invalid configurations
3104
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
3105
3106
3107
3108
3109
3110
3111
3112
        maybe_skip_quantization(quantization, dims=ffn_shape, device=device)
        quantization_needed = quantized_compute or quantized_weight
        if quantization is None and quantization_needed:
            pytest.skip("Quantization scheme is not specified")
        if quantization is not None and not quantization_needed:
            pytest.skip("Quantization scheme is not used")

        # Random data
3113
        x_ref, x_test = make_reference_and_test_tensors(
3114
3115
3116
3117
            in_shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
Jan Bielak's avatar
Jan Bielak committed
3118
            requires_grad=requires_grad,
3119
        )
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
        norm_w_ref, norm_w_test = make_reference_and_test_tensors(
            hidden_size,
            test_dtype=dtype,
            test_device=device,
        )
        norm_b_ref, norm_b_test = make_reference_and_test_tensors(
            hidden_size,
            test_dtype=dtype,
            test_device=device,
        )
        w1_ref, w1_test = make_reference_and_test_tensors(
            (ffn_hidden_size, hidden_size),
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
        )
        w2_ref, w2_test = make_reference_and_test_tensors(
            (hidden_size, ffn_hidden_size // 2),
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
        )
        b1_ref, b1_test, b2_ref, b2_test = None, None, None, None
        if bias:
            b1_ref, b1_test = make_reference_and_test_tensors(
                ffn_hidden_size,
                test_dtype=dtype,
                test_device=device,
            )
            b2_ref, b2_test = make_reference_and_test_tensors(
                hidden_size,
                test_dtype=dtype,
                test_device=device,
            )
        dy_ref, dy_test = make_reference_and_test_tensors(
3155
3156
3157
3158
3159
3160
            in_shape,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
        with torch.no_grad():
            for t in (norm_w_ref, norm_w_test, norm_b_ref, norm_b_test):
                t -= 0.5
            for t in (w1_ref, w1_test, w2_ref, w2_test):
                t *= 1 / 64
            if bias:
                for t in (b1_ref, b1_test, b2_ref, b2_test):
                    t -= 0.5
            for t in (dy_ref, dy_test):
                t -= 0.5

        # Reference implementation
        x = x_ref
        x = torch.nn.functional.layer_norm(
            x,
            (hidden_size,),
            weight=norm_w_ref,
            bias=norm_b_ref,
            eps=layernorm_epsilon,
        )
        x = torch.nn.functional.linear(x, w1_ref, bias=b1_ref)
        x1, x2 = x.chunk(2, dim=-1)
        x = torch.nn.functional.silu(x1) * x2
        x = torch.nn.functional.linear(x, w2_ref, bias=b2_ref)
        y_ref = x
        y_ref.backward(dy_ref)
3187

3188
        # Construct operations
3189
        recipe = make_recipe(quantization)
3190
        with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
3191
3192
3193
3194
3195
3196
            norm = te_ops.LayerNorm(
                hidden_size,
                eps=layernorm_epsilon,
                device=device,
                dtype=dtype,
            )
3197
3198
3199
3200
3201
3202
3203
            ffn1 = te_ops.Linear(
                hidden_size,
                ffn_hidden_size,
                bias=bias,
                device=device,
                dtype=dtype,
            )
3204
            act = te_ops.SwiGLU()
3205
            ffn2 = te_ops.Linear(
3206
                ffn_hidden_size // 2,
3207
3208
3209
3210
3211
                hidden_size,
                bias=bias,
                device=device,
                dtype=dtype,
            )
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224

        # Copy weights
        with torch.no_grad():
            norm.weight.copy_(norm_w_test)
            norm.bias.copy_(norm_b_test)
            ffn1.weight.copy_(w1_test)
            ffn2.weight.copy_(w2_test)
            if bias:
                ffn1.bias.copy_(b1_test)
                ffn2.bias.copy_(b2_test)
        del norm_w_test, norm_b_test, w1_test, b1_test, w2_test, b2_test

        # Fuse ops and perform forward and backward pass
3225
        forward = te_ops.Sequential(norm, ffn1, act, ffn2)
3226
        with te.autocast(enabled=quantized_compute, recipe=recipe):
3227
3228
            y_test = forward(x_test)
        y_test.backward(dy_test)
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248

        def to_cpu(tensor: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
            """Convert to FP64 CPU tensor"""
            if tensor is None:
                return None
            out = tensor.detach().to(dtype=torch.float64, device="cpu")
            out = out.requires_grad_(requires_grad=tensor.requires_grad)
            return out

        # Check values
        tols = {"rtol": 0.25, "atol": 0.5}  # Loose tols for sanity checking
        torch.testing.assert_close(to_cpu(y_test), y_ref, **tols)
        torch.testing.assert_close(to_cpu(x_test.grad), x_ref.grad, **tols)
        torch.testing.assert_close(to_cpu(norm.weight.grad), norm_w_ref.grad, **tols)
        torch.testing.assert_close(to_cpu(norm.bias.grad), norm_b_ref.grad, **tols)
        torch.testing.assert_close(to_cpu(ffn2.weight.grad), w2_ref.grad, **tols)
        torch.testing.assert_close(to_cpu(ffn1.weight.grad), w1_ref.grad, **tols)
        if bias:
            torch.testing.assert_close(to_cpu(ffn1.bias.grad), b1_ref.grad, **tols)
            torch.testing.assert_close(to_cpu(ffn2.bias.grad), b2_ref.grad, **tols)
3249

3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
    @pytest.mark.parametrize("bias", (False, True))
    @pytest.mark.parametrize("dtype", _dtypes)
    @pytest.mark.parametrize("quantization", _quantization_list)
    @pytest.mark.parametrize("glu_interleave_size", (None, 32))
    def test_grouped_mlp(
        self,
        *,
        group_size: int = 4,
        bias: bool,
        hidden_size: int = 256,
        dtype: torch.dtype,
        quantization: Optional[str],
        device: torch.device = "cuda",
        split_alignment: int = 256,
        glu_interleave_size: Optional[int],
    ) -> None:
        """GroupedLinear + ScaledSwiGLU + GroupedLinear"""

        # Split sizes
        split_sizes = [split_alignment * i for i in range(group_size)]
        random.shuffle(split_sizes)
        split_sizes = torch.tensor(split_sizes, dtype=torch.int, device=device)

        # Make input shape
        in_shape = (split_sizes.sum().item(), hidden_size)
        out_shape = in_shape

        # Skip invalid configurations
        with_quantization = quantization is not None
        maybe_skip_quantization(quantization, dims=in_shape, device=device, dtype=dtype)
        if with_quantization and dtype not in (torch.bfloat16, torch.float16):
            pytest.skip("Quantized group GEMM is only supported with BF16/FP16")

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            in_shape,
            min=-0.25,
            max=0.25,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            out_shape,
            min=-0.25,
            max=0.25,
            quantization=quantization,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )
        probs_ref, probs_test = make_reference_and_test_tensors(
            (in_shape[0],),
            test_dtype=dtype,
            test_device=device,
        )
        fc1_ws_ref, fc1_ws_test = [], []
        fc1_bs_ref, fc1_bs_test = [], []
        fc2_ws_ref, fc2_ws_test = [], []
        fc2_bs_ref, fc2_bs_test = [], []
        for _ in range(group_size):
            fc1_w_ref, fc1_w_test = make_reference_and_test_tensors(
                (2 * hidden_size, hidden_size),
                min=-0.25,
                max=0.25,
                quantization=quantization,
                test_dtype=dtype,
                test_device=device,
            )
            fc2_w_ref, fc2_w_test = make_reference_and_test_tensors(
                (hidden_size, hidden_size),
                min=-0.25,
                max=0.25,
                quantization=quantization,
                test_dtype=dtype,
                test_device=device,
            )
            fc1_b_ref, fc1_b_test = None, None
            fc2_b_ref, fc2_b_test = None, None
            if bias:
                fc1_b_ref, fc1_b_test = make_reference_and_test_tensors(
                    (2 * hidden_size,),
                    min=-0.5,
                    max=0.5,
                    test_dtype=dtype,
                    test_device=device,
                )
                fc2_b_ref, fc2_b_test = make_reference_and_test_tensors(
                    (hidden_size,),
                    min=-0.5,
                    max=0.5,
                    test_dtype=dtype,
                    test_device=device,
                )
            fc1_ws_ref.append(fc1_w_ref)
            fc1_bs_ref.append(fc1_b_ref)
            fc1_ws_test.append(fc1_w_test)
            fc1_bs_test.append(fc1_b_test)
            fc2_ws_ref.append(fc2_w_ref)
            fc2_bs_ref.append(fc2_b_ref)
            fc2_ws_test.append(fc2_w_test)
            fc2_bs_test.append(fc2_b_test)

        # Reference implementation
        xs = torch.split(x_ref, split_sizes.tolist())
        probs = torch.split(probs_ref, split_sizes.tolist())
        ys = []
        for group_idx in range(group_size):
            x = xs[group_idx]
            x = torch.nn.functional.linear(x, fc1_ws_ref[group_idx], bias=fc1_bs_ref[group_idx])
            if glu_interleave_size is not None:
                x = x.reshape(
                    -1,
                    2 * hidden_size // (2 * glu_interleave_size),
                    2,
                    glu_interleave_size,
                )
                x = x.transpose(1, 2)
                x = x.reshape(-1, 2 * hidden_size)
            x1, x2 = x.chunk(2, dim=-1)
            x = torch.nn.functional.silu(x1) * x2
            x = x * probs[group_idx].unsqueeze(-1)
            x = torch.nn.functional.linear(x, fc2_ws_ref[group_idx], bias=fc2_bs_ref[group_idx])
            ys.append(x)
        y_ref = torch.cat(ys)
        y_ref.backward(dy_ref)

        # Construct operations
        recipe = make_recipe(quantization)
        with te.quantized_model_init(enabled=with_quantization, recipe=recipe):
            fc1 = te_ops.GroupedLinear(
                group_size,
                hidden_size,
                2 * hidden_size,
                bias=bias,
                device=device,
                dtype=dtype,
            )
            fc2 = te_ops.GroupedLinear(
                group_size,
                hidden_size,
                hidden_size,
                bias=bias,
                device=device,
                dtype=dtype,
            )
            module = te_ops.Sequential(
                fc1,
                te_ops.ScaledSwiGLU(glu_interleave_size=glu_interleave_size),
                fc2,
            )

        # Copy weights
        with torch.no_grad():
            for group_idx in range(group_size):
                getattr(fc1, f"weight{group_idx}").copy_(fc1_ws_test[group_idx])
                getattr(fc2, f"weight{group_idx}").copy_(fc2_ws_test[group_idx])
                if bias:
                    getattr(fc1, f"bias{group_idx}").copy_(fc1_bs_test[group_idx])
                    getattr(fc2, f"bias{group_idx}").copy_(fc2_bs_test[group_idx])
        del fc1_ws_test, fc1_bs_test, fc2_ws_test, fc2_bs_test

        # Fuse ops and perform forward and backward pass
        with te.autocast(enabled=with_quantization, recipe=recipe):
            y_test = module(x_test, split_sizes, probs_test, split_sizes)
        y_test.backward(dy_test)

        # Loose tols for sanity checking
        tols = {"rtol": 0.125, "atol": 0.25}
        if quantization == "nvfp4":
            tols = {"rtol": 0.25, "atol": 0.5}

        # Check values
        assert_close(y_test, y_ref, **tols)
        assert_close_grads(x_test, x_ref, **tols)
        assert_close_grads(probs_test, probs_ref, **tols)
        for group_idx in range(group_size):
            assert_close_grads(getattr(fc2, f"weight{group_idx}"), fc2_ws_ref[group_idx], **tols)
            assert_close_grads(getattr(fc2, f"bias{group_idx}"), fc2_bs_ref[group_idx], **tols)
            assert_close_grads(getattr(fc1, f"weight{group_idx}"), fc1_ws_ref[group_idx], **tols)
            assert_close_grads(getattr(fc1, f"bias{group_idx}"), fc1_bs_ref[group_idx], **tols)

3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744

class TestCustomOps:
    """Test with ops that are defined externally"""

    def test_custom_basic_op(
        self,
        *,
        shape: Iterable[int] = (7, 5),
        dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
    ) -> None:
        """Custom basic op"""

        class CustomScaleOp(te.ops.BasicOperation):
            """Custom op that applies a learnable scale"""

            def __init__(self) -> None:
                super().__init__()
                self.scale: torch.nn.Parameter
                scale = torch.ones((), dtype=dtype, device=device)
                scale = torch.nn.Parameter(scale)
                self.register_parameter("scale", scale)

            def op_forward(
                self,
                ctx: OperationContext,
                input_: torch.Tensor,
                prev_op_grad_output_quantizer: Optional[Quantizer],
                next_op_input_quantizer: Optional[Quantizer],
            ) -> torch.Tensor:
                ctx.save_for_backward(self.scale, input_)
                return self.scale * input_

            def op_backward(
                self,
                ctx: OperationContext,
                grad_output: torch.Tensor,
            ) -> torch.Tensor:
                (
                    scale,
                    input_,
                ) = ctx.saved_tensors
                grad_scale = torch.inner(input_.reshape(-1), grad_output.reshape(-1))
                grad_scale = grad_scale.reshape(())
                grad_input = scale * grad_output
                return grad_input, (grad_scale,)

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (),
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = w_ref * x_ref
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        op = CustomScaleOp()
        forward = te.ops.Sequential(te.ops.Identity(), op, te.ops.Identity())
        with torch.no_grad():
            op.scale.copy_(w_test)
            del w_test
        y_test = forward(x_test)
        y_test.backward(dy_test)

        # Check results
        tols = dtype_tols(dtype)
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = op.scale.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)

    def test_custom_forward_fused_op(
        self,
        *,
        shape: Iterable[int] = (7, 11),
        dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
    ):
        """Custom fused op in forward pass"""

        class CustomForwardLinearSiLU(te.ops.FusedOperation):
            """Custom fused op for GEMM + SiLU"""

            _enabled = True

            def __init__(self, *, linear, silu) -> None:
                super().__init__((linear, silu))

            def fuser_forward(
                self,
                basic_op_ctxs: list[OperationContext],
                input_: torch.Tensor,
                **unused,
            ) -> torch.Tensor:
                weight = self.basic_ops[0].weight
                dtype = weight.dtype
                device = weight.device

                # Perform compute on CPU, because why not?
                x = input_.cpu()
                w = weight.cpu()
                y = torch.matmul(x, w.T)
                z = torch.nn.functional.silu(y)
                out = z.to(device=device)

                # Save state for linear backward
                linear_op_ctx = basic_op_ctxs[0]
                linear_op_ctx.save_for_backward(input_, weight)
                linear_op_ctx.with_quantized_compute = False
                linear_op_ctx.input_quantizer = None
                linear_op_ctx.weight_quantizer = None
                linear_op_ctx.grad_output_quantizer = None
                linear_op_ctx.grad_input_quantizer = None
                linear_op_ctx.dtype = dtype
                linear_op_ctx.input_requires_grad = True
                linear_op_ctx.weight_requires_grad = True

                # Save state for SiLU backward
                silu_op_ctx = basic_op_ctxs[1]
                silu_op_ctx.save_for_backward(y.to(device=device))
                silu_op_ctx.dtype = dtype
                silu_op_ctx.prev_op_grad_output_quantizer = None

                return out, [(), ()]

            @staticmethod
            def fuse_ops(
                ops: list[FusibleOperation],
                **unused,
            ) -> list[FusibleOperation]:
                """Apply fusion the first time this function is called"""
                if CustomForwardLinearSiLU._enabled:
                    CustomForwardLinearSiLU._enabled = False
                    op = CustomForwardLinearSiLU(linear=ops[0], silu=ops[1])
                    return [op] + ops[2:]
                return ops

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (shape[-1], shape[-1]),
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.linear(x_ref, w_ref)
        y_ref = torch.nn.functional.silu(y_ref)
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        te.ops.register_forward_fusion(CustomForwardLinearSiLU.fuse_ops)
        model = te.ops.Sequential(
            te.ops.Linear(shape[-1], shape[-1], bias=False),
            te.ops.SiLU(),
        )
        with torch.no_grad():
            model[0].weight.copy_(w_test)
            del w_test
        y_test = model(x_test)
        y_test.backward(dy_test)

        # Check that forward operations have been fused
        forward_ops = model._module_groups[0]._forward_ops
        assert len(forward_ops) == 1
        assert isinstance(forward_ops[0][0], CustomForwardLinearSiLU)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = model[0].weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)

    def test_custom_backward_fused_op(
        self,
        *,
        shape: Iterable[int] = (13, 5),
        dtype: torch.dtype = torch.float32,
        device: torch.device = "cuda",
    ):
        """Custom fused op in backward pass"""

        class CustomBackwardLinearScale(te.ops.FusedOperation):
            """Custom fused op for backward linear + scale"""

            _enabled: bool = True

            def __init__(self, *, scale, linear) -> None:
                super().__init__((scale, linear))

            def fuser_backward(
                self,
                basic_op_ctxs: list[OperationContext],
                grad_output: torch.Tensor,
                **unused,
            ) -> torch.Tensor:

                # Load state from linear forward
                linear_op_ctx = basic_op_ctxs[1]
                x, w = linear_op_ctx.saved_tensors
                dtype = linear_op_ctx.dtype
                device = w.device

                # Perform compute in FP64 and apply scale before dgrad
                # GEMM instead of after
                scale = self.basic_ops[0].scale
                dy = grad_output.double()
                x = x.double()
                w = w.double()
                dx = torch.matmul(dy, scale * w)
                dw = torch.matmul(dy.T, x)
                dx = dx.to(dtype=dtype)
                dw = dw.to(dtype=dtype)

                return dx, [(), (dw,)], [(), ()]

            @staticmethod
            def fuse_ops(
                ops: list[FusibleOperation],
                **unused,
            ) -> list[FusibleOperation]:
                """Apply fusion the first time this function is called"""
                if CustomBackwardLinearScale._enabled:
                    CustomBackwardLinearScale._enabled = False
                    op = CustomBackwardLinearScale(scale=ops[0], linear=ops[1])
                    return [op] + ops[2:]
                return ops

        # Random data
        x_ref, x_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
        )
        w_ref, w_test = make_reference_and_test_tensors(
            (shape[-1], shape[-1]),
            test_dtype=dtype,
            test_device=device,
        )
        dy_ref, dy_test = make_reference_and_test_tensors(
            shape,
            test_dtype=dtype,
            test_device=device,
            requires_grad=False,
        )
        scale = 1.234

        # Plain PyTorch implementation
        y_ref = torch.nn.functional.linear(scale * x_ref, w_ref)
        y_ref.backward(dy_ref)

        # Implementation with fusible operation
        te.ops.register_backward_fusion(CustomBackwardLinearScale.fuse_ops, prepend=True)
        model = te.ops.Sequential(
            te.ops.ConstantScale(scale),
            te.ops.Linear(shape[-1], shape[-1], bias=False),
        )
        with torch.no_grad():
            model[1].weight.copy_(w_test)
            del w_test
        y_test = model(x_test)
        y_test.backward(dy_test)

        # Check that forward operations have been fused
        backward_ops = model._module_groups[0]._backward_ops
        assert len(backward_ops) == 1
        assert isinstance(backward_ops[0][0], CustomBackwardLinearScale)

        # Expected numerical error
        tols = dtype_tols(dtype)
        if dtype == torch.float32:
            tols = dtype_tols(torch.float16)  # TF32 GEMM

        # Check results
        y_test = y_test.to(dtype=torch.float64, device="cpu")
        dx_test = x_test.grad.to(dtype=torch.float64, device="cpu")
        dw_test = model[1].weight.grad.to(dtype=torch.float64, device="cpu")
        torch.testing.assert_close(y_test, y_ref, **tols)
        torch.testing.assert_close(dx_test, x_ref.grad, **tols)
        torch.testing.assert_close(dw_test, w_ref.grad, **tols)