Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

feat(stream): make NF4 fused forward checkpoint-visible (#842) (#1143)

AmixDigital33639fb4f6be
diff --git a/changelog.d/0.75.1/1143.changed.md b/changelog.d/0.75.1/1143.changed.md
new file mode 100644
index 00000000..28e02cfb
--- /dev/null
+++ b/changelog.d/0.75.1/1143.changed.md
@@ -0,0 +1,3 @@
+- **Streamed CUDA NF4 now follows bitsandbytes' own fused-versus-dequantized dispatch,
+ so it runs the same kernels as resident NF4 (#842 by @Amix29 in #1143).** Pooled
+ weight aliases stay checkpoint-visible and backward verifies stream-slot ownership.
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 9f7aca71..522a0e69 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -425,6 +425,15 @@ soup train --config soup.yaml
**How it works.** LoRA adapters + their gradients + optimizer state stay resident in VRAM (they are small). The frozen base lives in CPU RAM, page-locked when the machine allows it, and is streamed: each decoder layer is copied into one of two pre-allocated VRAM buffers on a dedicated CUDA stream while the previous layer is still computing, so the load overlaps the compute. Vocabulary-sized `embed_tokens` and an untied `lm_head` use one additional shared slot: the embedding is loaded for the model input, then the same allocation is reused for the output head, whose copy is issued right after the embedding lookup (`StreamPrefetcher.head_prefetch_layer`, default `0`) rather than at the last decoder layer, and the embedding is reloaded into it at the tail of that step's backward pass so the copy overlaps the remaining compute instead of blocking the next step's first lookup. Each decoder layer is read **twice** per step — once in the forward pass and once when the backward pass recomputes it — because `dL/dx = Wᵀ · dL/dy` needs the weights to reach the layers below. That is physics, not an implementation detail, and it is why streaming costs time.
+For streamed NF4 on CUDA, Soup follows bitsandbytes' own 4-bit dispatch. When
+bitsandbytes selects its custom fused GEMM, Soup executes that GEMM through a
+checkpoint-visible autograd Function so pooled packed weights cannot outlive their
+slot ownership. When bitsandbytes selects dequantisation plus `F.linear` at larger
+training shapes, Soup keeps that path and avoids adding a third dequantisation to a
+checkpointed step. The fused arm reduces saved-weight VRAM but its backward still
+dequantises because bitsandbytes exposes no transposed 4-bit GEMM; it is therefore a
+bounded memory/time trade, not a claim that #842's full kernel ceiling is complete.
+
**Qwen3.8-Flash-Next / Qwen4-Exp PLE.** The frozen PLE N-gram table is not a
decoder-layer weight for storage purposes: putting it in the PLE layer's shard
would make the shared layer buffer as large as the whole table. Soup keeps the
diff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.py
index b1bbc159..03ccb0ac 100644
--- a/src/soup_cli/utils/layer_stream_runtime.py
+++ b/src/soup_cli/utils/layer_stream_runtime.py
@@ -175,6 +175,200 @@ def rebuild_params4bit(key: str, buffers: Mapping[str, Any], spec: Any, codes: M
)
+_CHECKPOINT_VISIBLE_NF4_FUNCTION = None
+
+
+def _checkpoint_visible_nf4_function():
+ """Lazy custom autograd Function whose saved state is visible to checkpoint (#842)."""
+ global _CHECKPOINT_VISIBLE_NF4_FUNCTION
+ if _CHECKPOINT_VISIBLE_NF4_FUNCTION is not None:
+ return _CHECKPOINT_VISIBLE_NF4_FUNCTION
+
+ import bitsandbytes.functional as bnb_functional
+ import torch
+
+ class CheckpointVisibleNF4Matmul(torch.autograd.Function):
+ @staticmethod
+ @torch.amp.custom_fwd(device_type="cuda")
+ def forward(
+ ctx,
+ x,
+ packed,
+ absmax,
+ state2_absmax,
+ state2_code,
+ offset,
+ bias,
+ shape,
+ weight_dtype,
+ blocksize,
+ quant_type,
+ nested,
+ state2_blocksize,
+ ):
+ # #331/#842: every tensor the backward needs goes through
+ # save_for_backward. Non-reentrant checkpoint can therefore discard
+ # these references and recreate them after the streaming slot has
+ # been refilled with the correct layer during recompute.
+ ctx.save_for_backward(packed, absmax, state2_absmax, state2_code, offset)
+ ctx.shape = tuple(int(dim) for dim in shape)
+ ctx.weight_dtype = weight_dtype
+ ctx.blocksize = int(blocksize)
+ ctx.quant_type = str(quant_type)
+ ctx.nested = bool(nested)
+ ctx.state2_blocksize = int(state2_blocksize)
+ ctx.bias_dtype = None if bias is None else bias.dtype
+ ctx.owner_check = getattr(packed, "_soup_stream_owner_check", None)
+
+ if ctx.nested:
+ return torch.ops.bitsandbytes.gemm_4bit.default(
+ x,
+ packed,
+ ctx.shape,
+ state2_absmax,
+ ctx.blocksize,
+ ctx.quant_type,
+ bias=bias,
+ absmax_8bit=absmax,
+ absmax_code=state2_code,
+ absmax_offset=offset,
+ )
+ return torch.ops.bitsandbytes.gemm_4bit.default(
+ x, packed, ctx.shape, absmax, ctx.blocksize, ctx.quant_type, bias=bias
+ )
+
+ @staticmethod
+ @torch.amp.custom_bwd(device_type="cuda")
+ def backward(ctx, grad_output):
+ # Recompute must have reloaded this layer into its slot, and the
+ # one-ahead prefetcher must not recycle that slot before its
+ # backward finishes. A deeper lookahead would otherwise make the
+ # aliases below silently describe another layer (#842).
+ if ctx.owner_check is not None:
+ ctx.owner_check()
+ packed, absmax, state2_absmax, state2_code, offset = ctx.saved_tensors
+ state2 = None
+ q_offset = None
+ if ctx.nested:
+ state2 = bnb_functional.QuantState(
+ absmax=state2_absmax,
+ code=state2_code,
+ blocksize=ctx.state2_blocksize,
+ dtype=torch.float32,
+ )
+ q_offset = offset
+ quant_state = bnb_functional.QuantState(
+ absmax=absmax,
+ shape=torch.Size(ctx.shape),
+ dtype=ctx.weight_dtype,
+ blocksize=ctx.blocksize,
+ quant_type=ctx.quant_type,
+ offset=q_offset,
+ state2=state2,
+ )
+ # bitsandbytes 0.50.x exposes a fused forward GEMM but no transposed
+ # 4-bit GEMM for dX. Keep this fallback explicit: it is correct and
+ # checkpoint-visible, but #842 remains open until this dense
+ # dequantisation is replaced by a real transposed kernel.
+ grad_x = None
+ if ctx.needs_input_grad[0]:
+ weight = bnb_functional.dequantize_4bit(packed, quant_state).to(
+ grad_output.dtype
+ )
+ grad_x = torch.matmul(grad_output, weight)
+ grad_bias = None
+ if ctx.needs_input_grad[6] and ctx.bias_dtype is not None:
+ grad_bias = grad_output.reshape(-1, grad_output.shape[-1]).sum(
+ dim=0, dtype=ctx.bias_dtype
+ )
+ return (
+ grad_x,
+ None,
+ None,
+ None,
+ None,
+ None,
+ grad_bias,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+
+ _CHECKPOINT_VISIBLE_NF4_FUNCTION = CheckpointVisibleNF4Matmul
+ return CheckpointVisibleNF4Matmul
+
+
+def checkpoint_visible_nf4_linear(
+ x: Any, packed: Any, quant_state: Any, bias: Any = None
+) -> Any:
+ """Fused NF4 forward with checkpoint-visible packed state (#842)."""
+ empty = packed.new_empty((0,))
+ state2_absmax = empty
+ state2_code = empty
+ offset = empty
+ state2_blocksize = 0
+ if quant_state.nested:
+ state2_absmax = quant_state.state2.absmax
+ state2_code = quant_state.state2.code
+ offset = quant_state.offset
+ state2_blocksize = int(quant_state.state2.blocksize)
+ return _checkpoint_visible_nf4_function().apply(
+ x,
+ packed,
+ quant_state.absmax,
+ state2_absmax,
+ state2_code,
+ offset,
+ bias,
+ tuple(quant_state.shape),
+ quant_state.dtype,
+ int(quant_state.blocksize),
+ str(quant_state.quant_type),
+ bool(quant_state.nested),
+ state2_blocksize,
+ )
+
+
+def _can_use_checkpoint_visible_nf4_gemm(x: Any, quant_state: Any) -> bool:
+ """Match bitsandbytes' own decision to use its custom 4-bit CUDA GEMM.
+
+ The private dispatch names are intentionally read from bitsandbytes rather
+ than copying a card-specific M window. If those private names move, prefer
+ the checkpoint-visible Function: it remains exact, though potentially
+ slower, and the compatibility test makes the upstream change visible.
+ """
+ if getattr(getattr(x, "device", None), "type", None) != "cuda":
+ return False
+ if bool(getattr(quant_state, "nested", False)):
+ state2 = getattr(quant_state, "state2", None)
+ if state2 is None or int(getattr(state2, "blocksize", 0)) != 256:
+ return False
+ try:
+ import torch
+
+ torch.ops.bitsandbytes.gemm_4bit.default
+ except (ImportError, AttributeError, RuntimeError):
+ return False
+ try:
+ from bitsandbytes.backends.cuda import ops as bnb_cuda_ops
+
+ custom_max_m = bnb_cuda_ops._gemm_4bit_custom_max_m
+ use_custom_fn = bnb_cuda_ops._gemm_4bit_use_custom_fn
+ except (ImportError, AttributeError, RuntimeError):
+ return True
+
+ k = int(x.shape[-1])
+ m = int(x.numel() // k)
+ n = int(quant_state.shape[0])
+ blocksize = int(quant_state.blocksize)
+ if m > int(custom_max_m) or k % blocksize != 0:
+ return False
+ return bool(use_custom_fn(x.device.index, x.dtype, m, n, k))
+
+
def install_dequant_forward(module: Any) -> int:
"""#331 — keep a STREAMED NF4 weight out of ``bitsandbytes``' ``MatMul4Bit``.
@@ -195,17 +389,21 @@ def install_dequant_forward(module: Any) -> int:
forward-to-backward span, so any copy keeps one layer alive for that span and
costs O(model). On real 32B, peak VRAM 4 220 -> 19 720 MiB.
- So the weight never enters that autograd Function. It is dequantised inside the
- checkpointed region and multiplied natively; ``F.linear`` saves the dequantised
- tensor through the ordinary mechanism, which checkpointing DOES discard and
- recompute, and the transient lives only inside the recomputed block — O(window).
-
- This changes the computation path used by the patched NF4 module. With
- bitsandbytes 0.50.2, the native fused ``MatMul4Bit`` path and explicit
- ``dequantize_4bit`` + ``F.linear`` can differ depending on the CUDA
- architecture and projection shape. The dequantise + linear path is retained
- for correctness under checkpointing (#331); this path choice is not assumed
- to be numerically free.
+ The streamed weight still never enters bitsandbytes' ``MatMul4Bit`` Function.
+ When bitsandbytes' own CUDA dispatch selects its custom 4-bit GEMM, #842 routes
+ that same operation through Soup's autograd Function: packed bytes and every
+ quantisation tensor go through ``save_for_backward``, so non-reentrant
+ checkpointing can discard and recompute them after the pool refills the correct
+ layer. Whenever bitsandbytes selects its dequantise + linear fallback, Soup
+ keeps the v0.73.0 path rather than paying a third dequantisation in backward.
+ Missing private dispatch symbols fail toward the Function: exact but possibly
+ slower, never toward an alias-unsafe ``MatMul4Bit``.
+
+ The #842 Function is deliberately only the first half of the intended kernel.
+ bitsandbytes exposes a fused forward GEMM but no transposed 4-bit GEMM for
+ ``grad_x = grad_y @ W``; its backward also dequantises. Soup therefore keeps
+ that dense-dequant backward explicitly until a transposed kernel exists. Do
+ not claim the full #842 throughput ceiling from the fused-forward path alone.
Returns the number of modules patched, so a caller can assert it patched
something. Zero would mean the model carries no 4-bit linears at all.
@@ -233,8 +431,16 @@ def install_dequant_forward(module: Any) -> int:
if bias is not None:
bias = bias.to(x.dtype)
- # THE repair: dequantise here, inside whatever checkpointed region this
- # forward is running in, and let F.linear save the dense weight properly.
+ # Match bnb's own private dispatch. Only the custom-GEMM arm needs
+ # Soup's Function; on bnb's dequant+linear arm the old path below has
+ # identical arithmetic and avoids an extra backward dequantisation.
+ if _can_use_checkpoint_visible_nf4_gemm(x, quant_state):
+ return checkpoint_visible_nf4_linear(
+ x, self.weight, quant_state, bias
+ ).to(inp_dtype)
+
+ # Compatibility path: dequantise inside the checkpointed region and let
+ # F.linear save the dense weight properly.
weight = dequantize_4bit(self.weight, quant_state).to(x.dtype)
return functional.linear(x, weight, bias).to(inp_dtype)
@@ -1131,6 +1337,13 @@ def _build_streamed_layer_class():
self.use_checkpoint = bool(use_checkpoint)
self.quant_specs = dict(quant_specs or {})
self.codes = dict(codes or {})
+ # #841 — each wrapper returns to the same pool slot on every visit.
+ # Cache the tensor/Params4bit substitution views for that slot rather
+ # than reconstructing Python wrappers and QuantState objects on every
+ # forward and checkpoint recompute. The views share storage with the
+ # pool tensors, so later layer loads update their contents in place.
+ self._cached_substitution_buffers = None
+ self._cached_substitution_weights = None
# v0.72.5 (#331) — a streamed NF4 weight must not reach MatMul4Bit,
# which captures it outside save_for_backward and so aliases the pool
# across the checkpoint boundary. See install_dequant_forward.
@@ -1355,20 +1568,42 @@ def _build_streamed_layer_class():
# Weights arrive with requires_grad=False, so autograd allocates no
# grad buffers for them — but W STAYS IN THE GRAPH for W^T . dL/dy,
# which is how the lower adapters receive gradient at all.
- if not self.quant_specs:
- return {meta: buffers[ckpt] for meta, ckpt in self.name_map.items()}
- # NF4: a Params4bit VIEW is rebuilt over the pooled buffer on every
- # call (plan P3). The packed bytes are never copied or re-quantised
- # — only the small Python wrapper is reconstructed.
+ #
+ # #841 — a wrapper revisits the same pool-slot mapping every forward
+ # and checkpoint recompute. Only the tensors' CONTENTS change when a
+ # layer is loaded. Reuse the mapping and Params4bit/QuantState views
+ # while the mapping object is identical; rebuilding them is pure
+ # Python/object churn and does not create fresher storage.
+ if (
+ self._cached_substitution_buffers is buffers
+ and self._cached_substitution_weights is not None
+ ):
+ return self._cached_substitution_weights
+
weights = {}
for meta, ckpt in self.name_map.items():
spec = self.quant_specs.get(ckpt)
if spec is None:
weights[meta] = buffers[ckpt]
else:
- weights[meta] = rebuild_params4bit(ckpt, buffers, spec, self.codes)
+ weight = rebuild_params4bit(ckpt, buffers, spec, self.codes)
+ weight._soup_stream_owner_check = self._assert_nf4_slot_owner
+ weights[meta] = weight
+ self._cached_substitution_buffers = buffers
+ self._cached_substitution_weights = weights
return weights
+ def _assert_nf4_slot_owner(self) -> None:
+ slot = self.pool.slot_for(self.idx)
+ owner = self.pool.owner[slot]
+ if owner != self.idx:
+ raise RuntimeError(
+ "streamed NF4 backward found a recycled weight slot: "
+ f"slot {slot} holds layer {owner}, expected layer {self.idx}. "
+ "The prefetch lookahead exceeded the checkpoint-visible "
+ "alias lifetime."
+ )
+
def _body(self, hidden_states: Any, *args: Any, **kwargs: Any) -> Any:
buffers = self.pool.wait(self.idx)
self.prefetcher.advance(self.idx)
diff --git a/tests/test_issue385_stream_dtype.py b/tests/test_issue385_stream_dtype.py
index 25e82e24..acdfbcad 100644
--- a/tests/test_issue385_stream_dtype.py
+++ b/tests/test_issue385_stream_dtype.py
@@ -439,12 +439,10 @@ def _copy_lora(src, dst):
class TestFloat16StreamingIsBitExact:
"""Acceptance item 4 of #385.
- The reference matches the streamed model's computation path. For NF4 that
- means a genuinely NF4-quantised resident reference with
- ``install_dequant_forward`` applied. With ``bitsandbytes`` 0.50.2, NF4 may
- dispatch through a different fused kernel depending on CUDA architecture
- and projection shape, so comparing the native resident path would measure
- kernel-path differences rather than layer streaming.
+ The reference is a genuinely NF4-quantised resident model using native
+ bitsandbytes dispatch. Streamed NF4 follows that same fused-versus-dequantized
+ decision, so this comparison isolates layer streaming without changing the
+ resident arithmetic.
"""
def _run(self, tmp_path, dtype: str, quant: str) -> float:
@@ -455,7 +453,6 @@ class TestFloat16StreamingIsBitExact:
from soup_cli.utils.layer_stream_runtime import (
build_meta_skeleton,
build_streamed_model,
- install_dequant_forward,
quantised_layer_suffixes,
)
@@ -496,7 +493,6 @@ class TestFloat16StreamingIsBitExact:
weights, quantization_config=build_nf4_config(dtype),
dtype=getattr(torch, dtype), device_map={"": "cuda"},
)
- assert install_dequant_forward(base) > 0
base.config.use_cache = False
for param in base.parameters():
param.requires_grad = False
diff --git a/tests/test_issue842_checkpoint_visible_nf4.py b/tests/test_issue842_checkpoint_visible_nf4.py
new file mode 100644
index 00000000..24a58e29
--- /dev/null
+++ b/tests/test_issue842_checkpoint_visible_nf4.py
@@ -0,0 +1,614 @@
+"""Checkpoint-visible NF4 fused-forward groundwork (#842, folding #841)."""
+
+from __future__ import annotations
+
+import os
+import sys
+
+import pytest
+
+from soup_cli.utils.layer_stream_runtime import checkpoint_visible_nf4_linear
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+torch = pytest.importorskip("torch")
+bnb_functional = pytest.importorskip("bitsandbytes.functional")
+
+
[email protected]("nested", [False, True])
+def test_fused_forward_and_input_gradient_match_dequant_linear(nested):
+ torch.manual_seed(17)
+ weight = torch.randn(16, 16)
+ packed, state = bnb_functional.quantize_4bit(
+ weight, quant_type="nf4", compress_statistics=nested
+ )
+ x = torch.randn(3, 16, requires_grad=True)
+ reference_x = x.detach().clone().requires_grad_(True)
+
+ actual = checkpoint_visible_nf4_linear(x, packed, state)
+ dense = bnb_functional.dequantize_4bit(packed, state).to(reference_x.dtype)
+ expected = torch.nn.functional.linear(reference_x, dense)
+
+ assert torch.equal(actual, expected)
+ actual.square().sum().backward()
+ expected.square().sum().backward()
+ assert torch.equal(x.grad, reference_x.grad)
+
+
+def _non_nested_state(absmax, template):
+ return bnb_functional.QuantState(
+ absmax=absmax,
+ shape=template.shape,
+ dtype=template.dtype,
+ blocksize=template.blocksize,
+ quant_type=template.quant_type,
+ )
+
+
+def test_save_for_backward_makes_pool_recycling_recompute_and_preserve_gradients():
+ from torch.utils.checkpoint import checkpoint
+
+ torch.manual_seed(23)
+ weight0 = torch.randn(16, 16)
+ weight1 = torch.randn(16, 16)
+ packed0, state0 = bnb_functional.quantize_4bit(weight0, quant_type="nf4")
+ packed1, state1 = bnb_functional.quantize_4bit(weight1, quant_type="nf4")
+
+ shared_packed = packed0.clone()
+ shared_absmax = state0.absmax.clone()
+ shared_state = _non_nested_state(shared_absmax, state0)
+ calls = {"n": 0}
+
+ def streamed_body(value):
+ calls["n"] += 1
+
+ with torch.no_grad():
+ shared_packed.copy_(packed0)
+ shared_absmax.copy_(state0.absmax)
+ return checkpoint_visible_nf4_linear(value, shared_packed, shared_state)
+
+ x = torch.randn(3, 16, requires_grad=True)
+ reference_x = x.detach().clone().requires_grad_(True)
+ output = checkpoint(streamed_body, x, use_reentrant=False)
+
+ # Recycle the pool slot to another layer before backward.
+ with torch.no_grad():
+ shared_packed.copy_(packed1)
+ shared_absmax.copy_(state1.absmax)
+
+ output.square().sum().backward()
+ dense0 = bnb_functional.dequantize_4bit(packed0, state0).to(reference_x.dtype)
+ reference = torch.nn.functional.linear(reference_x, dense0)
+ reference.square().sum().backward()
+
+ assert calls["n"] == 2, "checkpoint did not recompute the custom NF4 op"
+ assert torch.equal(x.grad, reference_x.grad)
+
+
+def test_plain_ctx_control_is_detectably_wrong_after_pool_recycling():
+ """Negative control: reproduces the #331 lifetime bug on a tiny CPU fixture."""
+ from torch.utils.checkpoint import checkpoint
+
+ torch.manual_seed(29)
+ weight0 = torch.randn(16, 16)
+ weight1 = torch.randn(16, 16)
+
+ packed0, state0 = bnb_functional.quantize_4bit(weight0, quant_type="nf4")
+ packed1, state1 = bnb_functional.quantize_4bit(weight1, quant_type="nf4")
+ shared_packed = packed0.clone()
+ shared_absmax = state0.absmax.clone()
+ shared_state = _non_nested_state(shared_absmax, state0)
+
+ class PlainCtx4Bit(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, value, packed):
+ ctx.packed = packed
+ ctx.state = shared_state
+ return torch.ops.bitsandbytes.gemm_4bit.default(
+ value,
+ packed,
+ shared_state.shape,
+ shared_state.absmax,
+ shared_state.blocksize,
+ shared_state.quant_type,
+ )
+
+ @staticmethod
+ def backward(ctx, grad_output):
+ dense = bnb_functional.dequantize_4bit(ctx.packed, ctx.state).to(
+ grad_output.dtype
+ )
+ return torch.matmul(grad_output, dense), None
+
+ calls = {"n": 0}
+
+ def broken_body(value):
+ calls["n"] += 1
+ with torch.no_grad():
+ shared_packed.copy_(packed0)
+ shared_absmax.copy_(state0.absmax)
+ return PlainCtx4Bit.apply(value, shared_packed)
+
+ x = torch.randn(3, 16, requires_grad=True)
+ reference_x = x.detach().clone().requires_grad_(True)
+ output = checkpoint(broken_body, x, use_reentrant=False)
+ with torch.no_grad():
+ shared_packed.copy_(packed1)
+ shared_absmax.copy_(state1.absmax)
+ output.square().sum().backward()
+
+ dense0 = bnb_functional.dequantize_4bit(packed0, state0).to(reference_x.dtype)
+ reference = torch.nn.functional.linear(reference_x, dense0)
+ reference.square().sum().backward()
+
+ assert calls["n"] == 1, "negative control unexpectedly became checkpoint-visible"
+ assert not torch.equal(x.grad, reference_x.grad)
+ assert (x.grad - reference_x.grad).abs().max().item() > 1e-3
+
+
+def test_production_capability_gate_keeps_cpu_on_the_old_path():
+ from soup_cli.utils.layer_stream_runtime import _can_use_checkpoint_visible_nf4_gemm
+
+ packed, state = bnb_functional.quantize_4bit(torch.randn(16, 16), quant_type="nf4")
+ assert packed.device.type == "cpu"
+ assert _can_use_checkpoint_visible_nf4_gemm(torch.randn(2, 16), state) is False
+
+
+def test_bitsandbytes_private_dispatch_contract_is_visible_to_cpu_ci():
+ try:
+ from bitsandbytes.backends.cuda import ops as bnb_cuda_ops
+ except (ImportError, AttributeError) as exc:
+ pytest.skip(f"bitsandbytes CUDA ops cannot import with this torch build: {exc}")
+
+ assert hasattr(bnb_cuda_ops, "_gemm_4bit_use_custom_fn")
+ assert hasattr(bnb_cuda_ops, "_gemm_4bit_custom_max_m")
+
+
+ ("m", "k", "dispatch", "expected"),
+ [
+ (3, 64, True, True),
+ (3, 64, False, False),
+ (97, 64, True, False),
+ (3, 65, True, False),
+ ],
+ ids=["fused", "bnb-dequant", "above-m-cap", "misaligned-k"],
+)
+def test_cuda_route_follows_bitsandbytes_shape_decision_on_cpu(
+ monkeypatch, m, k, dispatch, expected
+):
+ from types import SimpleNamespace
+
+ import bitsandbytes.backends.cuda as bnb_cuda_package
+
+ from soup_cli.utils.layer_stream_runtime import _can_use_checkpoint_visible_nf4_gemm
+
+ calls = []
+
+ def use_custom_fn(device_index, dtype, rows, out_features, in_features):
+ calls.append((device_index, dtype, rows, out_features, in_features))
+ return dispatch
+
+ fake_ops = SimpleNamespace(
+ _gemm_4bit_custom_max_m=96,
+ _gemm_4bit_use_custom_fn=use_custom_fn,
+ )
+ monkeypatch.setitem(sys.modules, "bitsandbytes.backends.cuda.ops", fake_ops)
+ monkeypatch.setattr(bnb_cuda_package, "ops", fake_ops, raising=False)
+ x = SimpleNamespace(
+ device=SimpleNamespace(type="cuda", index=0),
+ dtype=torch.bfloat16,
+ shape=(m, k),
+ numel=lambda: m * k,
+ )
+ state = SimpleNamespace(
+ nested=False,
+ shape=(128, k),
+ blocksize=64,
+ )
+
+ assert _can_use_checkpoint_visible_nf4_gemm(x, state) is expected
+ if m <= 96 and k % 64 == 0:
+ assert calls == [(0, torch.bfloat16, m, 128, k)]
+ else:
+ assert calls == []
+
+
+ ("shape", "expected", "expected_m"),
+ [
+ ((1, 97, 64), False, None),
+ ((2, 3, 64), True, 6),
+ ],
+ ids=["three-dimensional-above-m-cap", "three-dimensional-fused"],
+)
+def test_cuda_route_flattens_all_leading_dimensions_on_cpu(
+ monkeypatch, shape, expected, expected_m
+):
+ from types import SimpleNamespace
+
+ import bitsandbytes.backends.cuda as bnb_cuda_package
+
+ from soup_cli.utils.layer_stream_runtime import _can_use_checkpoint_visible_nf4_gemm
+
+ calls = []
+
+ def use_custom_fn(device_index, dtype, rows, out_features, in_features):
+ calls.append((device_index, dtype, rows, out_features, in_features))
+ return True
+
+ fake_ops = SimpleNamespace(
+ _gemm_4bit_custom_max_m=96,
+ _gemm_4bit_use_custom_fn=use_custom_fn,
+ )
+ monkeypatch.setitem(sys.modules, "bitsandbytes.backends.cuda.ops", fake_ops)
+ monkeypatch.setattr(bnb_cuda_package, "ops", fake_ops, raising=False)
+ x = SimpleNamespace(
+ device=SimpleNamespace(type="cuda", index=0),
+ dtype=torch.bfloat16,
+ shape=shape,
+ numel=lambda: shape[0] * shape[1] * shape[2],
+ )
+ state = SimpleNamespace(nested=False, shape=(128, 64), blocksize=64)
+
+ assert _can_use_checkpoint_visible_nf4_gemm(x, state) is expected
+ if expected_m is None:
+ assert calls == []
+ else:
+ assert calls == [(0, torch.bfloat16, expected_m, 128, 64)]
+
+
+def test_backward_refuses_a_recycled_stream_slot():
+ torch.manual_seed(31)
+ packed, state = bnb_functional.quantize_4bit(
+ torch.randn(16, 16), quant_type="nf4"
+ )
+ owner = {"current": 0}
+
+ def assert_owner():
+ if owner["current"] != 0:
+ raise RuntimeError("recycled weight slot")
+
+ packed._soup_stream_owner_check = assert_owner
+ x = torch.randn(3, 16, requires_grad=True)
+ output = checkpoint_visible_nf4_linear(x, packed, state)
+ owner["current"] = 1
+ with pytest.raises(RuntimeError, match="recycled weight slot"):
+ output.square().sum().backward()
+
+
+def test_the_production_owner_check_refuses_a_recycled_slot(tmp_path):
+ from test_v07202 import _nf4_stream
+
+ import soup_cli.utils.layer_stream_runtime as runtime_module
+
+ model, runtime, _, _, _ = _nf4_stream(tmp_path, n_layers=4, buffers=2)
+ layer = runtime_module.decoder_owner(model).layers[0]
+ slot = runtime.pool.slot_for(layer.idx)
+
+ runtime.pool.owner[slot] = layer.idx
+ layer._assert_nf4_slot_owner()
+
+ runtime.pool.owner[slot] = layer.idx + 2
+ with pytest.raises(RuntimeError, match="recycled weight slot"):
+ layer._assert_nf4_slot_owner()
+
+
+def test_streamed_layer_caches_substitution_views_for_one_pool_mapping(
+ tmp_path, monkeypatch
+):
+ from test_v07202 import _nf4_stream
+
+ import soup_cli.utils.layer_stream_runtime as runtime_module
+
+ model, runtime, _, _, _ = _nf4_stream(tmp_path)
+ layer = runtime_module.decoder_owner(model).layers[0]
+ buffers = runtime.pool.buffers[runtime.pool.slot_for(layer.idx)]
+
+ # Start from a known-empty cache: model construction must not be what makes
+ # this test pass.
+ layer._cached_substitution_buffers = None
+ layer._cached_substitution_weights = None
+
+ real_rebuild = runtime_module.rebuild_params4bit
+ calls = {"n": 0}
+
+ def counting_rebuild(*args, **kwargs):
+ calls["n"] += 1
+ return real_rebuild(*args, **kwargs)
+
+ monkeypatch.setattr(runtime_module, "rebuild_params4bit", counting_rebuild)
+
+ quantized = sum(
+ ckpt in layer.quant_specs for ckpt in layer.name_map.values()
+ )
+ assert quantized > 0
+
+ first = layer._substituted_weights(buffers)
+ second = layer._substituted_weights(buffers)
+ assert second is first
+ assert calls["n"] == quantized
+
+ # A different mapping object represents a different pool view and must not
+ # inherit the cache, even when it currently points at the same tensors.
+ other_mapping = dict(buffers)
+ third = layer._substituted_weights(other_mapping)
+ assert third is not first
+ assert calls["n"] == 2 * quantized
+
+
+def test_missing_bnb_private_dispatch_symbols_fail_toward_safe_function_on_cpu(
+ monkeypatch,
+):
+ from types import SimpleNamespace
+
+ import bitsandbytes.backends.cuda as bnb_cuda_package
+
+ from soup_cli.utils.layer_stream_runtime import _can_use_checkpoint_visible_nf4_gemm
+
+ fake_ops = SimpleNamespace()
+ monkeypatch.setitem(sys.modules, "bitsandbytes.backends.cuda.ops", fake_ops)
+ monkeypatch.setattr(bnb_cuda_package, "ops", fake_ops, raising=False)
+ x = SimpleNamespace(
+ device=SimpleNamespace(type="cuda", index=0),
+ dtype=torch.bfloat16,
+ shape=(512, 64),
+ numel=lambda: 512 * 64,
+ )
+ state = SimpleNamespace(nested=False, shape=(128, 64), blocksize=64)
+
+ assert _can_use_checkpoint_visible_nf4_gemm(x, state) is True
+
+
+def test_forced_function_in_a_recycling_stream_matches_unpatched_resident(
+ tmp_path, monkeypatch
+):
+ from test_v07202 import (
+ _nf4_stream,
+ _randomise_lora_b,
+ _resident_nf4,
+ _sync_adapters,
+ )
+
+ import soup_cli.utils.layer_stream_runtime as runtime_module
+
+ calls = {"function": 0, "owner_checks": 0}
+ real_function = runtime_module.checkpoint_visible_nf4_linear
+
+ def counting_function(x, packed, quant_state, bias=None):
+ calls["function"] += 1
+ check = getattr(packed, "_soup_stream_owner_check", None)
+ assert check is not None, "streamed NF4 weight carries no slot-owner check"
+
+ def counted_check():
+ calls["owner_checks"] += 1
+ check()
+
+ packed._soup_stream_owner_check = counted_check
+ try:
+ return real_function(x, packed, quant_state, bias)
+ finally:
+ packed._soup_stream_owner_check = check
+
+ monkeypatch.setattr(
+ runtime_module, "checkpoint_visible_nf4_linear", counting_function
+ )
+ monkeypatch.setattr(
+ runtime_module,
+ "_can_use_checkpoint_visible_nf4_gemm",
+ lambda *_args, **_kwargs: True,
+ )
+
+ # Four layers over two buffers: every slot is refilled by another layer mid-step.
+ streamed, runtime, weights, _index, _shards = _nf4_stream(
+ tmp_path, n_layers=4, buffers=2
+ )
+ resident = _resident_nf4(weights)
+ _randomise_lora_b(resident)
+ assert _sync_adapters(streamed, resident) > 0
+
+ input_ids = torch.randint(
+ 0, 64, (1, 16), generator=torch.Generator().manual_seed(5)
+ )
+ batch = {
+ "input_ids": input_ids,
+ "attention_mask": torch.ones_like(input_ids),
+ "labels": input_ids,
+ }
+ streamed.train()
+ resident.train()
+ streamed_loss = streamed(**batch).loss
+ streamed_loss.backward()
+ resident_loss = resident(**batch).loss
+ resident_loss.backward()
+
+ assert calls["function"] > 0 and calls["owner_checks"] > 0
+ assert runtime.pool.loads > 4, "no slot was recycled"
+ assert torch.equal(streamed_loss, resident_loss)
+
+ def lora_grads(model):
+ return {
+ name.replace(".inner.", "."): parameter.grad
+ for name, parameter in model.named_parameters()
+ if "lora_" in name and parameter.grad is not None
+ }
+
+ mine, theirs = lora_grads(streamed), lora_grads(resident)
+ assert mine and mine.keys() == theirs.keys()
+ for name, grad in mine.items():
+ assert torch.equal(grad, theirs[name]), name
+
+
+def test_missing_bnb_private_dispatch_symbols_fail_toward_the_safe_function(
+ monkeypatch,
+):
+ from bitsandbytes.backends.cuda import ops as bnb_cuda_ops
+
+ from soup_cli.utils.layer_stream_runtime import (
+ _can_use_checkpoint_visible_nf4_gemm,
+ )
+
+ weight = torch.randn(64, 64, device="cuda", dtype=torch.bfloat16)
+ _packed, state = bnb_functional.quantize_4bit(weight, quant_type="nf4")
+ x = torch.randn(3, 64, device="cuda", dtype=torch.bfloat16)
+ monkeypatch.delattr(bnb_cuda_ops, "_gemm_4bit_use_custom_fn")
+ assert _can_use_checkpoint_visible_nf4_gemm(x, state) is True
+
+
+def test_fused_cuda_recycling_matches_private_buffer_and_plain_ctx_fails():
+ from torch.utils.checkpoint import checkpoint
+
+ from soup_cli.utils.layer_stream_runtime import (
+ _can_use_checkpoint_visible_nf4_gemm,
+ )
+
+ torch.manual_seed(37)
+ weight0 = torch.randn(64, 64, device="cuda", dtype=torch.bfloat16)
+ weight1 = torch.randn(64, 64, device="cuda", dtype=torch.bfloat16)
+ packed0, state0 = bnb_functional.quantize_4bit(weight0, quant_type="nf4")
+ packed1, state1 = bnb_functional.quantize_4bit(weight1, quant_type="nf4")
+ shared_packed = packed0.clone()
+ shared_absmax = state0.absmax.clone()
+ shared_state = _non_nested_state(shared_absmax, state0)
+ x = torch.randn(3, 64, device="cuda", dtype=torch.bfloat16, requires_grad=True)
+ assert _can_use_checkpoint_visible_nf4_gemm(x, shared_state) is True
+
+ calls = {"visible": 0, "plain": 0}
+
+ def visible_body(value):
+ calls["visible"] += 1
+ with torch.no_grad():
+ shared_packed.copy_(packed0)
+ shared_absmax.copy_(state0.absmax)
+ return checkpoint_visible_nf4_linear(value, shared_packed, shared_state)
+
+ output = checkpoint(visible_body, x, use_reentrant=False)
+ with torch.no_grad():
+ shared_packed.copy_(packed1)
+ shared_absmax.copy_(state1.absmax)
+ output.float().square().sum().backward()
+
+ private_x = x.detach().clone().requires_grad_(True)
+ private = checkpoint_visible_nf4_linear(private_x, packed0, state0)
+ private.float().square().sum().backward()
+ assert calls["visible"] == 2
+ assert torch.equal(x.grad, private_x.grad)
+
+ class PlainCtx4Bit(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, value, packed):
+ ctx.packed = packed
+ ctx.state = shared_state
+ return torch.ops.bitsandbytes.gemm_4bit.default(
+ value,
+ packed,
+ shared_state.shape,
+ shared_state.absmax,
+ shared_state.blocksize,
+ shared_state.quant_type,
+ )
+
+ @staticmethod
+ def backward(ctx, grad_output):
+ dense = bnb_functional.dequantize_4bit(ctx.packed, ctx.state).to(
+ grad_output.dtype
+ )
+ return torch.matmul(grad_output, dense), None
+
+ def plain_body(value):
+ calls["plain"] += 1
+ with torch.no_grad():
+ shared_packed.copy_(packed0)
+ shared_absmax.copy_(state0.absmax)
+ return PlainCtx4Bit.apply(value, shared_packed)
+
+ plain_x = x.detach().clone().requires_grad_(True)
+ plain = checkpoint(plain_body, plain_x, use_reentrant=False)
+ with torch.no_grad():
+ shared_packed.copy_(packed1)
+ shared_absmax.copy_(state1.absmax)
+ plain.float().square().sum().backward()
+ assert calls["plain"] == 1
+ assert not torch.equal(plain_x.grad, private_x.grad)
+
+
[email protected]("seq_len", [8, 128], ids=["fused-m", "training-m"])
+def test_streamed_matches_unpatched_resident_logits_and_all_lora_grads(
+ tmp_path, monkeypatch, seq_len
+):
+ import bitsandbytes as bnb
+ from test_v07202 import (
+ _nf4_stream,
+ _randomise_lora_b,
+ _resident_nf4,
+ _sync_adapters,
+ )
+
+ import soup_cli.utils.layer_stream_runtime as runtime_module
+
+ streamed, _runtime, weights, _index, _shards = _nf4_stream(
+ tmp_path, n_layers=4, buffers=2, device="cuda", dtype="bfloat16"
+ )
+ resident = _resident_nf4(weights, dtype="bfloat16", device=0)
+ _randomise_lora_b(resident)
+ assert _sync_adapters(streamed, resident) > 0
+
+ calls = {"function": 0, "streamed_matmul": 0, "resident_matmul": 0}
+ phase = {"name": "streamed"}
+ real_function = runtime_module.checkpoint_visible_nf4_linear
+ real_matmul = bnb.matmul_4bit
+ real_gate = runtime_module._can_use_checkpoint_visible_nf4_gemm
+ gate_decisions = []
+
+ def counting_function(*args, **kwargs):
+ calls["function"] += 1
+ return real_function(*args, **kwargs)
+
+ def counting_matmul(*args, **kwargs):
+ calls[phase["name"] + "_matmul"] += 1
+ return real_matmul(*args, **kwargs)
+
+ def recording_gate(*args, **kwargs):
+ decision = real_gate(*args, **kwargs)
+ gate_decisions.append(decision)
+ return decision
+
+ monkeypatch.setattr(
+ runtime_module, "checkpoint_visible_nf4_linear", counting_function
+ )
+ monkeypatch.setattr(
+ runtime_module, "_can_use_checkpoint_visible_nf4_gemm", recording_gate
+ )
+ monkeypatch.setattr(bnb, "matmul_4bit", counting_matmul)
+
+ generator = torch.Generator(device="cuda").manual_seed(41)
+ input_ids = torch.randint(
+ 0, 64, (1, seq_len), device="cuda", generator=generator
+ )
+ streamed_logits = streamed(input_ids=input_ids, use_cache=False).logits
+ streamed_logits.float().square().mean().backward()
+ phase["name"] = "resident"
+ resident_logits = resident(input_ids=input_ids, use_cache=False).logits
+ resident_logits.float().square().mean().backward()
+
+ assert calls["streamed_matmul"] == 0
+ assert calls["resident_matmul"] > 0
+ assert gate_decisions
+ assert (calls["function"] > 0) is any(gate_decisions)
+ assert torch.equal(streamed_logits, resident_logits)
+
+ def adapter_grads(model):
+ return {
+ name.replace(".inner.", "."): parameter.grad
+ for name, parameter in model.named_parameters()
+ if "lora_" in name and parameter.grad is not None
+ }
+
+ streamed_grads = adapter_grads(streamed)
+ resident_grads = adapter_grads(resident)
+ assert streamed_grads and streamed_grads.keys() == resident_grads.keys()
+ for name, grad in streamed_grads.items():
+ assert torch.equal(grad, resident_grads[name]), name
diff --git a/tests/test_issue968_bnb_nf4_path_divergence.py b/tests/test_issue968_bnb_nf4_path_divergence.py
index fa73f409..8b24e355 100644
--- a/tests/test_issue968_bnb_nf4_path_divergence.py
+++ b/tests/test_issue968_bnb_nf4_path_divergence.py
@@ -1,43 +1,29 @@
-"""#968 — pin the bitsandbytes fused-vs-dequant NF4 divergence that #857 rests on.
-
-#857 (merged ``d456a1d3``) moved the NF4 bit-exactness reference in
-``tests/test_issue385_stream_dtype.py`` onto the streamed model's *computation
-path*: the resident reference now gets ``install_dequant_forward`` applied too.
-The justification is that production streams NF4 through ``dequantize_4bit`` +
-``F.linear`` (``utils/layer_stream_runtime.py``, the #331 repair), while an
-unpatched resident ``Linear4bit`` goes through bitsandbytes' own fused kernel —
-so the old comparison was measuring two KERNELS against each other, not
-streaming against itself.
-
-That correction is right. The problem #968 records is that after the merge, the
-property it rests on is asserted NOWHERE: it survives only in two docstrings.
-A bitsandbytes release that fixed the fused path would make the correction
-unnecessary and nothing would say so; a release that worsened it would change
-the magnitude and nothing would notice.
-
-So this file asserts the property directly, with **no streaming anywhere in the
-experiment**. Two resident NF4 models are built from the same checkpoint, their
-packed weights are asserted byte-identical, and the only difference between them
-is whether ``install_dequant_forward`` was applied. On sm_120 with bitsandbytes
-0.50.2 they disagree; with the patch applied to BOTH (or to NEITHER) they agree
-exactly, which is what makes the divergence attributable to the path and not to
-the harness.
+"""#968 — pin Soup's streamed NF4 path to native bitsandbytes dispatch.
+
+#842 deliberately changes #857's reference. ``install_dequant_forward`` no
+longer means "always dequantise": it follows bitsandbytes' own CUDA decision.
+At a custom-GEMM shape it runs the native op through Soup's checkpoint-visible
+Function; at a fallback shape it keeps dequantise + ``F.linear``. A patched
+resident model must therefore agree bit for bit with an unpatched resident model
+at the fused shape, and a counter must prove this is not agreement obtained by
+silently disabling the Function.
WHAT THE "FUSED" PATH ACTUALLY IS, in bitsandbytes 0.50.2. ``#331``'s docstring
names ``MatMul4Bit``, which is where the *aliasing* bug lives, but numerically
both routes land on the same kernel: ``matmul_4bit`` calls
``torch.ops.bitsandbytes.gemm_4bit`` directly when no gradient is needed and
``MatMul4Bit.apply`` otherwise, and ``MatMul4Bit.forward`` calls that same op.
-Measured: the divergence below is bit-identical under ``torch.no_grad()`` and
-under ``torch.enable_grad()``, which is the evidence for that reading.
+The low-level control below still shows that the raw custom GEMM and a manually
+dequantised linear can differ; Soup no longer substitutes the latter when native
+bitsandbytes selected the former.
THE DIVERGENCE IS SHAPE-GATED, and this is the part that is easy to get wrong.
``gemm_4bit`` only runs its own fused dequantise-and-multiply for a small
-leading dimension; above it, bitsandbytes dequantises and calls a normal GEMM,
-which agrees with our path bit-for-bit. Measured on this card at
+leading dimension; above it, bitsandbytes dequantises and calls a normal GEMM.
+Measured on this card at
``M in {1..32}`` -> divergent, ``M >= 33`` -> exactly 0.0. That is why
-``test_issue385``'s ``(1, 12)`` input sees the divergence at all, and it is the
-trap the first attempt at this probe fell into (see the class docstring in
+the old always-dequantised ``test_issue385`` arm saw a divergence at ``(1, 12)``;
+it is the trap the first attempt at this probe fell into (see
``TestTheDivergenceIsGatedOnTheLeadingDimension``).
This can only ever be a dev-box signal: GitHub runners have no GPU, so the whole
@@ -45,10 +31,6 @@ module skips in CI, exactly like its neighbours in ``test_issue385_stream_dtype`
It is additionally pinned to the bitsandbytes version it was measured against, so
a version bump reports "unverified" rather than silently passing.
-**#968 does not resolve #776.** Which of the two bitsandbytes paths is
-numerically CORRECT on sm_120 is still unestablished. This file pins that they
-differ, and by how much.
-
Environment the constants below were measured on: RTX 5070 Laptop GPU (sm_120),
driver 616.92 / CUDA 13.4, torch 2.14.0+cu130, bitsandbytes 0.50.2,
transformers 5.17.0, peft 0.20.0, Python 3.12.10, Windows 11.
@@ -57,27 +39,10 @@ transformers 5.17.0, peft 0.20.0, Python 3.12.10, Windows 11.
import pytest
# --------------------------------------------------------------------------
-# The measurement, as data. Prose in a docstring is what #968 exists to replace.
+# Pinned native dispatch record.
# --------------------------------------------------------------------------
PINNED_BITSANDBYTES = "0.50.2"
-#: maxabs logit difference between two resident NF4 models that differ ONLY in
-#: whether ``install_dequant_forward`` was applied. Byte-identical packed
-#: weights, identical inputs, no streaming.
-MEASURED_LOGIT_DIVERGENCE = {
- "float16": 0.0006103515625,
- "bfloat16": 0.00439453125,
-}
-
-#: The assertion is about EXISTENCE and ROUGH MAGNITUDE, never equality. An
-#: exact-float assertion would break on any driver-level change in GEMM kernel
-#: selection and teach the next person to delete the test. One order of
-#: magnitude either side is wide enough to absorb that (repeated runs on this
-#: box are bit-stable, and re-seeding the model moves it by ~1.3x) and tight
-#: enough that a bitsandbytes release which fixed the fused path (-> 0.0) or
-#: worsened it (-> 10x) turns this red.
-MAGNITUDE_BAND = 10.0
-
#: ``gemm_4bit`` runs its fused path only up to this leading dimension; above
#: it bitsandbytes dequantises and calls an ordinary GEMM, which agrees with
#: ``install_dequant_forward`` exactly. Measured by bisection on this card.
@@ -87,8 +52,6 @@ _SEED = 7
_HIDDEN = 64
_SEQ_LEN = 12 # <= FUSED_KERNEL_MAX_ROWS, and the shape test_issue385 uses
-
-
def _bnb_version() -> str:
try:
import importlib.metadata
@@ -103,7 +66,7 @@ CUDA = pytest.mark.gpu(reason="the bitsandbytes 4-bit kernels are GPU-only")
PINNED = pytest.mark.skipif(
_bnb_version() != PINNED_BITSANDBYTES,
reason=(
- f"UNVERIFIED: the fused-vs-dequant NF4 divergence was measured against "
+ f"UNVERIFIED: the native NF4 dispatch was measured against "
f"bitsandbytes {PINNED_BITSANDBYTES}, this env has "
f"{_bnb_version() or 'no bitsandbytes'}. Re-measure and re-pin (#968) "
f"rather than widening the band."
@@ -176,7 +139,7 @@ def _logits(model, ids):
return model(input_ids=ids).logits.float()
-def _divergence(tmp_path, dtype: str, *, patch_reference: bool) -> float:
+def _divergence(tmp_path, dtype: str, *, patch_reference: bool, monkeypatch=None):
"""maxabs logit gap between two resident NF4 models built from one file.
``patch_reference=False`` is the real comparison: fused kernel vs
@@ -199,13 +162,26 @@ def _divergence(tmp_path, dtype: str, *, patch_reference: bool) -> float:
"below would be quantiser nondeterminism rather than a path difference"
)
+ calls = {"checkpoint_visible": 0}
+ if monkeypatch is not None:
+ import soup_cli.utils.layer_stream_runtime as runtime_module
+
+ real = runtime_module.checkpoint_visible_nf4_linear
+
+ def counting(*args, **kwargs):
+ calls["checkpoint_visible"] += 1
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(runtime_module, "checkpoint_visible_nf4_linear", counting)
+
if patch_reference:
assert install_dequant_forward(reference) > 0
assert install_dequant_forward(patched) > 0
generator = torch.Generator(device="cuda").manual_seed(3)
ids = torch.randint(0, 64, (1, _SEQ_LEN), device="cuda", generator=generator)
- return (_logits(reference, ids) - _logits(patched, ids)).abs().max().item()
+ gap = (_logits(reference, ids) - _logits(patched, ids)).abs().max().item()
+ return gap, calls
def _require_bf16():
@@ -217,30 +193,27 @@ def _require_bf16():
@CUDA
@PINNED
-class TestTheTwoBitsandbytesFourBitPathsDisagree:
- """The property #857's reference correction rests on, asserted.
+class TestSoupMatchesNativeBitsandbytesDispatch:
+ """The #842 reference: patched and native resident models agree exactly.
No streaming is involved. Two resident NF4 models, byte-identical packed
weights, identical input, differing only in ``install_dequant_forward``.
"""
@pytest.mark.parametrize("dtype", ["float16", "bfloat16"])
- def test_the_paths_diverge_by_the_measured_magnitude(self, tmp_path, dtype):
+ def test_patched_and_unpatched_agree_at_a_fused_m(
+ self, tmp_path, dtype, monkeypatch
+ ):
if dtype == "bfloat16":
_require_bf16()
- expected = MEASURED_LOGIT_DIVERGENCE[dtype]
-
- got = _divergence(tmp_path, dtype, patch_reference=False)
-
- assert got > 0.0, (
- f"the two bitsandbytes 4-bit paths now AGREE in {dtype}. If that is "
- f"real, #857's reference correction is no longer load-bearing and "
- f"#776 may be resolvable — re-measure before deleting anything."
+ gap, calls = _divergence(
+ tmp_path, dtype, patch_reference=False, monkeypatch=monkeypatch
)
- assert expected / MAGNITUDE_BAND <= got <= expected * MAGNITUDE_BAND, (
- f"{dtype}: divergence {got!r} is outside one order of magnitude of "
- f"the recorded {expected!r} on bitsandbytes {PINNED_BITSANDBYTES}"
+ assert calls["checkpoint_visible"] > 0, (
+ "the patched arm never ran Soup's checkpoint-visible Function at "
+ "the fused shape, so exact agreement would not pin #842"
)
+ assert gap == 0.0
@pytest.mark.parametrize("dtype", ["float16", "bfloat16"])
def test_the_same_path_twice_is_exact(self, tmp_path, dtype):
@@ -249,15 +222,8 @@ class TestTheTwoBitsandbytesFourBitPathsDisagree:
would read the same. Patch both -> the only difference is gone -> 0.0."""
if dtype == "bfloat16":
_require_bf16()
- assert _divergence(tmp_path, dtype, patch_reference=True) == 0.0
-
- def test_bfloat16_diverges_further_than_float16(self):
- """Structural, and it survives a change of shape or seed: bf16 carries
- 8 mantissa bits to fp16's 11, so the same relative kernel difference
- lands about an order of magnitude larger."""
- assert (
- MEASURED_LOGIT_DIVERGENCE["bfloat16"] > MEASURED_LOGIT_DIVERGENCE["float16"]
- )
+ gap, _calls = _divergence(tmp_path, dtype, patch_reference=True)
+ assert gap == 0.0
@CUDA
diff --git a/tests/test_v07202.py b/tests/test_v07202.py
index f663a28c..2a155e73 100644
--- a/tests/test_v07202.py
+++ b/tests/test_v07202.py
@@ -1890,14 +1890,11 @@ class TestNF4ParityOnCuda:
_randomise_lora_b(resident)
assert _sync_adapters(model, resident) > 0, "vacuous: no adapters copied"
- # 128 tokens, NOT 16: below 64 this fixture's [64x64] projections are
- # served by bitsandbytes' FUSED gemm_4bit kernel, while the streamed path
- # always dequantises (#331), so the two arms run different kernels and
- # differ by exactly one bf16 ulp — measured 3.906250e-03 = 2^-8 at 16
- # tokens. At 64 all 14 4-bit linears take _dequant_linear_fallback and
- # parity returns to 0.0; the window boundary and the exactness boundary
- # were measured to coincide exactly. 128 is that boundary with margin.
- # TestFixtureIsOutsideTheFusedKernelWindow in test_v07300.py pins it.
+ # 128 tokens exercises bitsandbytes' dequant+linear dispatch. Since
+ # #842 the streamed arm follows the same native dispatch at every M:
+ # Soup's checkpoint-visible Function owns the fused arm, while this
+ # larger shape keeps #331's dequant+linear arm without a third
+ # dequantisation. The #842 GPU matrix also pins the fused shape.
ids = torch.randint(
0, 64, (1, 128), generator=torch.Generator().manual_seed(11)
).cuda()
diff --git a/tests/test_v07300.py b/tests/test_v07300.py
index 07e394e1..c514e30a 100644
--- a/tests/test_v07300.py
+++ b/tests/test_v07300.py
@@ -24,13 +24,15 @@ across the whole forward-to-backward span, ANY de-aliasing keeps one copy of eve
layer alive for that span and costs O(model), not O(window). On real 32B that was
peak VRAM 4 220 -> 19 720 MiB, which deletes the feature's premise.
-THE REPAIR: do not send a streamed NF4 weight through ``MatMul4Bit`` at all.
-Dequantise inside the checkpointed region and use a native matmul. ``F.linear``
-saves the dequantised weight properly, so checkpointing DOES discard and recompute
-it, and the transient lives only inside the recomputed block — O(window) by
-construction.
+THE REPAIR: do not send a streamed NF4 weight through bitsandbytes'
+``MatMul4Bit`` autograd Function at all. v0.73.0 dequantised inside the
+checkpointed region and used ``F.linear``. #842 may instead call the native
+``bitsandbytes::gemm_4bit`` forward through Soup's own autograd Function, whose
+packed weight and quantisation tensors all pass through ``save_for_backward``.
+Either route is visible to checkpointing; the unsafe plain-ctx lifetime remains
+forbidden.
-WHY THIS IS NOT A NUMERICS CHANGE AT TRAINING SHAPES (STEP 13 of the record)
+HOW #842 PRESERVES THE NATIVE BITSANDBYTES REFERENCE
``bitsandbytes::gemm_4bit`` chooses between its fused kernel and
``_dequant_linear_fallback``. The constant this file used to cite is only the OUTER
@@ -46,19 +48,13 @@ occupancy heuristic over the full shape ``(M, N, K)`` and the device. The consta
therefore explains the ``M > 1536`` half only, and citing it alone is not an argument
about training shapes.
-What carries the claim is measurement, and it is SHAPE-DEPENDENT rather than
-universal. On REAL 8B/32B projections the fallback was taken at every M measured from
-8 to 2048, so at those shapes bitsandbytes is ALREADY doing what this repair does and
-the repair only makes it explicit and moves it inside the checkpoint: measured over
-423 rows, the gradient is bit-exact in every one of them, worst ``max_abs`` exactly
-0.0 — by construction, since bnb's own backward is dequantise-then-matmul.
-
-On SMALL shapes the fused kernel genuinely does run, and the forward then differs by
-one bf16 ulp: worst 3.95e-3 relative to scale against 2^-8 = 3.9e-3. That is not
-hypothetical: this file's own fixture (hidden 64) sits inside the fused window at
-M <= 32, which is precisely what ``TestFixtureIsOutsideTheFusedKernelWindow`` below
-exists to pin. Read the two together — the "always fallback" result belongs to the
-real projection shapes it was measured on, not to every call site.
+Soup now asks those private bitsandbytes dispatch symbols the same question. At a
+custom-GEMM shape it calls that GEMM through a checkpoint-visible Function; at a
+fallback shape it retains the dequantise + ``F.linear`` repair. Thus the streamed
+model matches an unpatched resident bitsandbytes model at both shapes without
+paying the Function's extra backward dequantisation at ordinary training M. If the
+private symbols move, Soup fails toward the safe Function and a GPU test reports
+the upstream change.
"""
import os
@@ -215,8 +211,8 @@ class TestStreamedPreferenceLossesDisableHfGradientCheckpointing:
# the CI fixture must exercise the kernel path production actually takes
# ==========================================================================
@pytest.mark.gpu(reason="the fused-kernel window is a CUDA dispatch")
-class TestFixtureIsOutsideTheFusedKernelWindow:
- """The streamed-vs-resident gate was comparing a code path no real model uses.
+class TestBitsandbytesDispatchAtTrainingShape:
+ """The larger fixture shape pins bitsandbytes' fallback branch.
``bitsandbytes::gemm_4bit`` dispatches on M. Measured on this fixture (hidden 64,
so every projection is [64x64] or [32x64]), on an H100:
@@ -234,9 +230,9 @@ class TestFixtureIsOutsideTheFusedKernelWindow:
measured to coincide EXACTLY at 64, which is what identifies the dispatch as the
cause of the ulp rather than something else that merely correlates with size.
- This test pins the fixture outside that window, so shrinking the sequence back
- for speed fails here with the reason attached instead of silently returning the
- gate to the wrong kernel.
+ #842 separately pins a fused shape and requires exact parity with an unpatched
+ resident model. This test keeps a representative training M on the native
+ fallback branch, where Soup must avoid its custom Function.
"""
def test_every_resident_4bit_call_takes_the_dequant_fallback(self, tmp_path):
@@ -289,10 +285,8 @@ class TestFixtureIsOutsideTheFusedKernelWindow:
)
assert counts["fallback"] == counts["total"], (
f"{counts['total'] - counts['fallback']} of {counts['total']} resident "
- "4-bit calls took the FUSED kernel at the token count the CUDA gates use. "
- "Real models never take that branch, so the gate would be pinning a path "
- "no user runs — and the streamed arm, which always dequantises, differs "
- "from it by one bf16 ulp. Raise the fixture's sequence length."
+ "4-bit calls took the custom GEMM at the training-shape control. "
+ "Update the #842 fused/fallback matrix for this bitsandbytes dispatch."
)