|
| 1 | +import logging |
| 2 | +import unittest |
| 3 | + |
| 4 | +import torch |
| 5 | +from torch import nn |
| 6 | +from torch.testing._internal.common_utils import TestCase |
| 7 | +from torchao.modules import FrozenNF4Linear |
| 8 | +from torchao.dtypes.nf4tensor import NF4Tensor |
| 9 | + |
| 10 | +bnb_available = False |
| 11 | + |
| 12 | +try: |
| 13 | + import bitsandbytes as bnb |
| 14 | + bnb_available = True |
| 15 | +except ImportError: |
| 16 | + pass |
| 17 | + |
| 18 | +logging.basicConfig( |
| 19 | + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO |
| 20 | +) |
| 21 | + |
| 22 | +class TestNF4Linear(TestCase): |
| 23 | + """ |
| 24 | + Test torchao.modules.NF4Linear |
| 25 | + """ |
| 26 | + def test_bias_unsupported(self): |
| 27 | + with self.assertRaisesRegex(RuntimeError, "does not currently support biases"): |
| 28 | + _ = FrozenNF4Linear(1, 1, bias=True) |
| 29 | + |
| 30 | + def test_non_bf16_unsupported(self): |
| 31 | + with self.assertRaisesRegex(RuntimeError, "only supported with bf16"): |
| 32 | + _ = FrozenNF4Linear(1, 1) |
| 33 | + |
| 34 | + def test_frozen_nf4_linear(self): |
| 35 | + nf4_linear = FrozenNF4Linear(512, 512, device='cpu', dtype=torch.bfloat16) |
| 36 | + self.assertTrue(isinstance(nf4_linear.weight, NF4Tensor)) |
| 37 | + self.assertEqual(torch.bfloat16, nf4_linear.weight.get_original_weight().dtype) |
| 38 | + |
| 39 | + def test_output_bf16(self): |
| 40 | + # Test to ensure W4 A16 produces A16 |
| 41 | + nf4_linear = FrozenNF4Linear(512, 512, device='cpu', dtype=torch.bfloat16) |
| 42 | + inp = torch.randn(2, 512, dtype=torch.bfloat16, requires_grad=True) |
| 43 | + out = nf4_linear(inp) |
| 44 | + assert out.dtype == torch.bfloat16 |
| 45 | + |
| 46 | + def test_backward_bf16(self): |
| 47 | + # Test to ensure backward pass gives activation a bf16 gradient and no gradient |
| 48 | + # to the linear's weight, as it is frozen. |
| 49 | + nf4_linear = FrozenNF4Linear(512, 512, device='cpu', dtype=torch.bfloat16) |
| 50 | + inp = torch.randn(2, 512, dtype=torch.bfloat16, requires_grad=True) |
| 51 | + nf4_linear(inp).sum().backward() |
| 52 | + assert inp.grad is not None and inp.grad.dtype == torch.bfloat16 |
| 53 | + assert nf4_linear.weight.grad is None |
| 54 | + |
| 55 | + |
| 56 | + def _build_bnb_linear(self, input_weight): |
| 57 | + assert bnb_available, "Needs bitsandbytes support" |
| 58 | + param = bnb.nn.Params4bit(input_weight, requires_grad=False, quant_type="nf4") |
| 59 | + bnb_linear = bnb.nn.LinearNF4(input_weight.size(0), input_weight.size(1), bias=False) |
| 60 | + bnb_linear.weight = param |
| 61 | + bnb_linear.cuda() |
| 62 | + return bnb_linear |
| 63 | + |
| 64 | + @unittest.skipIf(not bnb_available, "Need bnb availble") |
| 65 | + @unittest.skipIf(not torch.cuda.is_available(), "Need CUDA available") |
| 66 | + def test_fwd_bnb_parity(self): |
| 67 | + """ |
| 68 | + Ensures fwd + backward logits and grads are at parity w/bnb |
| 69 | + """ |
| 70 | + nf4_linear = FrozenNF4Linear(512, 512, device='cuda', dtype=torch.bfloat16) |
| 71 | + orig_weight = nf4_linear.weight.get_original_weight().clone().detach() |
| 72 | + bnb_nf4_linear = self._build_bnb_linear(input_weight=orig_weight) |
| 73 | + |
| 74 | + inp = torch.randn(2, 512, dtype=torch.bfloat16, device='cuda', requires_grad=True) |
| 75 | + with torch.no_grad(): |
| 76 | + inp_bnb = inp.clone() |
| 77 | + inp_bnb.requires_grad_(True) |
| 78 | + out_native = nf4_linear(inp).sum() |
| 79 | + out_bnb = bnb_nf4_linear(inp_bnb).sum() |
| 80 | + self.assertEqual(out_native, out_bnb) |
| 81 | + |
| 82 | + |
| 83 | + @unittest.skipIf(not bnb_available, "Need bnb availble") |
| 84 | + @unittest.skipIf(not torch.cuda.is_available(), "Need CUDA available") |
| 85 | + def test_nf4_reconstruction_vs_bnb(self): |
| 86 | + """ |
| 87 | + Ensures a BNB NF4 linear and our FrozenNF4Linear have low error when |
| 88 | + reconstructing the respective original weights. |
| 89 | + """ |
| 90 | + dim = 512 |
| 91 | + nf4_linear = FrozenNF4Linear(dim, dim, device='cuda', dtype=torch.bfloat16) |
| 92 | + orig_weight = nf4_linear.weight.get_original_weight().clone().detach() |
| 93 | + bnb_nf4_linear = self._build_bnb_linear(input_weight=orig_weight) |
| 94 | + |
| 95 | + # From https://github.com/drisspg/transformer_nuggets/blob/f05afad68ad9086d342268f46a7f344617a02314/test/test_qlora.py#L65 |
| 96 | + bnb_reconstruction = bnb_nf4_linear( |
| 97 | + torch.eye(dim, dim, dtype=torch.bfloat16, device='cuda') |
| 98 | + ) |
| 99 | + # Ensure nf4_linear and bnb reconstructions are close to each other. |
| 100 | + diff = (bnb_reconstruction.T - nf4_linear.weight.get_original_weight()).abs().max() |
| 101 | + assert diff.item() < 1e-2 |
| 102 | + |
| 103 | + @unittest.skipIf(not bnb_available, "Need bnb availble") |
| 104 | + @unittest.skipIf(not torch.cuda.is_available(), "Need CUDA available") |
| 105 | + def test_nf4_bnb_linear(self): |
| 106 | + """ |
| 107 | + This test ensures that nf4_linear is "no worse" than BNB by ensuring the |
| 108 | + error compared to a bf16 linear is not more than BNB's implementation. |
| 109 | + """ |
| 110 | + dim = 512 |
| 111 | + nf4_linear = FrozenNF4Linear(dim, dim, device='cuda', dtype=torch.bfloat16) |
| 112 | + orig_weight = nf4_linear.weight.get_original_weight().clone().detach() |
| 113 | + bnb_nf4_linear = self._build_bnb_linear(input_weight=orig_weight) |
| 114 | + bf16_linear = torch.nn.Linear(dim, dim, device='cuda', dtype=torch.bfloat16) |
| 115 | + |
| 116 | + inp = torch.randn(2, 512, dtype=torch.bfloat16, device='cuda') |
| 117 | + |
| 118 | + out_nf4 = nf4_linear(inp).sum() |
| 119 | + out_bnb = bnb_nf4_linear(inp).sum() |
| 120 | + out_ref = bf16_linear(inp).sum() |
| 121 | + |
| 122 | + err_bnb = (out_bnb - out_ref).abs().max() |
| 123 | + err_native = (out_nf4 - out_ref).abs().max() |
| 124 | + assert err_native.item() <= err_bnb |
| 125 | + |
| 126 | + |
| 127 | + |
| 128 | +if __name__ == "__main__": |
| 129 | + unittest.main() |
0 commit comments