Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions examples/01_quant_linear_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ def main() -> None:
print("\n[3] Converted to QuantLinear (BitNet 1.58b {-1, 0, +1}):")
print(f" Packed Buffer : {list(q_ternary.packed_weight.shape)} (4 weights/byte)")
print(
f" Memory Footprint : {mb_t:.2f} MB "
f"({r_t_fp32:.2f}x vs FP32, {r_t_fp16:.2f}x vs FP16)"
f" Memory Footprint : {mb_t:.2f} MB ({r_t_fp32:.2f}x vs FP32, {r_t_fp16:.2f}x vs FP16)"
)

# 3. Ampere 2:4 Structured Sparsity QuantLinear
Expand All @@ -71,8 +70,7 @@ def main() -> None:
print(f" Condensed Buffer : {list(q_sparse.condensed_weight.shape)} (50% non-zeros)")
print(f" Index Metadata : {list(q_sparse.packed_metadata.shape)} (2-bit column nibbles)")
print(
f" Memory Footprint : {mb_s:.2f} MB "
f"({r_s_fp32:.2f}x vs FP32, {r_s_fp16:.2f}x vs FP16)"
f" Memory Footprint : {mb_s:.2f} MB ({r_s_fp32:.2f}x vs FP32, {r_s_fp16:.2f}x vs FP16)"
)

# 4. Verify Forward Pass & Reconstruction SQNR
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "quantbench-engine"
version = "0.1.0"
version = "0.1.1"
description = "First-principles LLM quantization engine, bit-packing runtimes, 2:4 sparsity, and Quality-vs-Speed Pareto evaluation benchmark."
readme = "README.md"
license = "Apache-2.0"
Expand Down
2 changes: 1 addition & 1 deletion src/quantbench/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""quantbench: Unified Quantization Engine, Bit-Packing Runtime & Quality-vs-Speed Benchmark."""

__version__ = "0.1.0"
__version__ = "0.1.1"

from quantbench.bench import ParetoBenchmark, ParetoPoint
from quantbench.eval import (
Expand Down
4 changes: 1 addition & 3 deletions src/quantbench/bench/pareto.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,7 @@ def run_sweep(
stride=self.stride,
)

base_bytes = sum(
p.numel() * 2 for p in self.base_model.parameters()
)
base_bytes = sum(p.numel() * 2 for p in self.base_model.parameters())
base_mb = base_bytes / (1024 * 1024)

points: List[ParetoPoint] = []
Expand Down
8 changes: 2 additions & 6 deletions src/quantbench/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,7 @@ def forward(self, x: torch.Tensor) -> torch.Tensor:
model = DemoTransformer(vocab=vocab_size, dim=hidden_dim)
tokens = generate_synthetic_corpus(vocab_size=vocab_size, seq_length=seq_len, seed=1)

bench = ParetoBenchmark(
base_model=model, test_tokens=tokens, window_size=64, stride=32
)
bench = ParetoBenchmark(base_model=model, test_tokens=tokens, window_size=64, stride=32)
console.print(
"[bold yellow]Running Pareto sweep across all precision runtimes...[/bold yellow]"
)
Expand All @@ -279,9 +277,7 @@ def forward(self, x: torch.Tensor) -> torch.Tensor:
for p in points:
grp = str(p.group_size) if p.group_size > 0 else "None"
delta_str = (
f"+{p.perplexity_delta:.3f}"
if p.perplexity_delta > 0
else f"{p.perplexity_delta:.3f}"
f"+{p.perplexity_delta:.3f}" if p.perplexity_delta > 0 else f"{p.perplexity_delta:.3f}"
)
table.add_row(
p.name,
Expand Down
4 changes: 4 additions & 0 deletions src/quantbench/quant/algorithms/awq.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,13 @@ def search_best_awq_scale(
- best_alpha: Optimal alpha hyperparameter.
"""
if quant_fn is None:

def default_quant(w: torch.Tensor) -> torch.Tensor:
q_b, s_b, zp_b, meta = quantize_blockwise(
w, group_size=min(128, w.shape[1]), num_bits=4
)
return dequantize_blockwise(q_b, s_b, zp_b, meta)

quant_fn = default_quant

