Publish Packed binary and ternary weight-aware classifiers
Browse files- README.md +43 -0
- binary_qat.safetensors +3 -0
- binary_weights.npz +3 -0
- evaluation.json +31 -0
- fp32.safetensors +3 -0
- source/app.py +78 -0
- source/model.py +49 -0
- source/packing.py +49 -0
- source/requirements.txt +8 -0
- source/train.py +245 -0
- ternary_qat.safetensors +3 -0
README.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
tags:
|
| 4 |
+
- quantization
|
| 5 |
+
- binary-neural-network
|
| 6 |
+
- ternary-weights
|
| 7 |
+
- knowledge-distillation
|
| 8 |
+
- gradio
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# BitForge 1-bit
|
| 12 |
+
|
| 13 |
+
BitForge trains and compares a full-precision digit classifier, a strict one-bit
|
| 14 |
+
weight model, and a ternary-weight model. The low-bit students use straight-through
|
| 15 |
+
quantization during training and learn from both labels and the full-precision
|
| 16 |
+
teacher's softened output distribution.
|
| 17 |
+
|
| 18 |
+
The binary deployment artifact stores each matrix weight as one packed sign bit,
|
| 19 |
+
plus one floating-point scale per output channel and floating-point biases. The
|
| 20 |
+
project reports both classification accuracy and the measured inference payload.
|
| 21 |
+
Activations, scales, and biases remain floating point, so this is specifically a
|
| 22 |
+
one-bit **matrix-weight** experiment rather than a claim that every operation or
|
| 23 |
+
parameter is one bit.
|
| 24 |
+
|
| 25 |
+
## Verified results
|
| 26 |
+
|
| 27 |
+
| Variant | Test accuracy | Accuracy change |
|
| 28 |
+
| --- | ---: | ---: |
|
| 29 |
+
| FP32 teacher | 95.78% | reference |
|
| 30 |
+
| Packed binary matrix weights | 94.22% | -1.56 points |
|
| 31 |
+
| Ternary matrix weights | 95.11% | -0.67 points |
|
| 32 |
+
|
| 33 |
+
Each network has 4,810 parameters, including 4,736 matrix weights. The measured
|
| 34 |
+
inference payload fell from 19,240 bytes for FP32 parameters to 1,184 bytes for
|
| 35 |
+
packed signs, per-channel scales, and biases, a 16.25 times reduction. The `.npz`
|
| 36 |
+
container itself is 3,270 bytes because it also carries names, shapes, and archive
|
| 37 |
+
metadata. An independent reload of the packed signs reproduced 94.22% accuracy.
|
| 38 |
+
|
| 39 |
+
## Reproduce
|
| 40 |
+
|
| 41 |
+
```powershell
|
| 42 |
+
uv run python projects/bitforge-1bit/train.py
|
| 43 |
+
```
|
binary_qat.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7257b7ba4b3ea3a1507ebaf0b7880ddcedafa55ff86b92e0cea58aaaf8b49f6d
|
| 3 |
+
size 19544
|
binary_weights.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ecba90c176dce2c19d17f1db3c30f69addc132f52a6302a60f63ea4aec6e859a
|
| 3 |
+
size 3270
|
evaluation.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"benchmark": "BitForge 1-bit",
|
| 3 |
+
"parameters_per_variant": 4810,
|
| 4 |
+
"matrix_weight_count": 4736,
|
| 5 |
+
"test": {
|
| 6 |
+
"fp32": {
|
| 7 |
+
"accuracy": 0.9577777777777777,
|
| 8 |
+
"cross_entropy": 0.1542476937174797
|
| 9 |
+
},
|
| 10 |
+
"binary_weight": {
|
| 11 |
+
"accuracy": 0.9422222222222222,
|
| 12 |
+
"cross_entropy": 0.2073044627904892
|
| 13 |
+
},
|
| 14 |
+
"ternary_weight": {
|
| 15 |
+
"accuracy": 0.9511111111111111,
|
| 16 |
+
"cross_entropy": 0.19603287428617477
|
| 17 |
+
}
|
| 18 |
+
},
|
| 19 |
+
"storage": {
|
| 20 |
+
"fp32_parameter_payload_bytes": 19240,
|
| 21 |
+
"packed_payload_bytes": 1184,
|
| 22 |
+
"container_bytes": 3270,
|
| 23 |
+
"measured_payload_compression": 16.25
|
| 24 |
+
},
|
| 25 |
+
"precision_boundary": {
|
| 26 |
+
"matrix_weights": "one packed bit in binary variant",
|
| 27 |
+
"scales": "float32 per output channel",
|
| 28 |
+
"biases": "float32",
|
| 29 |
+
"activations": "float32"
|
| 30 |
+
}
|
| 31 |
+
}
|
fp32.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:304f27de63d3ff5669b8edc61eb1c0d2e01c967882c6a78b7a6bc6b4747f4a2f
|
| 3 |
+
size 19544
|
source/app.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import numpy as np
|
| 7 |
+
import plotly.graph_objects as go
|
| 8 |
+
import torch
|
| 9 |
+
from model import BitMLP
|
| 10 |
+
from packing import load_binary_model
|
| 11 |
+
from safetensors.torch import load_file
|
| 12 |
+
from sklearn.datasets import load_digits
|
| 13 |
+
|
| 14 |
+
ARTIFACT_DIR = Path(__file__).resolve().parent / "artifacts" / "bitforge-1bit"
|
| 15 |
+
FP32 = BitMLP("fp32")
|
| 16 |
+
FP32.load_state_dict(load_file(ARTIFACT_DIR / "fp32.safetensors"))
|
| 17 |
+
BINARY = load_binary_model(ARTIFACT_DIR / "binary_weights.npz")
|
| 18 |
+
TERNARY = BitMLP("ternary")
|
| 19 |
+
TERNARY.load_state_dict(load_file(ARTIFACT_DIR / "ternary_qat.safetensors"))
|
| 20 |
+
for model in [FP32, BINARY, TERNARY]:
|
| 21 |
+
model.eval()
|
| 22 |
+
DIGITS = load_digits()
|
| 23 |
+
IMAGES = (DIGITS.images / 16.0).astype(np.float32)
|
| 24 |
+
LABELS = DIGITS.target
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def compare(index: int) -> tuple[go.Figure, dict]:
|
| 28 |
+
index = int(index) % len(IMAGES)
|
| 29 |
+
image = torch.from_numpy(IMAGES[index][None])
|
| 30 |
+
predictions = {}
|
| 31 |
+
with torch.inference_mode():
|
| 32 |
+
for name, model in [
|
| 33 |
+
("FP32", FP32),
|
| 34 |
+
("Binary packed", BINARY),
|
| 35 |
+
("Ternary", TERNARY),
|
| 36 |
+
]:
|
| 37 |
+
predictions[name] = torch.softmax(model(image), dim=1).numpy()[0]
|
| 38 |
+
figure = go.Figure()
|
| 39 |
+
for name, probabilities in predictions.items():
|
| 40 |
+
figure.add_trace(
|
| 41 |
+
go.Bar(
|
| 42 |
+
name=name,
|
| 43 |
+
x=list(range(10)),
|
| 44 |
+
y=probabilities,
|
| 45 |
+
)
|
| 46 |
+
)
|
| 47 |
+
figure.update_layout(
|
| 48 |
+
title=f"Digit {int(LABELS[index])}: precision variants",
|
| 49 |
+
xaxis_title="Predicted class",
|
| 50 |
+
yaxis_title="Probability",
|
| 51 |
+
barmode="group",
|
| 52 |
+
template="plotly_dark",
|
| 53 |
+
)
|
| 54 |
+
return figure, {
|
| 55 |
+
name: {
|
| 56 |
+
"prediction": int(values.argmax()),
|
| 57 |
+
"confidence": round(float(values.max()), 4),
|
| 58 |
+
}
|
| 59 |
+
for name, values in predictions.items()
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
with gr.Blocks(title="BitForge 1-bit") as demo:
|
| 64 |
+
gr.Markdown(
|
| 65 |
+
"# BitForge 1-bit\n"
|
| 66 |
+
"Compare full-precision, packed one-bit matrix weights, and ternary weights "
|
| 67 |
+
"on the same digit."
|
| 68 |
+
)
|
| 69 |
+
index = gr.Slider(0, len(IMAGES) - 1, 0, step=1, label="Digit sample")
|
| 70 |
+
run = gr.Button("Compare precision", variant="primary")
|
| 71 |
+
chart = gr.Plot()
|
| 72 |
+
results = gr.JSON()
|
| 73 |
+
run.click(compare, index, [chart, results])
|
| 74 |
+
demo.load(compare, index, [chart, results])
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
demo.launch()
|
source/model.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def binary_weight(weight: torch.Tensor) -> torch.Tensor:
|
| 9 |
+
scale = weight.abs().mean(dim=1, keepdim=True).clamp_min(1e-6)
|
| 10 |
+
quantized = scale * torch.where(weight >= 0, 1.0, -1.0)
|
| 11 |
+
return weight + (quantized - weight).detach()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def ternary_weight(weight: torch.Tensor) -> torch.Tensor:
|
| 15 |
+
scale = weight.abs().mean(dim=1, keepdim=True).clamp_min(1e-6)
|
| 16 |
+
normalized = weight / scale
|
| 17 |
+
quantized = scale * normalized.round().clamp(-1, 1)
|
| 18 |
+
return weight + (quantized - weight).detach()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class QuantizedLinear(nn.Linear):
|
| 22 |
+
def __init__(self, *args, bits: str = "fp32", **kwargs) -> None:
|
| 23 |
+
super().__init__(*args, **kwargs)
|
| 24 |
+
self.bits = bits
|
| 25 |
+
|
| 26 |
+
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
|
| 27 |
+
if self.bits == "binary":
|
| 28 |
+
weight = binary_weight(self.weight)
|
| 29 |
+
elif self.bits == "ternary":
|
| 30 |
+
weight = ternary_weight(self.weight)
|
| 31 |
+
else:
|
| 32 |
+
weight = self.weight
|
| 33 |
+
return F.linear(inputs, weight, self.bias)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class BitMLP(nn.Module):
|
| 37 |
+
def __init__(self, bits: str = "fp32") -> None:
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.bits = bits
|
| 40 |
+
self.hidden = QuantizedLinear(64, 64, bits=bits)
|
| 41 |
+
self.output = QuantizedLinear(64, 10, bits=bits)
|
| 42 |
+
|
| 43 |
+
def forward(self, images: torch.Tensor) -> torch.Tensor:
|
| 44 |
+
flattened = images.flatten(1)
|
| 45 |
+
return self.output(F.gelu(self.hidden(flattened)))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def parameter_count(module: nn.Module) -> int:
|
| 49 |
+
return sum(parameter.numel() for parameter in module.parameters())
|
source/packing.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from model import BitMLP
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def pack_binary_model(model: BitMLP, destination: Path) -> dict:
|
| 11 |
+
payload = {}
|
| 12 |
+
payload_bytes = 0
|
| 13 |
+
for name in ["hidden", "output"]:
|
| 14 |
+
layer = getattr(model, name)
|
| 15 |
+
weight = layer.weight.detach().cpu().numpy()
|
| 16 |
+
scales = np.mean(np.abs(weight), axis=1).astype(np.float32)
|
| 17 |
+
signs = np.packbits((weight >= 0).reshape(-1), bitorder="little")
|
| 18 |
+
shape = np.asarray(weight.shape, dtype=np.int32)
|
| 19 |
+
bias = layer.bias.detach().cpu().numpy().astype(np.float32)
|
| 20 |
+
payload[f"{name}_signs"] = signs
|
| 21 |
+
payload[f"{name}_scales"] = scales
|
| 22 |
+
payload[f"{name}_shape"] = shape
|
| 23 |
+
payload[f"{name}_bias"] = bias
|
| 24 |
+
payload_bytes += signs.nbytes + scales.nbytes + bias.nbytes
|
| 25 |
+
np.savez(destination, **payload)
|
| 26 |
+
return {
|
| 27 |
+
"packed_payload_bytes": int(payload_bytes),
|
| 28 |
+
"container_bytes": int(destination.stat().st_size),
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_binary_model(source: Path) -> BitMLP:
|
| 33 |
+
packed = np.load(source)
|
| 34 |
+
model = BitMLP(bits="binary")
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
for name in ["hidden", "output"]:
|
| 37 |
+
layer = getattr(model, name)
|
| 38 |
+
shape = tuple(packed[f"{name}_shape"].astype(int))
|
| 39 |
+
total = int(np.prod(shape))
|
| 40 |
+
bits = np.unpackbits(
|
| 41 |
+
packed[f"{name}_signs"], bitorder="little"
|
| 42 |
+
)[:total]
|
| 43 |
+
signs = np.where(bits.reshape(shape) == 1, 1.0, -1.0)
|
| 44 |
+
scales = packed[f"{name}_scales"][:, None]
|
| 45 |
+
layer.weight.copy_(
|
| 46 |
+
torch.from_numpy((signs * scales).astype(np.float32))
|
| 47 |
+
)
|
| 48 |
+
layer.bias.copy_(torch.from_numpy(packed[f"{name}_bias"]))
|
| 49 |
+
return model
|
source/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=5,<7
|
| 2 |
+
numpy>=2,<3
|
| 3 |
+
pandas>=2.3,<4
|
| 4 |
+
plotly>=6,<7
|
| 5 |
+
pyarrow>=21,<24
|
| 6 |
+
safetensors>=0.6,<1
|
| 7 |
+
scikit-learn>=1.7,<2
|
| 8 |
+
torch>=2.7,<3
|
source/train.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
import trackio
|
| 11 |
+
from model import BitMLP, parameter_count
|
| 12 |
+
from packing import pack_binary_model
|
| 13 |
+
from safetensors.torch import save_file
|
| 14 |
+
from sklearn.datasets import load_digits
|
| 15 |
+
from sklearn.model_selection import train_test_split
|
| 16 |
+
from torch import nn
|
| 17 |
+
from torch.nn import functional as F
|
| 18 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 19 |
+
|
| 20 |
+
PROJECT_DIR = Path(__file__).resolve().parent
|
| 21 |
+
ARTIFACT_DIR = PROJECT_DIR / "artifacts" / "bitforge-1bit"
|
| 22 |
+
DATA_DIR = PROJECT_DIR / "data"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def seed_everything(seed: int) -> None:
|
| 26 |
+
np.random.seed(seed)
|
| 27 |
+
torch.manual_seed(seed)
|
| 28 |
+
torch.set_num_threads(1)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def make_loader(
|
| 32 |
+
images: np.ndarray,
|
| 33 |
+
labels: np.ndarray,
|
| 34 |
+
*,
|
| 35 |
+
shuffle: bool,
|
| 36 |
+
seed: int,
|
| 37 |
+
) -> DataLoader:
|
| 38 |
+
return DataLoader(
|
| 39 |
+
TensorDataset(
|
| 40 |
+
torch.from_numpy(images.astype(np.float32)),
|
| 41 |
+
torch.from_numpy(labels.astype(np.int64)),
|
| 42 |
+
),
|
| 43 |
+
batch_size=256,
|
| 44 |
+
shuffle=shuffle,
|
| 45 |
+
generator=torch.Generator().manual_seed(seed),
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@torch.inference_mode()
|
| 50 |
+
def evaluate(model: nn.Module, loader: DataLoader) -> dict:
|
| 51 |
+
model.eval()
|
| 52 |
+
correct = 0
|
| 53 |
+
total = 0
|
| 54 |
+
losses = []
|
| 55 |
+
for images, labels in loader:
|
| 56 |
+
logits = model(images)
|
| 57 |
+
losses.append(float(F.cross_entropy(logits, labels)))
|
| 58 |
+
correct += int((logits.argmax(1) == labels).sum())
|
| 59 |
+
total += len(labels)
|
| 60 |
+
return {"accuracy": correct / total, "cross_entropy": float(np.mean(losses))}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def train_teacher(
|
| 64 |
+
model: BitMLP, train_loader: DataLoader, validation_loader: DataLoader
|
| 65 |
+
) -> BitMLP:
|
| 66 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-4)
|
| 67 |
+
best = copy.deepcopy(model.state_dict())
|
| 68 |
+
best_accuracy = 0.0
|
| 69 |
+
for epoch in range(1, 101):
|
| 70 |
+
model.train()
|
| 71 |
+
for images, labels in train_loader:
|
| 72 |
+
loss = F.cross_entropy(model(images), labels)
|
| 73 |
+
optimizer.zero_grad()
|
| 74 |
+
loss.backward()
|
| 75 |
+
optimizer.step()
|
| 76 |
+
if epoch % 5 == 0:
|
| 77 |
+
validation = evaluate(model, validation_loader)
|
| 78 |
+
trackio.log(
|
| 79 |
+
{
|
| 80 |
+
"teacher_epoch": epoch,
|
| 81 |
+
"teacher_validation_accuracy": validation["accuracy"],
|
| 82 |
+
}
|
| 83 |
+
)
|
| 84 |
+
if validation["accuracy"] > best_accuracy:
|
| 85 |
+
best_accuracy = validation["accuracy"]
|
| 86 |
+
best = copy.deepcopy(model.state_dict())
|
| 87 |
+
model.load_state_dict(best)
|
| 88 |
+
return model
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def train_student(
|
| 92 |
+
name: str,
|
| 93 |
+
model: BitMLP,
|
| 94 |
+
teacher: BitMLP,
|
| 95 |
+
train_loader: DataLoader,
|
| 96 |
+
validation_loader: DataLoader,
|
| 97 |
+
) -> BitMLP:
|
| 98 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1.5e-3, weight_decay=2e-5)
|
| 99 |
+
best = copy.deepcopy(model.state_dict())
|
| 100 |
+
best_accuracy = 0.0
|
| 101 |
+
temperature = 2.5
|
| 102 |
+
teacher.eval()
|
| 103 |
+
for epoch in range(1, 151):
|
| 104 |
+
model.train()
|
| 105 |
+
for images, labels in train_loader:
|
| 106 |
+
logits = model(images)
|
| 107 |
+
with torch.no_grad():
|
| 108 |
+
teacher_logits = teacher(images)
|
| 109 |
+
hard = F.cross_entropy(logits, labels)
|
| 110 |
+
soft = F.kl_div(
|
| 111 |
+
F.log_softmax(logits / temperature, dim=1),
|
| 112 |
+
F.softmax(teacher_logits / temperature, dim=1),
|
| 113 |
+
reduction="batchmean",
|
| 114 |
+
) * temperature**2
|
| 115 |
+
loss = 0.45 * hard + 0.55 * soft
|
| 116 |
+
optimizer.zero_grad()
|
| 117 |
+
loss.backward()
|
| 118 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 119 |
+
optimizer.step()
|
| 120 |
+
if epoch % 5 == 0:
|
| 121 |
+
validation = evaluate(model, validation_loader)
|
| 122 |
+
trackio.log(
|
| 123 |
+
{
|
| 124 |
+
f"{name}_epoch": epoch,
|
| 125 |
+
f"{name}_validation_accuracy": validation["accuracy"],
|
| 126 |
+
}
|
| 127 |
+
)
|
| 128 |
+
if validation["accuracy"] > best_accuracy:
|
| 129 |
+
best_accuracy = validation["accuracy"]
|
| 130 |
+
best = copy.deepcopy(model.state_dict())
|
| 131 |
+
model.load_state_dict(best)
|
| 132 |
+
return model
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def main() -> None:
|
| 136 |
+
seed_everything(2043)
|
| 137 |
+
digits = load_digits()
|
| 138 |
+
images = (digits.images / 16.0).astype(np.float32)
|
| 139 |
+
labels = digits.target.astype(np.int64)
|
| 140 |
+
indices = np.arange(len(images))
|
| 141 |
+
train_indices, test_indices = train_test_split(
|
| 142 |
+
indices, test_size=0.25, random_state=2043, stratify=labels
|
| 143 |
+
)
|
| 144 |
+
train_indices, validation_indices = train_test_split(
|
| 145 |
+
train_indices,
|
| 146 |
+
test_size=0.18,
|
| 147 |
+
random_state=3043,
|
| 148 |
+
stratify=labels[train_indices],
|
| 149 |
+
)
|
| 150 |
+
train_loader = make_loader(
|
| 151 |
+
images[train_indices], labels[train_indices], shuffle=True, seed=2043
|
| 152 |
+
)
|
| 153 |
+
validation_loader = make_loader(
|
| 154 |
+
images[validation_indices],
|
| 155 |
+
labels[validation_indices],
|
| 156 |
+
shuffle=False,
|
| 157 |
+
seed=3043,
|
| 158 |
+
)
|
| 159 |
+
test_loader = make_loader(
|
| 160 |
+
images[test_indices], labels[test_indices], shuffle=False, seed=4043
|
| 161 |
+
)
|
| 162 |
+
teacher = BitMLP("fp32")
|
| 163 |
+
binary = BitMLP("binary")
|
| 164 |
+
ternary = BitMLP("ternary")
|
| 165 |
+
trackio.init(
|
| 166 |
+
project="bitforge-1bit",
|
| 167 |
+
name="binary-ternary-distillation-v1",
|
| 168 |
+
config={
|
| 169 |
+
"parameters_per_variant": parameter_count(teacher),
|
| 170 |
+
"teacher_epochs": 100,
|
| 171 |
+
"student_epochs": 150,
|
| 172 |
+
"binary_matrix_weight_bits": 1,
|
| 173 |
+
},
|
| 174 |
+
)
|
| 175 |
+
teacher = train_teacher(teacher, train_loader, validation_loader)
|
| 176 |
+
binary = train_student(
|
| 177 |
+
"binary", binary, teacher, train_loader, validation_loader
|
| 178 |
+
)
|
| 179 |
+
ternary = train_student(
|
| 180 |
+
"ternary", ternary, teacher, train_loader, validation_loader
|
| 181 |
+
)
|
| 182 |
+
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
|
| 183 |
+
save_file(teacher.state_dict(), ARTIFACT_DIR / "fp32.safetensors")
|
| 184 |
+
save_file(binary.state_dict(), ARTIFACT_DIR / "binary_qat.safetensors")
|
| 185 |
+
save_file(ternary.state_dict(), ARTIFACT_DIR / "ternary_qat.safetensors")
|
| 186 |
+
packing = pack_binary_model(binary, ARTIFACT_DIR / "binary_weights.npz")
|
| 187 |
+
fp32_payload_bytes = parameter_count(teacher) * 4
|
| 188 |
+
results = {
|
| 189 |
+
"benchmark": "BitForge 1-bit",
|
| 190 |
+
"parameters_per_variant": parameter_count(teacher),
|
| 191 |
+
"matrix_weight_count": int(
|
| 192 |
+
teacher.hidden.weight.numel() + teacher.output.weight.numel()
|
| 193 |
+
),
|
| 194 |
+
"test": {
|
| 195 |
+
"fp32": evaluate(teacher, test_loader),
|
| 196 |
+
"binary_weight": evaluate(binary, test_loader),
|
| 197 |
+
"ternary_weight": evaluate(ternary, test_loader),
|
| 198 |
+
},
|
| 199 |
+
"storage": {
|
| 200 |
+
"fp32_parameter_payload_bytes": fp32_payload_bytes,
|
| 201 |
+
**packing,
|
| 202 |
+
"measured_payload_compression": fp32_payload_bytes
|
| 203 |
+
/ packing["packed_payload_bytes"],
|
| 204 |
+
},
|
| 205 |
+
"precision_boundary": {
|
| 206 |
+
"matrix_weights": "one packed bit in binary variant",
|
| 207 |
+
"scales": "float32 per output channel",
|
| 208 |
+
"biases": "float32",
|
| 209 |
+
"activations": "float32",
|
| 210 |
+
},
|
| 211 |
+
}
|
| 212 |
+
(ARTIFACT_DIR / "evaluation.json").write_text(
|
| 213 |
+
json.dumps(results, indent=2), encoding="utf-8"
|
| 214 |
+
)
|
| 215 |
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 216 |
+
pd.DataFrame(
|
| 217 |
+
{
|
| 218 |
+
"source_index": indices,
|
| 219 |
+
"label": labels,
|
| 220 |
+
"split": np.select(
|
| 221 |
+
[
|
| 222 |
+
np.isin(indices, train_indices),
|
| 223 |
+
np.isin(indices, validation_indices),
|
| 224 |
+
],
|
| 225 |
+
["train", "validation"],
|
| 226 |
+
default="test",
|
| 227 |
+
),
|
| 228 |
+
}
|
| 229 |
+
).to_parquet(DATA_DIR / "split_manifest.parquet", index=False)
|
| 230 |
+
trackio.log(
|
| 231 |
+
{
|
| 232 |
+
"fp32_test_accuracy": results["test"]["fp32"]["accuracy"],
|
| 233 |
+
"binary_test_accuracy": results["test"]["binary_weight"]["accuracy"],
|
| 234 |
+
"ternary_test_accuracy": results["test"]["ternary_weight"]["accuracy"],
|
| 235 |
+
"binary_payload_compression": results["storage"][
|
| 236 |
+
"measured_payload_compression"
|
| 237 |
+
],
|
| 238 |
+
}
|
| 239 |
+
)
|
| 240 |
+
trackio.finish()
|
| 241 |
+
print(json.dumps(results, indent=2))
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
if __name__ == "__main__":
|
| 245 |
+
main()
|
ternary_qat.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4634446de7d3594a2f47ef0eb296852fd03ee2a39b43f3f6cfdceb356189cc5d
|
| 3 |
+
size 19544
|