Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 47 additions & 5 deletions bitsandbytes/autograd/_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,37 @@ def backward(ctx, grad_output):
return grad_A, grad_B, None, grad_bias, None


def _quant_state_tensors(quant_state: F.QuantState) -> tuple[torch.Tensor, ...]:
"""The tensors of a 4-bit QuantState that dequantize_4bit reads."""
if quant_state.nested:
return (quant_state.absmax, quant_state.offset, quant_state.state2.absmax, quant_state.state2.code)
return (quant_state.absmax,)


def _quant_state_with(quant_state: F.QuantState, tensors: tuple[torch.Tensor, ...]) -> F.QuantState:
"""A copy of quant_state that uses `tensors` (as returned by _quant_state_tensors) instead of its own."""
if quant_state.nested:
absmax, offset, absmax2, code2 = tensors
state2 = F.QuantState(
absmax=absmax2,
code=code2,
blocksize=quant_state.state2.blocksize,
dtype=quant_state.state2.dtype,
)
else:
(absmax,), offset, state2 = tensors, None, None
return F.QuantState(
absmax=absmax,
shape=quant_state.shape,
code=quant_state.code,
blocksize=quant_state.blocksize,
quant_type=quant_state.quant_type,
dtype=quant_state.dtype,
offset=offset,
state2=state2,
)


class MatMul4Bit(torch.autograd.Function):
# forward is the same, but we added the fallback for pre-turing GPUs

Expand Down Expand Up @@ -354,10 +385,19 @@ def forward(ctx, A, B, out=None, bias=None, quant_state: Optional[F.QuantState]
ctx.state = quant_state
ctx.dtype_A, ctx.dtype_B, ctx.dtype_bias = A.dtype, B.dtype, None if bias is None else bias.dtype

# Save the packed weight and the quant-state tensors backward dequantizes with
# (absmax, and for nested quantization offset / state2.absmax / state2.code)
# through save_for_backward rather than as plain ctx attributes.
# torch.utils.checkpoint discards and recomputes *saved* tensors, so a caller
# that re-materialises them (weight offloading, layer streaming) into recycled
# buffers under checkpointing gets fresh copies in backward. A raw ctx attribute
# is invisible to that mechanism and would keep pointing at the original
# buffer -- silently wrong gradients. ctx.state is kept for its non-tensor
# metadata only.
if any(ctx.needs_input_grad[:2]):
ctx.tensors = (None, B)
ctx.save_for_backward(B, *_quant_state_tensors(quant_state))
else:
ctx.tensors = (None, None)
ctx.save_for_backward()

return output

Expand All @@ -368,7 +408,8 @@ def backward(ctx, grad_output):
return torch.zeros_like(ctx.A), torch.zeros_like(ctx.B), None, bias_grad, None

req_gradA, _, _, req_gradBias, _ = ctx.needs_input_grad
_, B = ctx.tensors
saved = ctx.saved_tensors
B = saved[0] if saved else None

grad_A, grad_B, grad_bias = None, None, None

Expand All @@ -379,9 +420,10 @@ def backward(ctx, grad_output):
# not supported by PyTorch. TODO: create work-around
# if req_gradB: grad_B = torch.matmul(grad_output.t(), A)
if req_gradA:
# B in ctx.tensors is already in canonical [(N*K+1)//2, 1] form (normalized in forward).
# B from saved_tensors is already in canonical [(N*K+1)//2, 1] form (normalized in forward).
# dequantize returns [N, K]; matmul(grad_output[M,N], [N,K]) = grad_A[M,K].
grad_A = torch.matmul(grad_output, F.dequantize_4bit(B, ctx.state).to(grad_output.dtype))
state = _quant_state_with(ctx.state, saved[1:])
grad_A = torch.matmul(grad_output, F.dequantize_4bit(B, state).to(grad_output.dtype))

return grad_A, grad_B, None, grad_bias, None

Expand Down
69 changes: 69 additions & 0 deletions tests/test_autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,72 @@ def test_matmul_4bit(

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


@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("compress_statistics", TRUE_FALSE, ids=id_formatter("compress_statistics"))
@pytest.mark.parametrize("recycle", ["weight", "quant_state", "both"])
def test_matmul_4bit_checkpoint_recycled_buffers(device, compress_statistics, recycle):
# A caller that re-materialises each layer's 4-bit weight and quant-state tensors into a few
# reused buffers right before use (weight offloading, layer streaming) relies on
# torch.utils.checkpoint recomputing the saved tensors: the recompute loads the layer into a
# different buffer than the original forward did, so anything backward reads from a plain ctx
# attribute belongs to another layer by then (#2034).
dtype = torch.float32 if device == "cpu" else torch.float16
n_layers, dim, n_buffers = 4, 128, 2
QuantState = bnb.functional.QuantState

torch.manual_seed(0)
layers = [
bnb.functional.quantize_4bit(
torch.randn(dim, dim, device=device, dtype=dtype) / dim**0.5,
compress_statistics=compress_statistics,
quant_type="nf4",
)
for _ in range(n_layers)
]
x0 = torch.randn(8, dim, device=device, dtype=dtype)

def input_grad(recycle_weight, recycle_state):
buffers, calls = {}, {}

def load(name, t, recycled):
if not recycled:
return t
ring = buffers.setdefault(name, [torch.empty_like(t) for _ in range(n_buffers)])
calls[name] = calls.get(name, -1) + 1
return ring[calls[name] % n_buffers].copy_(t)

def layer(h, i):
B, qs = layers[i]
state2 = None
if qs.nested:
state2 = QuantState(
absmax=load("absmax2", qs.state2.absmax, recycle_state),
code=qs.state2.code,
blocksize=qs.state2.blocksize,
dtype=qs.state2.dtype,
)
qs = QuantState(
absmax=load("absmax", qs.absmax, recycle_state),
shape=qs.shape,
code=qs.code,
blocksize=qs.blocksize,
quant_type=qs.quant_type,
dtype=qs.dtype,
offset=load("offset", qs.offset, recycle_state) if qs.nested else None,
state2=state2,
)
return torch.relu(bnb.matmul_4bit(h, load("B", B, recycle_weight), quant_state=qs))

x = x0.clone().requires_grad_(True)
h = x
for i in range(n_layers):
h = torch.utils.checkpoint.checkpoint(layer, h, i, use_reentrant=False)
h.float().pow(2).sum().backward()
return x.grad

expected = input_grad(False, False)
actual = input_grad(recycle in ("weight", "both"), recycle in ("quant_state", "both"))
assert expected.abs().max() > 0
torch.testing.assert_close(actual, expected)