From a3f1cd09093ed33019c5b345d2a5348b0bf2054b Mon Sep 17 00:00:00 2001 From: shotsan Date: Tue, 17 Nov 2026 13:22:55 -0700 Subject: [PATCH] fix(autograd): support 1-D and arbitrary-rank inputs for k-bit linear backward (#2110, #2108) - Compute k-bit linear bias gradient over all leading dimensions via `grad_output.reshape(-1, grad_output.shape[-1]).sum(0)` instead of `sum(0)` alone. For 1-D inputs, `sum(0)` yielded a 0-D scalar which was rejected by autograd; for >2-D inputs, it returned extra leading dimensions (#2110). - Reshape `A` and `grad_output` in `MatMul8bitFp` (CPU/XPU) to 2-D when computing `grad_B`, avoiding `RuntimeError: t() expects a tensor with <= 2 dimensions` on 1-D, 3-D, and 4-D activations (#2108). - Reshape non-2D `grad_output` in `MatMulLt` to 2-D when `grad_output.ndim != 2`. - Add regression unit tests across 1-D, 2-D, 3-D, and 4-D input shapes in `tests/test_linear4bit.py` and `tests/test_linear8bitlt.py`. --- bitsandbytes/autograd/_functions.py | 13 +++++++------ tests/test_linear4bit.py | 11 +++++++++++ tests/test_linear8bitlt.py | 22 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/bitsandbytes/autograd/_functions.py b/bitsandbytes/autograd/_functions.py index 8a069bd10..1332e706c 100644 --- a/bitsandbytes/autograd/_functions.py +++ b/bitsandbytes/autograd/_functions.py @@ -212,10 +212,10 @@ def backward(ctx: torch.autograd.function.FunctionCtx, grad_output: torch.Tensor if req_gradBias: # compute grad_bias first before changing grad_output dtype - grad_bias = grad_output.sum(0, dtype=ctx.dtype_bias) + grad_bias = grad_output.reshape(-1, grad_output.shape[-1]).sum(0, dtype=ctx.dtype_bias) # Cast grad_output to fp16 - if len(grad_output.shape) == 3: + if len(grad_output.shape) != 2: grad_output = grad_output.reshape(-1, grad_output.shape[-1]).contiguous() if req_gradB: @@ -278,14 +278,15 @@ def backward(ctx, grad_output): grad_A = grad_B = grad_bias = None if req_gradBias: # compute grad_bias first before changing grad_output dtype - grad_bias = grad_output.sum(0, dtype=ctx.dtype_bias) + grad_bias = grad_output.reshape(-1, grad_output.shape[-1]).sum(0, dtype=ctx.dtype_bias) # Cast grad_output to fp16 - if len(grad_output.shape) == 3: + if len(grad_output.shape) != 2: grad_output = grad_output.reshape(-1, grad_output.shape[-1]).contiguous() if req_gradB: - grad_B = torch.matmul(A.t(), grad_output).t() + A_2d = A.reshape(-1, A.shape[-1]) + grad_B = torch.matmul(A_2d.t(), grad_output).t() if req_gradA: if state.CB is not None: @@ -374,7 +375,7 @@ def backward(ctx, grad_output): if req_gradBias: # compute grad_bias first before changing grad_output dtype - grad_bias = grad_output.sum(0, dtype=ctx.dtype_bias) + grad_bias = grad_output.reshape(-1, grad_output.shape[-1]).sum(0, dtype=ctx.dtype_bias) # not supported by PyTorch. TODO: create work-around # if req_gradB: grad_B = torch.matmul(grad_output.t(), A) diff --git a/tests/test_linear4bit.py b/tests/test_linear4bit.py index 79ede45b2..1b0a53c3f 100644 --- a/tests/test_linear4bit.py +++ b/tests/test_linear4bit.py @@ -612,3 +612,14 @@ def test_fsdp_state_dict_save_4bit(): f"stdout: {result.stdout}\n" f"stderr: {result.stderr}" ) + + +@pytest.mark.parametrize("shape", [(32,), (4, 32), (2, 3, 32), (2, 2, 3, 32)]) +@pytest.mark.parametrize("device", get_available_devices()) +def test_linear4bit_bias_gradient_input_ranks(shape, device): + layer = bnb.nn.LinearNF4(32, 64, bias=True).to(device) + x = torch.randn(shape, device=device, requires_grad=True) + out = layer(x) + out.sum().backward() + assert layer.bias.grad is not None + assert layer.bias.grad.shape == (64,) diff --git a/tests/test_linear8bitlt.py b/tests/test_linear8bitlt.py index b078e82b7..3135f87b6 100644 --- a/tests/test_linear8bitlt.py +++ b/tests/test_linear8bitlt.py @@ -364,3 +364,25 @@ def test_linear8bitlt_device_movement(device): # Accelerator outputs should match both times. torch.testing.assert_close(out_accelerator_2, out_accelerator, rtol=1e-8, atol=1e-8) + + +@pytest.mark.parametrize("shape", [(32,), (4, 32), (2, 3, 32), (2, 2, 3, 32)]) +@pytest.mark.parametrize("device", get_available_devices()) +def test_linear8bitlt_bias_gradient_input_ranks(shape, device): + layer = bnb.nn.Linear8bitLt(32, 64, bias=True, has_fp16_weights=False).to(device) + x = torch.randn(shape, device=device, requires_grad=True) + out = layer(x) + out.sum().backward() + assert layer.bias.grad is not None + assert layer.bias.grad.shape == (64,) + + +@pytest.mark.parametrize("shape", [(32,), (2, 3, 32), (2, 2, 2, 32)]) +@pytest.mark.parametrize("device", get_available_devices()) +def test_linear8bitlt_fp16_weights_backward_non_2d_ranks(shape, device): + layer = bnb.nn.Linear8bitLt(32, 64, bias=False, has_fp16_weights=True).to(device) + x = torch.randn(shape, device=device, requires_grad=True) + out = layer(x) + out.sum().backward() + assert layer.weight.grad is not None + assert layer.weight.grad.shape == (64, 32)