Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

bitsandbytes CPU fork — bitsandbytes-cpu-fork

Not upstream bitsandbytes. This is the CPU fork: the CUDA kernels are replaced by a pure-CPU backend, so it runs on ordinary laptops and Mini-PCs with no NVIDIA GPU, no CUDA toolkit and no driver — just an AVX2 x86-64 CPU (or ARM64 NEON), the CPU build of PyTorch, and 12–16 GB of RAM.

Version: 0.50.2.dev9 · import name is unchanged (import bitsandbytes as bnb) · MIT.

What the CPU backend provides: 8-bit blockwise optimizers (≈2.3 bytes of state per parameter instead of 8; the 4-bit optimizer ≈1.03), 4/8-bit layers that run on CPU tensors, the fused Gated DeltaNet kernel for Qwen3-Next / Qwen3.5 linear attention, fused gemm_8bit, fused RMSNorm/SwiGLU, an SSD cold-memory balancer, and a CPU training/concurrency toolbox.


Install

torch is deliberately not a dependency: on PyPI the name torch resolves to the CUDA build, which pulls ~2.5 GB of nvidia-* wheels onto machines with no NVIDIA device. Install the CPU build first, then this fork:

pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install bitsandbytes-cpu-fork
python -m bitsandbytes          # prints version / platform / library info

Requirements: Python ≥ 3.10 (64-bit), PyTorch ≥ 2.0 CPU build, x86-64 with AVX2 (a generic SSE2 fallback is shipped) or ARM64 with NEON, Windows 10/11 or Linux glibc ≥ 2.17.

Wheels and platform support (dev7)

Artifact Platform Parallel Notes
win_amd64.whl Windows 10/11 x64 MSVC OpenMP (bundled) prebuilt DLL, no compiler needed
manylinux_2_17_x86_64.whl Linux, glibc ≥ 2.17 OpenMP (bundled libgomp) portable wheel: AVX2 + generic .so; the bundled AVX-512 .so is single-threaded — set BNB_CPU_DISABLE_AVX512=1 to use the AVX2 OpenMP path
manylinux_2_39_x86_64.whl Linux, glibc ≥ 2.39 OpenMP (native build) native wheel incl. AVX-512/BF16 kernels
sdist any platform with a C++ compiler + OpenMP OpenMP builds csrc locally (aarch64 Linux / Android Termux supported this way)

pip picks the best matching wheel automatically. If your glibc is older than 2.17 (or the platform is not x86-64), install the sdist: pip install --no-binary bitsandbytes-cpu-fork bitsandbytes-cpu-fork.

Verify the install

python -m bitsandbytes          # version, platform, which native library loads
bitsandbytes-cpu detect         # CPU model, cores, SIMD, RAM, recommended thread count
bitsandbytes-cpu doctor         # which .dll/.so will load and which kernel symbols it has
bitsandbytes-cpu selftest       # 4-bit layer + 8-bit optimizer step + GDN kernel
bitsandbytes-cpu help           # full feature reference with runnable examples
bitsandbytes-cpu help 8bitopt   # one section: 8-bit optimizers
bitsandbytes-cpu help 4bit      # one section: 4-bit layers on a CPU
bitsandbytes-cpu help kernels   # one section: fused kernels, called directly

bitsandbytes-cpu is also installed as bnb-cpu.


Quick start

8-bit optimizer (≈2.3 B of state per parameter)

import torch, bitsandbytes as bnb

p = torch.nn.Parameter(torch.randn(1024, 1024))
opt = bnb.optim.AdamW8bit([p], lr=1e-4)
p.grad = torch.randn_like(p)
opt.step()

4-bit optimizer (half the state of 8-bit, ~1.03 B/param)

import torch, bitsandbytes as bnb