# Reference unquantized linear output
Expand Down Expand Up @@ -169,11 +171,13 @@ def awq_quantize_weights(
Tuple of (dequantized_weight, scale).
"""
if quant_fn is None:

def default_quant(w: torch.Tensor) -> torch.Tensor:
q_b, s_b, zp_b, meta = quantize_blockwise(
w, group_size=min(128, w.shape[1]), num_bits=4
)
return dequantize_blockwise(q_b, s_b, zp_b, meta)

quant_fn = default_quant

w_scaled = weight * scale.unsqueeze(0)
Expand Down
4 changes: 1 addition & 3 deletions src/quantbench/quant/algorithms/gptq.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,7 @@ def gptq_quantize_weights(
def quantize_dequantize_cols(col_w: torch.Tensor) -> torch.Tensor:
# col_w: (out_features, num_cols)
if group_size > 0:
q_b, s_b, zp_b, meta = quantize_blockwise(
col_w, group_size=group_size, num_bits=bits
)
q_b, s_b, zp_b, meta = quantize_blockwise(col_w, group_size=group_size, num_bits=bits)
return dequantize_blockwise(q_b, s_b, zp_b, meta)
else:
q, scale = quantize_absmax(col_w, num_bits=bits, dim=0)
Expand Down
7 changes: 1 addition & 6 deletions src/quantbench/quant/packing/sparse_pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,7 @@ def pack_2_4_indices(indices: torch.Tensor) -> torch.Tensor:
idx2 = i32[..., 2::4]
idx3 = i32[..., 3::4]

packed = (
(idx0 & 0x03)
| ((idx1 & 0x03) << 2)
| ((idx2 & 0x03) << 4)
| ((idx3 & 0x03) << 6)
)
packed = (idx0 & 0x03) | ((idx1 & 0x03) << 2) | ((idx2 & 0x03) << 4) | ((idx3 & 0x03) << 6)
return packed.to(torch.uint8)


Expand Down
11 changes: 7 additions & 4 deletions tests/test_packing.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,13 @@ class TestSparse24Packing:

def test_index_packing_roundtrip(self) -> None:
"""Test packing and unpacking of 2-bit column position indices."""
indices = torch.tensor([
[0, 2, 1, 3],
[1, 2, 0, 3],
], dtype=torch.int32)
indices = torch.tensor(
[
[0, 2, 1, 3],
[1, 2, 0, 3],
],
dtype=torch.int32,
)

packed = pack_2_4_indices(indices)
assert packed.dtype == torch.uint8
Expand Down
5 changes: 2 additions & 3 deletions tests/test_primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,8 @@ def test_fp8_analytical_emulator():
# E4M3 (max 448.0)
q_e4m3 = _emulate_fp8(x, exp_bits=4, mantissa_bits=3, bias=7, max_val=448.0)
assert q_e4m3[0].item() == -448.0 # saturated at -max
assert q_e4m3[6].item() == 448.0 # saturated at +max
assert q_e4m3[3].item() == 0.0 # exact zero
assert q_e4m3[6].item() == 448.0 # saturated at +max
assert q_e4m3[3].item() == 0.0 # exact zero

# E5M2 (max 57344.0)
q_e5m2 = _emulate_fp8(x, exp_bits=5, mantissa_bits=2, bias=15, max_val=57344.0)
Expand Down Expand Up @@ -203,4 +203,3 @@ def test_cli_runner():
# Test invalid format
res_err = runner.invoke(app, ["pack-inspect", "--format", "invalid_format"])
assert res_err.exit_code != 0

9 changes: 3 additions & 6 deletions tests/test_quant_linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ def test_int4_blockwise_forward_pass(self) -> None:
in_f, out_f = 64, 128
linear = nn.Linear(in_f, out_f, bias=True)

quant_linear = QuantLinear.from_linear(
linear, scheme="int4", group_size=32, symmetric=True
)
quant_linear = QuantLinear.from_linear(linear, scheme="int4", group_size=32, symmetric=True)

# 128 * 64 = 8192 elements -> 8192 / 32 = 256 blocks of 32 elements
# 32 elements pack into 16 uint8 bytes
Expand All @@ -43,9 +41,7 @@ def test_int4_per_channel_forward_pass(self) -> None:
in_f, out_f = 64, 128
linear = nn.Linear(in_f, out_f, bias=True)

quant_linear = QuantLinear.from_linear(
linear, scheme="int4", group_size=-1, symmetric=True
)
quant_linear = QuantLinear.from_linear(linear, scheme="int4", group_size=-1, symmetric=True)

# Per-channel: (out_f, in_f // 2) = (128, 32)
assert quant_linear.packed_weight.shape == (out_f, in_f // 2)
Expand Down Expand Up @@ -145,6 +141,7 @@ class TestModelConvert:

def test_convert_transformer_mlp_block(self) -> None:
"""Verify recursive conversion swaps targeted linear layers while respecting exclusions."""

class MockTransformerMLP(nn.Module):
def __init__(self, dim: int, hidden_dim: int):
super().__init__()
Expand Down
Loading