Skip to content

fix(autograd/MatMul4Bit): save the packed weight and quant-state tensors via save_for_backward (#2034) - #2035

Open
Anai-Guo wants to merge 2 commits into
bitsandbytes-foundation:mainfrom
Anai-Guo:fix-bnb-forkbase
Open

Anai-Guo wants to merge 2 commits into
bitsandbytes-foundation:mainfrom
Anai-Guo:fix-bnb-forkbase

Conversation

@Anai-Guo

@Anai-Guo Anai-Guo commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

What

MatMul4Bit.forward keeps the packed 4-bit weight and its QuantState as plain
ctx attributes (ctx.tensors = (None, B), ctx.state = quant_state), and
backward dequantizes from them. This PR saves the weight and the quant-state
tensors dequantize_4bit reads
(absmax, plus offset, state2.absmax and
state2.code for nested quantization) through ctx.save_for_backward, and
rebuilds a QuantState from ctx.saved_tensors in backward. ctx.state is
still kept, but only for its non-tensor metadata (shape, blocksize, quant_type,
dtype).

Fixes #2034.

Why

In the ordinary case the ctx-attribute approach is harmless — the weight is a
stable Parameter, so holding a reference to it is exactly as correct as saving
it, and costs nothing.

It stops being correct for a caller that re-materialises the weight — weight
offloading, layer streaming, anything that writes a layer's bytes into a recycled
device buffer just before use. torch.utils.checkpoint discards and recomputes
saved tensors, so under checkpointing such a caller expects the recompute to
hand backward fresh copies. A plain ctx attribute is invisible to that
mechanism: the reference taken during the original forward survives into
backward and, by then, points at a buffer that has been refilled with a
different layer. The result is silently wrong gradients — the forward stays
bit-exact and the loss curve looks healthy. The quant-state tensors have the same
problem as the weight when a caller streams them too (pointed out by
@pjordanandrsn below).

bf16 through the same buffer-recycling harness is unaffected, because it goes
through MmBackward0, which already uses save_for_backward. This change brings
MatMul4Bit in line with that.

No behavioural change in the ordinary training path (stable Parameter weight and
quant state, nothing mutated between forward and backward).

Testing

New test_matmul_4bit_checkpoint_recycled_buffers in tests/test_autograd.py:
four 4-bit layers, each re-materialised into a two-slot ring of buffers right
before use and run under checkpoint(use_reentrant=False). It compares the input
gradient with the same stack using private buffers, recycling the weight, the
quant-state tensors, or both, with and without compress_statistics.

Max |input grad − reference| on an RTX 4090 (torch 2.5.1+cu121, nf4, reference
max ≈ 1.42):

recycled main weight saved only (first commit) this PR
weight 1.67 0 0
quant state 0.49 0.49 0
both 1.66 0.49 0

(compress_statistics=True gives the same picture.)

  • pytest tests/test_autograd.py -k matmul_4bit with this branch's
    autograd/_functions.py on top of the 0.50.2 wheel (identical MatMul4Bit to
    main): 1132 passed, 416 xfailed, cpu + cuda.
  • The new test fails on main (12/12) and on the first commit alone (8/12).

bitsandbytes-foundation#2034)

MatMul4Bit.forward stored the packed weight as a plain ctx attribute
(ctx.tensors = (None, B)) instead of through save_for_backward. In the
ordinary case this is harmless -- the weight is a stable Parameter. It
breaks for a caller that re-materialises the weight (weight offloading,
layer streaming) into a recycled device buffer under gradient
checkpointing: torch.utils.checkpoint discards and recomputes *saved*
tensors, so the recompute is expected to hand backward a fresh copy of
the weight. A raw ctx attribute is invisible to that mechanism -- the
reference taken in the original forward survives into backward and, by
then, points at a buffer refilled with a different layer, producing
silently wrong gradients (forward stays bit-exact). bf16 through the
same harness is unaffected because MmBackward0 already uses
save_for_backward.

Switch to ctx.save_for_backward(B) in forward and read it back from
ctx.saved_tensors in backward. The QuantState stays on ctx.state since
it is not a tensor. No behavioural change in the ordinary path.
@pjordanandrsn

Copy link
Copy Markdown
Contributor

save_for_backward(B) addresses the packed-weight lifetime issue in #2034.

I hit the same class of lifetime issue in streamed 4-bit training. I wonder whether the same issue also applies to ctx.state = quant_state, since QuantState contains tensor-valued absmax / nested quantization state used by backward.

Worth adding one regression that independently recycles B and the quant-state tensors.

…for_backward

backward dequantizes with ctx.state, so absmax (and for nested quantization
offset, state2.absmax and state2.code) were still read through a plain ctx
attribute and kept pointing at the original forward's buffers under a
checkpoint recompute. Save them with the packed weight and rebuild the
QuantState from ctx.saved_tensors in backward; ctx.state is kept for its
non-tensor metadata only.

Add a regression test that re-materialises the weight, the quant-state
tensors, or both into a two-slot ring under checkpoint(use_reentrant=False)
and compares the input gradient with private buffers.
@Anai-Guo Anai-Guo changed the title fix(autograd/MatMul4Bit): save the packed weight via save_for_backward (#2034) fix(autograd/MatMul4Bit): save the packed weight and quant-state tensors via save_for_backward (#2034) Nov 26, 2026
@Anai-Guo

Copy link
Copy Markdown
Contributor Author

@pjordanandrsn yes, it does. backward dequantizes with ctx.state, so absmax (and offset, state2.absmax, state2.code when nested) came from whatever the original forward's QuantState pointed at. I've pushed a change that saves those tensors through save_for_backward too and rebuilds the QuantState from ctx.saved_tensors, plus the regression you suggested: weight and quant-state tensors recycled independently through a two-slot ring under checkpoint(use_reentrant=False). With only the weight saved, the quant-state arm was still off by 0.49 (reference max 1.42) on a 4090; with both saved every arm matches exactly. Numbers are in the description.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MatMul4Bit keeps B and quant_state on ctx instead of save_for_backward, so gradient checkpointing cannot recompute them

2 participants