p = torch.nn.Parameter(torch.randn(1024, 1024))
opt = bnb.optim.AdamW4bit([p], lr=1e-4)     # fp32 parameters only
p.grad = torch.randn_like(p)
opt.step()
print(opt.state_bytes())                    # ~1.031 bytes per parameter

The 4-bit kernel is scalar (the AVX2 packing was never correct), so it is ~8x slower than the AVX2 8-bit kernel per element — use it to save state memory, not for speed. On wheels without the kernel symbol (Windows) it falls back to torch with the same numbers.

4-bit layer on CPU

import torch, bitsandbytes as bnb

layer = bnb.nn.Linear4bit(1024, 1024, quant_type="nf4", compute_dtype=torch.float32)
layer = layer.to("cpu")      # .to() is what quantises the weights
y = layer(torch.randn(2, 1024))

Fused Gated DeltaNet (Qwen3-Next / Qwen3.5 linear attention)

from bitsandbytes.gdn_cpu import patch_transformers

patched = patch_transformers()   # routes the transformers torch fallback to the fused CPU kernel
# patched == True means the hybrid-attention models now use the fused fwd/bwd kernel
# (transformers 5.x and older models both supported; see docs_cpu/EPYC_VALIDATION.md for HW notes)

EFST — frozen experts + expert LoRA for MoE training

from bitsandbytes.efst import EFSTConfig, apply_efst

cfg = EFSTConfig(
    top_k=2,                                   # keep the 2 hottest experts per layer
    calibration_dataloader=calib_batches,
    calibration_forward_fn=lambda batch: model(**batch),
    lora=True, lora_r=8, lora_alpha=16,        # train LoRA adapters inside the selected experts
)
info = apply_efst(model, cfg)
print(info.summary())                          # expert groups, trainable before/after

Works with classic ModuleList experts and with the fused 3-D tensor experts used by HF transformers 5.x Mixtral / Qwen3-Next (routing-usage calibration included).

Disk load balancer — spill cold tensors to SSD when RAM is tight

import torch
from bitsandbytes.disk_balancer import DiskLoadBalancer, DiskBalancerConfig

bal = DiskLoadBalancer(DiskBalancerConfig(mode="auto"))
bal.start()                                    # picks a safe local SSD cache dir
t = torch.arange(2 * 1024 * 1024, dtype=torch.float32)
bal.put_cold("cold_embeddings", t, tier="ssd")
bal.wait_writes()
back = bal.get_cold_shape("cold_embeddings", t.shape)
bal.cleanup()                                  # deletes only its own cache dir

Safety rules: on Linux/WSL only native ext4/xfs/btrfs are used — 9P host drives (/mnt/[drive]), network filesystems, read-only mounts, tmpfs and / are rejected; explicit unsafe --flash_paths raise. In-flight write bytes are capped (max_inflight_bytes) so offload cannot silently pin source tensors; quota and free-space limits are enforced.

CPU concurrency planner / thread calibration (torch_cpu_kit)

from bitsandbytes import torch_cpu_kit as tck

plan = tck.plan_concurrency_for_training(
    800_000_000, mode="lora", trainable_fraction=0.005, activation_gb=0.5)
print(plan["advice"])        # e.g. "3 job(s) x 2 thread(s) each ..."
print(plan["env"])           # OMP/MKL env for each job

# Measured on a real step, not guessed (hybrid-attention models often prefer fewer threads):
best = tck.tune_threads(lambda: train_step(model, batch))

Also: estimate_training_memory_gb(), spawn_training_jobs(cmds, plan) (logs prefixed [jobN]), apply_env(), init(), mem_report().


What is inside the CPU backend

