|
| 1 | +import os |
| 2 | +from contextlib import nullcontext |
| 3 | +from itertools import product |
| 4 | +from tempfile import TemporaryDirectory |
| 5 | + |
| 6 | +import pytest |
| 7 | +import torch |
| 8 | + |
| 9 | +import bitsandbytes as bnb |
| 10 | +from bitsandbytes import functional as F |
| 11 | +from bitsandbytes.nn.modules import Linear4bit |
| 12 | + |
| 13 | + |
| 14 | +@pytest.mark.skipif(not torch.cuda.is_available(), reason="this test requires a GPU") |
| 15 | +@pytest.mark.parametrize( |
| 16 | + "quant_type, compress_statistics, bias", |
| 17 | + list(product(["nf4", "fp4"], [False, True], [False, True])), |
| 18 | +) |
| 19 | +def test_linear4_state_dict(quant_type, compress_statistics, bias): |
| 20 | + original_dtype = torch.float16 |
| 21 | + compute_dtype = None |
| 22 | + device = "cuda" |
| 23 | + layer_shape = (300, 400) |
| 24 | + |
| 25 | + linear = torch.nn.Linear(*layer_shape, dtype=original_dtype) # original layer |
| 26 | + |
| 27 | + # Quantizing original layer |
| 28 | + linear_q = bnb.nn.Linear4bit( |
| 29 | + linear.in_features, |
| 30 | + linear.out_features, |
| 31 | + bias=bias, |
| 32 | + compute_dtype=compute_dtype, |
| 33 | + compress_statistics=compress_statistics, |
| 34 | + quant_type=quant_type, |
| 35 | + device=device, |
| 36 | + ) |
| 37 | + new_weight = bnb.nn.Params4bit(data=linear.weight, requires_grad=False) |
| 38 | + linear_q.weight = new_weight.to(device) |
| 39 | + if bias: |
| 40 | + linear_q.bias.data = linear.bias.data.to(device) |
| 41 | + |
| 42 | + sd = linear_q.state_dict() |
| 43 | + |
| 44 | + # restoring from state_dict: |
| 45 | + |
| 46 | + sd = linear_q.state_dict() |
| 47 | + bias_data2 = sd.pop("bias", None) |
| 48 | + weight_data2 = sd.pop("weight") |
| 49 | + |
| 50 | + weight2 = bnb.nn.Params4bit.from_prequantized(quantized_stats=sd, data=weight_data2) |
| 51 | + |
| 52 | + linear_q2 = bnb.nn.Linear4bit( |
| 53 | + linear.in_features, |
| 54 | + linear.out_features, |
| 55 | + bias=bias, |
| 56 | + compute_dtype=compute_dtype, |
| 57 | + compress_statistics=compress_statistics, |
| 58 | + quant_type=quant_type, |
| 59 | + device=device, |
| 60 | + ) |
| 61 | + linear_q2.weight = weight2.to(device) |
| 62 | + if bias: |
| 63 | + linear_q2.bias.data = bias_data2 |
| 64 | + |
| 65 | + # matching |
| 66 | + a, b = linear_q.weight, linear_q2.weight |
| 67 | + |
| 68 | + assert a.device == b.device |
| 69 | + assert a.dtype == b.dtype |
| 70 | + assert torch.equal(a, b) |
| 71 | + |
| 72 | + q0 = a.quant_state |
| 73 | + q1 = b.quant_state |
| 74 | + for attr in ('code', 'dtype', 'blocksize', 'absmax'): |
| 75 | + c, d = getattr(q0, attr), getattr(q1, attr) |
| 76 | + if isinstance(c, torch.Tensor): |
| 77 | + assert torch.equal(c, d) |
| 78 | + else: |
| 79 | + assert c == d, f"{c} != {d}" |
| 80 | + |
| 81 | + if q0.state2 is not None: |
| 82 | + for attr in ('code', 'dtype', 'blocksize', 'absmax'): |
| 83 | + c, d = getattr(q0.state2, attr), getattr(q1.state2, attr) |
| 84 | + if isinstance(c, torch.Tensor): |
| 85 | + assert torch.equal(c, d) |
| 86 | + else: |
| 87 | + assert c == d, f"{c} != {d}" |
| 88 | + |
| 89 | + if bias: |
| 90 | + a, b = linear_q.bias, linear_q2.bias |
| 91 | + assert a.device == b.device |
| 92 | + assert a.dtype == b.dtype |
| 93 | + assert torch.equal(a, b) |
| 94 | + |
| 95 | + # Forward test |
| 96 | + x = torch.rand(42, linear_q.shape[-1], device=device) |
| 97 | + a = linear_q(x) |
| 98 | + b = linear_q2(x) |
| 99 | + assert a.device == b.device |
| 100 | + assert a.dtype == b.dtype |
| 101 | + assert torch.equal(a, b) |
| 102 | + |
| 103 | + # Saved size ratio test. Target set for layer_shape == (300, 400) w/ bias |
| 104 | + with TemporaryDirectory() as tmpdir: |
| 105 | + state_path_4bit = os.path.join(tmpdir, "state_4bit.pth") |
| 106 | + state_path = os.path.join(tmpdir, "state.pth") |
| 107 | + torch.save(linear.state_dict(), state_path) |
| 108 | + torch.save(linear_q.state_dict(), state_path_4bit) |
| 109 | + |
| 110 | + size_orig, size_4 = os.path.getsize(state_path), os.path.getsize( |
| 111 | + state_path_4bit |
| 112 | + ) |
| 113 | + size_ratio = size_4 / size_orig |
| 114 | + target_compression = 0.143 if original_dtype == torch.float32 else 0.285 |
| 115 | + ratio_error_msg = f"quantized_size {size_4:,} is larger on disk than {target_compression:.2%} of original size {size_orig:,}" |
| 116 | + assert size_ratio < target_compression, ratio_error_msg |
0 commit comments