Skip to content

Commit b262680

Browse files
MekkCybershumingmashumingmaSunMarc
authored
Add Bitnet model (#37742)
* Adding BitNet b1.58 Model * Add testing code for BitNet * Fix format issues * Fix docstring format issues * Fix docstring * Fix docstring * Fix: weight back to uint8 * Fix * Fix format issues * Remove copy comments * Add model link to the docstring * Fix: set tie_word_embeddings default to false * Update * Generate modeling file * Change config name for automatically generating modeling file. * Generate modeling file * Fix class name * Change testing branch * Remove unused param * Fix config docstring * Add docstring for BitNetQuantConfig. * Fix docstring * Update docs/source/en/model_doc/bitnet.md Co-authored-by: Mohamed Mekkouri <[email protected]> * Update docs/source/en/model_doc/bitnet.md Co-authored-by: Marc Sun <[email protected]> * Update bitnet config * Update explanation between online and offline mode * Remove space * revert changes * more revert * spaces * update * fix-copies * doc fix * fix minor nits * empty * small nit * empty --------- Co-authored-by: Shuming Ma <[email protected]> Co-authored-by: shumingma <[email protected]> Co-authored-by: Marc Sun <[email protected]>
1 parent 82862ce commit b262680

File tree

19 files changed

+1709
-19
lines changed

19 files changed

+1709
-19
lines changed

docs/source/en/_toctree.yml

+2
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,8 @@
385385
title: BigBirdPegasus
386386
- local: model_doc/biogpt
387387
title: BioGpt
388+
- local: model_doc/bitnet
389+
title: BitNet
388390
- local: model_doc/blenderbot
389391
title: Blenderbot
390392
- local: model_doc/blenderbot-small

docs/source/en/main_classes/quantization.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,9 @@ Learn how to quantize models in the [Quantization](../quantization) guide.
7777

7878
[[autodoc]] TorchAoConfig
7979

80-
## BitNetConfig
80+
## BitNetQuantConfig
8181

82-
[[autodoc]] BitNetConfig
82+
[[autodoc]] BitNetQuantConfig
8383

8484
## SpQRConfig
8585

docs/source/en/model_doc/bitnet.md

+121
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
<!--Copyright 2025 The BitNet Team and The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
12+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13+
rendered properly in your Markdown viewer.
14+
15+
-->
16+
17+
# BitNet
18+
19+
## Overview
20+
21+
Trained on a corpus of 4 trillion tokens, this model demonstrates that native 1-bit LLMs can achieve performance comparable to leading open-weight, full-precision models of similar size, while offering substantial advantages in computational efficiency (memory, energy, latency).
22+
23+
➡️ **Technical Report:** [BitNet b1.58 2B4T Technical Report](https://arxiv.org/abs/2504.12285)
24+
25+
➡️ **Official Inference Code:** [microsoft/BitNet (bitnet.cpp)](https://github.com/microsoft/BitNet)
26+
27+
## Model Variants
28+
29+
Several versions of the model weights are available on Hugging Face:
30+
31+
* [**`microsoft/bitnet-b1.58-2B-4T`**](https://huggingface.co/microsoft/bitnet-b1.58-2B-4T): Contains the packed 1.58-bit weights optimized for efficient inference. **Use this for deployment.**
32+
33+
* [**`microsoft/bitnet-b1.58-2B-4T-bf16`**](https://huggingface.co/microsoft/bitnet-b1.58-2B-4T-bf16): Contains the master weights in BF16 format. **Use this only for training or fine-tuning purposes.**
34+
35+
* [**`microsoft/bitnet-b1.58-2B-4T-gguf`**](https://huggingface.co/microsoft/bitnet-b1.58-2B-4T-gguf): Contains the model weights in GGUF format, compatible with the `bitnet.cpp` library for CPU inference.
36+
37+
38+
### Model Details
39+
40+
41+
* **Architecture:** Transformer-based, modified with `BitLinear` layers (BitNet framework).
42+
* Uses Rotary Position Embeddings (RoPE).
43+
* Uses squared ReLU (ReLU²) activation in FFN layers.
44+
* Employs [`subln`](https://proceedings.mlr.press/v202/wang23u.html) normalization.
45+
* No bias terms in linear or normalization layers.
46+
* **Quantization:** Native 1.58-bit weights and 8-bit activations (W1.58A8).
47+
* Weights are quantized to ternary values {-1, 0, +1} using absmean quantization during the forward pass.
48+
* Activations are quantized to 8-bit integers using absmax quantization (per-token).
49+
* **Crucially, the model was *trained from scratch* with this quantization scheme, not post-training quantized.**
50+
* **Parameters:** ~2 Billion
51+
* **Training Tokens:** 4 Trillion
52+
* **Context Length:** Maximum sequence length of **4096 tokens**.
53+
* *Recommendation:* For optimal performance on tasks requiring very long contexts (beyond the pre-training length or for specialized long-reasoning tasks), we recommend performing intermediate long-sequence adaptation/training before the final fine-tuning stage.
54+
* **Training Stages:**
55+
1. **Pre-training:** Large-scale training on public text/code and synthetic math data using a two-stage learning rate and weight decay schedule.
56+
2. **Supervised Fine-tuning (SFT):** Fine-tuned on instruction-following and conversational datasets using sum loss aggregation and specific hyperparameter tuning.
57+
3. **Direct Preference Optimization (DPO):** Aligned with human preferences using preference pairs.
58+
* **Tokenizer:** LLaMA 3 Tokenizer (vocab size: 128,256).
59+
60+
61+
## Usage tips
62+
63+
64+
**VERY IMPORTANT NOTE ON EFFICIENCY**
65+
66+
> Please do NOT expect performance efficiency gains (in terms of speed, latency, or energy consumption) when using this model with the standard transformers library.
67+
>
68+
> The current execution paths within transformers do not contain the specialized, highly optimized computational kernels required to leverage the advantages of the BitNet architecture. Running the model via transformers will likely result in inference speeds and energy usage comparable to, or potentially worse than, standard full-precision models within this framework on both CPU and GPU.
69+
>
70+
> While you might observe reduced memory usage due to the quantized weights, the primary computational efficiency benefits are not accessible through this standard transformers usage path.
71+
>
72+
> For achieving the efficiency benefits demonstrated in the technical paper, you MUST use the dedicated C++ implementation: [bitnet.cpp](https://github.com/microsoft/BitNet).
73+
74+
### Requirements
75+
76+
```bash
77+
pip install transformers
78+
```
79+
80+
### Example
81+
82+
```python
83+
import torch
84+
from transformers import AutoModelForCausalLM, AutoTokenizer
85+
86+
model_id = "microsoft/bitnet-b1.58-2B-4T"
87+
88+
# Load tokenizer and model
89+
tokenizer = AutoTokenizer.from_pretrained(model_id)
90+
model = AutoModelForCausalLM.from_pretrained(
91+
model_id,
92+
torch_dtype=torch.bfloat16
93+
)
94+
95+
# Apply the chat template
96+
messages = [
97+
{"role": "system", "content": "You are a helpful AI assistant."},
98+
{"role": "user", "content": "How are you?"},
99+
]
100+
chat_input = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
101+
102+
# Generate response
103+
chat_outputs = model.generate(chat_input, max_new_tokens=50)
104+
response = tokenizer.decode(chat_outputs[0][chat_input.shape[-1]:], skip_special_tokens=True) # Decode only the response part
105+
print("\nAssistant Response:", response)
106+
```
107+
108+
109+
## BitNetConfig
110+
111+
[[autodoc]] BitNetConfig
112+
113+
## BitNetModel
114+
115+
[[autodoc]] BitNetModel
116+
- forward
117+
118+
## BitNetForCausalLM
119+
120+
[[autodoc]] BitNetForCausalLM
121+
- forward

src/transformers/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@
261261
"AqlmConfig",
262262
"AutoRoundConfig",
263263
"AwqConfig",
264-
"BitNetConfig",
264+
"BitNetQuantConfig",
265265
"BitsAndBytesConfig",
266266
"CompressedTensorsConfig",
267267
"EetqConfig",
@@ -757,7 +757,7 @@
757757
AqlmConfig,
758758
AutoRoundConfig,
759759
AwqConfig,
760-
BitNetConfig,
760+
BitNetQuantConfig,
761761
BitsAndBytesConfig,
762762
CompressedTensorsConfig,
763763
EetqConfig,

src/transformers/integrations/bitnet.py

+112-8
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,98 @@ def forward(self, input):
190190
return y
191191

192192

193+
class WeightQuant(torch.autograd.Function):
194+
"""
195+
Implements a custom autograd function for weight quantization.
196+
This performs ternary quantization (-1, 0, 1) based on scaling by the
197+
mean absolute value of the weights. It uses the Straight-Through Estimator
198+
(STE) for the backward pass.
199+
"""
200+
201+
@staticmethod
202+
@torch.compile
203+
def forward(ctx, weight):
204+
dtype = weight.dtype
205+
weight = weight.float()
206+
scale = 1.0 / weight.abs().mean().clamp_(min=1e-5)
207+
weight = (weight * scale).round().clamp(-1, 1) / scale
208+
return weight.to(dtype)
209+
210+
@staticmethod
211+
def backward(ctx, grad_output):
212+
grad_input = grad_output.clone()
213+
return grad_input
214+
215+
216+
class ActQuant(torch.autograd.Function):
217+
"""
218+
Implements a custom autograd function for activation quantization.
219+
This performs symmetric 8-bit quantization (to the range [-128, 127])
220+
based on the maximum absolute value along the last dimension (per-token/row scaling).
221+
It uses the Straight-Through Estimator (STE) for the backward pass.
222+
"""
223+
224+
@staticmethod
225+
@torch.compile
226+
def forward(ctx, activation):
227+
dtype = activation.dtype
228+
activation = activation.float()
229+
scale = 127 / activation.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
230+
activation = (activation * scale).round().clamp(-128, 127) / scale
231+
return activation.to(dtype)
232+
233+
@staticmethod
234+
def backward(ctx, grad_output):
235+
grad_input = grad_output.clone()
236+
return grad_input
237+
238+
239+
class AutoBitLinear(nn.Linear):
240+
def __init__(
241+
self,
242+
in_features: int,
243+
out_features: int,
244+
bias: bool = True,
245+
device=None,
246+
dtype=None,
247+
online_quant: bool = False,
248+
):
249+
super().__init__(in_features, out_features, bias)
250+
self.online_quant = online_quant
251+
if not online_quant:
252+
self.register_buffer(
253+
"weight_scale",
254+
torch.ones(
255+
(1),
256+
dtype=dtype,
257+
device=device,
258+
),
259+
)
260+
self._register_load_state_dict_pre_hook(self.load_hook)
261+
262+
def load_hook(
263+
self,
264+
state_dict,
265+
prefix,
266+
*args,
267+
**kwargs,
268+
):
269+
if (prefix + "weight") in state_dict and state_dict[prefix + "weight"].dtype != self.weight.dtype:
270+
state_dict[prefix + "weight"] = unpack_weights(state_dict[prefix + "weight"], dtype=self.weight.dtype)
271+
return state_dict
272+
273+
def forward(self, input):
274+
if self.online_quant:
275+
weight = WeightQuant.apply(self.weight)
276+
else:
277+
weight = self.weight
278+
input = ActQuant.apply(input)
279+
output = F.linear(input, weight, self.bias)
280+
if not self.online_quant:
281+
output = output * self.weight_scale
282+
return output
283+
284+
193285
def _replace_with_bitnet_linear(
194286
model,
195287
modules_to_not_convert=None,
@@ -218,15 +310,27 @@ def _replace_with_bitnet_linear(
218310
if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
219311
in_features = module.in_features
220312
out_features = module.out_features
221-
model._modules[name] = BitLinear(
222-
in_features=in_features,
223-
out_features=out_features,
224-
bias=module.bias is not None,
225-
device=module.weight.device,
226-
dtype=module.weight.dtype,
227-
)
313+
if quantization_config and quantization_config.linear_class == "autobitlinear":
314+
model._modules[name] = AutoBitLinear(
315+
in_features=in_features,
316+
out_features=out_features,
317+
bias=module.bias is not None,
318+
device=module.weight.device,
319+
dtype=module.weight.dtype,
320+
online_quant=(quantization_config.quantization_mode == "online"),
321+
)
322+
if quantization_config.quantization_mode == "offline":
323+
model._modules[name].requires_grad_(False)
324+
else:
325+
model._modules[name] = BitLinear(
326+
in_features=in_features,
327+
out_features=out_features,
328+
bias=module.bias is not None,
329+
device=module.weight.device,
330+
dtype=module.weight.dtype,
331+
)
332+
model._modules[name].requires_grad_(False)
228333
has_been_replaced = True
229-
model._modules[name].requires_grad_(False)
230334

231335
if len(list(module.children())) > 0:
232336
_, has_been_replaced = _replace_with_bitnet_linear(

src/transformers/models/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from .bigbird_pegasus import *
4141
from .biogpt import *
4242
from .bit import *
43+
from .bitnet import *
4344
from .blenderbot import *
4445
from .blenderbot_small import *
4546
from .blip import *

src/transformers/models/auto/configuration_auto.py

+2
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
("bigbird_pegasus", "BigBirdPegasusConfig"),
5151
("biogpt", "BioGptConfig"),
5252
("bit", "BitConfig"),
53+
("bitnet", "BitNetConfig"),
5354
("blenderbot", "BlenderbotConfig"),
5455
("blenderbot-small", "BlenderbotSmallConfig"),
5556
("blip", "BlipConfig"),
@@ -398,6 +399,7 @@
398399
("bigbird_pegasus", "BigBird-Pegasus"),
399400
("biogpt", "BioGpt"),
400401
("bit", "BiT"),
402+
("bitnet", "BitNet"),
401403
("blenderbot", "Blenderbot"),
402404
("blenderbot-small", "BlenderbotSmall"),
403405
("blip", "BLIP"),

src/transformers/models/auto/modeling_auto.py

+2
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
("bigbird_pegasus", "BigBirdPegasusModel"),
5050
("biogpt", "BioGptModel"),
5151
("bit", "BitModel"),
52+
("bitnet", "BitNetModel"),
5253
("blenderbot", "BlenderbotModel"),
5354
("blenderbot-small", "BlenderbotSmallModel"),
5455
("blip", "BlipModel"),
@@ -515,6 +516,7 @@
515516
("big_bird", "BigBirdForCausalLM"),
516517
("bigbird_pegasus", "BigBirdPegasusForCausalLM"),
517518
("biogpt", "BioGptForCausalLM"),
519+
("bitnet", "BitNetForCausalLM"),
518520
("blenderbot", "BlenderbotForCausalLM"),
519521
("blenderbot-small", "BlenderbotSmallForCausalLM"),
520522
("bloom", "BloomForCausalLM"),
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Copyright 2025 The BitNet Team and The HuggingFace Inc. team. All rights reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
from typing import TYPE_CHECKING
15+
16+
from ...utils import _LazyModule
17+
from ...utils.import_utils import define_import_structure
18+
19+
20+
if TYPE_CHECKING:
21+
from .configuration_bitnet import *
22+
from .modeling_bitnet import *
23+
else:
24+
import sys
25+
26+
_file = globals()["__file__"]
27+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)

0 commit comments

Comments
 (0)