Area What it does
8-bit optimizers AdamW/Adam/AdEMAMix/LAMB/LARS/Lion + paged variants, blockwise 8-bit state with single-pass dequant→update→requant kernels (AVX2/NEON)
4-bit optimizer AdamW4bit: ≈1.03 bytes of state per parameter (scalar kernel; native on Linux and, since dev9, Windows)
Quantisation blockwise 8-bit, NF4/FP4 4-bit quantize/dequantize; 4-bit GEMV inference kernel
gemm_8bit out = A @ dequant8(B) with weights kept uint8 (¼ DRAM traffic), no fp32 temporary (bnb.functional.fused_dequant_linear_8bit)
GDN fused Gated DeltaNet forward + chunk-checkpointed backward (gdn_fwd_cpu / gdn_bwd_cpu), plus patch_transformers() / patch_fla()
Fused elementwise RMSNorm fwd/bwd, SwiGLU, add-scale, NT-store variants
CPU detection CPUID/XCR0 probe with OS-state checks; the AVX-512 library is only loaded when AVX-512 and BF16 are present, otherwise AVX2 (or the generic zero-AVX artifact)
Tooling torch_cpu_kit, disk_balancer, efst, bitsandbytes-cpu CLI

The library never loads a CUDA/ROCm/XPU library: bnb.cuda/bnb.optim CPU paths work, and import bitsandbytes succeeds on a CPU-only host with no CUDA anywhere.


Full fine-tuning vs LoRA

--mode full (and bnb.optim.* directly) fine-tunes every parameter; measured on Qwen3.5-0.8B (752 M, 100% trainable, fp32 + AdamW8bit, seq 64, batch 1): peak RSS 10.4 GB, 8.8 s/step, versus LoRA (5.4 M trainable) at 5.9 GB / 2.65 s/step. On a 15.4 GB machine ~0.8 B full fine-tuning is comfortable; ~1 B is tight (estimator: 10.7 GB weights+grads+8-bit state before activations), and above that use LoRA / EFST / q3bit, or add activation checkpointing (not yet wired into the generic trainer).

iGPU image inference (experimental)

The OpenCL kit is GEMM-oriented (nn.Linear/Conv1D); diffusion UNets are conv2d-heavy and need an im2col+dGEMM conv engine before the OpenCL path can run them. As a proof of concept, gt1030/igpu_image_ort.py runs an ONNX-exported SD1.5 through ONNX Runtime's DmlExecutionProvider on the integrated GPU (local _sd15_combined, 256x256, DDIM):

path 8 steps per step
CPU diffusers (Torch 2.13, 6 threads) 25.29 s 3.16 s
iGPU ONNX Runtime DirectML 13.05 s 1.63 s

≈1.9x faster at 256x256; 512x512 currently fails inside the UNet on the DML EP (activation memory / operator coverage) while the same ONNX runs on CPUExecutionProvider. Export once with optimum-cli export onnx --task stable-diffusion --opset 17. A diffusers + torch_directml variant (igpu_image_infer.py) is kept as a comparison; it needs legacy attention and still hits DML chunk/reshape issues. Long-term the OpenCL backend gets an fp16 device-resident conv engine: measured probes show per-op OpenCL conv is 2-3x slower than CPU oneDNN and fp32 resident only reaches parity, but fp16 resident im2col+Hgemm is 1.3-2x faster than the CPU conv at SD1.5 shapes (538 vs 342 GFLOPS; 1280-channel 16x16 layer 17.3 vs 34.8 ms). The 256-resolution demo therefore uses DirectML, while the OpenCL engine is the planned production backend.

The fp16 device-resident building blocks are in gt1030/opencl_fp16_ops.py + gt1030/kernels_attention.cl (im2col + CLBlast Hgemm conv, GroupNorm+SiLU, LayerNorm, GEGLU, multi-head attention, nearest-2x upsample, add). Clean measurements on the Vega 6 (no CPU contention), parity 0.02-1.1% relL2: ResNetBlock2D 0.61-0.77x, VAE up-block 0.40x, FFN 0.16-0.23x, attention 0.42-0.99x, full Transformer block 0.51-0.71x of CPU time -- i.e. 1.3-6x faster for most blocks. The VAE decoder is now end-to-end on the iGPU (gt1030/opencl_vae.py): fp16 parity 2.7-3.7% vs CPU, 1.81 s vs 2.07 s at 256 (0.87x), 7.93 s vs 8.34 s at 512 (0.95x, warm). The remaining step is assembling the full 256px UNet graph (fp16 weights ~1.7 GB, under the 5,090 MB single-allocation limit; 512px needs activation tiling).

3-bit frozen base + LoRA (bitsandbytes.q3bit, experimental)

A frozen weight can be stored as blockwise 3-bit codes (≈11% of fp32 memory) and trained through LoRA; the native Linux wheels contain the C dequant / fused-GEMM kernels, other platforms fall back to a pure-torch implementation with identical numbers (slower):

import torch, torch.nn as nn
from bitsandbytes import q3bit

w = torch.randn(1024, 1024)
packed, absmax = q3bit.quantize_3bit(w, block=64)       # 3 bytes per 8 weights
back = q3bit.dequantize_3bit(packed, absmax, w.shape)   # native kernel when available

layer = nn.Linear(1024, 1024)
ql = q3bit.QuantLinear3bit.from_linear(layer, lora_r=8)  # frozen 3-bit base + LoRA
y = ql(torch.randn(2, 1024))                             # only lora_A/lora_B train
print([n for n, p in ql.named_parameters() if p.requires_grad])  # ['lora_A', 'lora_B']

# freeze every Linear in a model at 3 bits (lm_head stays fp32):
q3bit.convert_linears_3bit(model, lora_r=8)

Functions: quantize_3bit / dequantize_3bit / gemm_3bit (A @ dequant(B).T without materialising B) / gemm_3bit_transposed; 2-bit variants are available as quantize_2bit / dequantize_2bit (dequant only). Bits are blockwise symmetric (block=64, one absmax per block) and match the C kernel layout exactly.

Performance notes (measured on this fork's target laptops)

All numbers are from the repodata in bench_results/ and the technical report; hardware: R5-4500U (6C/6T, AVX2, 15.4 GB) / i5-10400 (6C/12T, AVX2, 12 GB), no NVIDIA GPU.

Scenario Result
17M-parameter AdamW8bit step ≈34.7 ms (6 threads) / ≈38.6 ms (1 thread); 7–10 GB/s effective
8-bit vs fp32 optimizer traffic ≈16 B/element vs ≈28 B/element (1.7× less bandwidth)
Concurrency packing (synthetic jobs) 6 jobs × 1 thread 5619 tok/s vs 1 job × 6 threads 3843 tok/s (+46%)
Real model (Qwen3.5-0.8B LoRA, seq 64) 4 threads beat 6 by 7–10% — measure with tune_threads()
Fused lm_head 3-bit GEMM (research) 14–22% faster than fp32 matmul, 89% less weight memory
3-bit frozen base + LoRA (Qwen3-1.7B, CPU) 80 steps: eval loss 4.34 → 4.03; RSS 2.9 GB vs 8.7 GB fp32; step 7.7 s vs 5.5 s (native Windows)
Full-parameter fine-tune (Qwen3.5-0.8B, 752 M, fp32 + AdamW8bit, CPU) 10.4 GB peak RSS, 8.8 s/step; LoRA on the same model: 5.9 GB, 2.65 s/step
AdamW4bit step (1M params) 28.6 ms vs 3.3 ms for the AVX2 8-bit kernel; state 1.031 vs 2.062 B/param

Not every workload is faster than fp32: 4-bit/8-bit kernels trade compute for memory traffic, and small per-layer matmuls are better left to oneDNN. See bench_results/ and the report for the full trade-off tables, including negative results.


Platform limitations

  • CPU only. CUDA/ROCm/XPU kernels are not built; a GPU is never required or used.
  • Windows wheel: from dev9 on it ships the MSVC DLL built by CI from the current csrc, which exports the 2/3-bit dequant/GEMM and 4-bit optimizer kernels; they run natively on Windows (verified: dequant maxdiff 1.2e-6, 4-bit native vs torch 1.2e-7). Wheels older than dev9 fall back to pure torch for those symbols.
  • manylinux_2_17 wheel: the AVX-512 library inside it is single-threaded (the parallel build is only for the native manylinux_2_39 wheel). On AVX-512 machines set BNB_CPU_DISABLE_AVX512=1 to run the AVX2 OpenMP path.
  • aarch64: there is no PyPI wheel yet; build from the sdist (build_linux.sh) or follow the Termux guide TERMUX_GUIDE.md.
  • macOS: no wheel is published and the CPU backend is not tested there; the sdist build may work with clang + OpenMP, but treat it as unsupported.
  • 3-bit (and 2-bit dequant-only) is experimental: the API and kernels are covered by tests, but there is no long-run quality study yet; treat it as a research feature.
  • torch must be installed separately as the CPU build (see above).

Build from source

# Linux (x86-64 AVX2 or aarch64 NEON; g++/clang + OpenMP)
sudo apt install g++ libomp-dev           # Debian/Ubuntu
bash build_linux.sh                       # -> bitsandbytes/libbitsandbytes_cpu.so
bash build_linux.sh --selftest            # also build + run the torch-free C self-test

# Windows (MSVC, manual build, no CMake)
build_manual\build_manual.bat amd         # run inside "x64 Native Tools Command Prompt"

Termux (Android / ARM64)

On-device builds work; there is no aarch64 PyPI wheel, so build from the sdist:

pkg update && pkg install -y clang libomp make python
bash build_termux.sh                 # -> bitsandbytes/libbitsandbytes_cpu.so
bash build_termux.sh --selftest      # also build + run the torch-free C self-test

Three Termux-specific traps the script already handles: the compiler is clang++ (there is no g++), OpenMP needs pkg install libomp, and -march=native is unsafe under Android's clang. The script is also what the automated flow uses to build on a phone driven from a PC over ADB — see TERMUX_GUIDE.md for the phone-side preparation, the ADB/wireless-debugging path, the ARM64 kernel notes and the verification matrix.

Two special wheel builds used by this project are documented in docs_cpu/WHEEL_PLATFORM_NOTES.md: the zig manylinux_2_17 portable build and the devtoolset-8 manylinux_2_17 OpenMP build (build_oldgomp_linux.sh, bundles libgomp).

Tests

bash build_linux.sh --selftest          # C kernels: 9 checks (quantize/gemm_8bit/gemv_4bit/
                                        # AdamW8bit/vector-vs-scalar/2-3bit dequant/fused GEMM)
python test_efst_regressions.py         # EFST: nested blocks, 3-D tensor experts, routing usage
python test_q3bit_kernels.py            # 2/3-bit research prototype (old DLL-based tests)
python test_q3bit_api.py                # public q3bit API: pack/dequant/gemm, QuantLinear3bit, fallback
python test_adamw4bit.py                # restored 4-bit optimizer: state bytes, native vs torch, fp32 tracking
python test_concurrency_plan.py         # planner / memory estimate / tune_threads / launcher
python test_disk_balancer_safety.py     # data-safety rules for the disk balancer

Documentation

The long-form docs live in the repository (bitsandbytes/docs_cpu/, Chinese and English):

Changelog

Version Changes
0.50.2.dev1 First CPU-fork release: AVX2/NEON CPU backend (8-bit optimizers, fused GDN, gemm_8bit, 4/8-bit quantisation)
0.50.2.dev2 AdamW4bit packaged; PyPI release
0.50.2.dev3 README / API reference / summary document the 4-bit optimizer
0.50.2.dev4 Linux wheels (manylinux_2_17 portable + manylinux_2_39 OpenMP); libgcc-free CPUID detection; AVX-512 BF16 loader safety; portability and data-safety fixes
0.50.2.dev5 WSL/Linux disk balancer (ext4-only, 9P rejected, in-flight byte cap); torch_cpu_kit concurrency planner / memory estimator / tune_threads; optional kernels warning fix; EPYC validation docs
0.50.2.dev6 manylinux_2_17 wheel is now OpenMP (devtoolset-8, bundled libgomp → 3–4× optimizer-kernel speedup on old glibc); csrc 2/3-bit dequant + fused GEMM kernels with 9-item C self-test; EFST fused tensor-expert routing fix; GCC 8 <cpuid.h> portability fix
0.50.2.dev7 documentation release: README rewritten for the CPU fork (install/wheels/platform matrix, feature table, measured performance, limitations, tests, full dev1→dev7 changelog, EFST/disk-balancer/toolbox examples)
0.50.2.dev8 restored AdamW4bit (the kernel was dropped when dev4 vendored upstream; now scalar C kernel + torch fallback, 1.031 B/param); new bitsandbytes.q3bit API — quantize_3bit/dequantize_3bit/gemm_3bit/gemm_3bit_transposed, QuantLinear3bit (frozen 3-bit base + LoRA), convert_linears_3bit, native kernels on Linux with identical pure-torch fallback; CLI reference now includes 4bitopt/q3bit and all 43 examples execute in CI-style verification
0.50.2.dev9 Windows native kernels: CI now compiles the MSVC DLL from the current csrc and the export list includes the 4-bit optimizer and 2/3-bit symbols (they were silently missing before); q3bit real-model validation on Qwen3-1.7B (frozen 3-bit base + LoRA, eval 4.34→4.03 over 80 steps, RSS −67%, native step 7.7 s vs fp32 5.5 s); fixed the causal-LM double-shift label bug in the iGPU training kit (Windows package v0.1.2)

License and attribution

bitsandbytes-cpu-fork is MIT licensed, like upstream bitsandbytes (this fork is based on upstream 0.50.2); the CUDA kernels were removed and replaced by the CPU backend described above. See NOTICE.md for details and upstream attribution.

Metadata

Release files for bitsandbytes-cpu-fork 0.50.2.dev10

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bitsandbytes-cpu-fork 0.50.2.dev10
File Size Uploaded Provenance Actions
bitsandbytes_cpu_fork-0.50.2.dev10.tar.gz 946.5 kB Without provenance Details for bitsandbytes_cpu_fork-0.50.2.dev10.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bitsandbytes-cpu-fork 0.50.2.dev10
File Interpreter ABI Platform Actions
bitsandbytes_cpu_fork-0.50.2.dev10-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for bitsandbytes_cpu_fork-0.50.2.dev10-py3-none-win_amd64.whl

Total release size: 1.4 MB

Release files / bitsandbytes_cpu_fork-0.50.2.dev10.tar.gz

Download URL bitsandbytes_cpu_fork-0.50.2.dev10.tar.gz
Size 946.5 kB
Tags Source
SHA-256 checksum
How to use checksums
377925a864dd93e32dd772513c398e4a619dbcbce5807702796eb74262cfac8f
BLAKE2b-256 checksum
How to use checksums
ecf9f8b2d1b1374d4f12262e8eb4a77466f7ce2004a3af029c82a4f641d368c4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.3

Release files / bitsandbytes_cpu_fork-0.50.2.dev10-py3-none-win_amd64.whl

Download URL bitsandbytes_cpu_fork-0.50.2.dev10-py3-none-win_amd64.whl
Size 498.4 kB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
193b518e3533cede6a2dd27c101e8fd2eec770a084c642c13f9cae9477718cd6
BLAKE2b-256 checksum
How to use checksums
057e5ac061397e5e7e7b5700577c680fa65902f27c918862aee67fe4abee96a3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.3

Security for bitsandbytes-cpu-fork 0.50.2.dev10

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page