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
10 changes: 10 additions & 0 deletions DEVLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,13 @@
- Group-wise / block-wise quantization for group sizes $G \in \{32, 64, 128\}$ with arbitrary tensor padding and dequantization reconstruction.
- Bit-level simulation of OCP FP8 E4M3FN (range $\pm 448$, 3 mantissa bits) and E5M2 (range $\pm 57344$, 2 mantissa bits).
- 100% test coverage across mathematical invariants and error bounds.

## 2026-10-26: Phase 2 — Integer Bit-Packing Runtimes (Sub-Byte Storage)

- Implemented vectorized sub-byte bit-packing runtimes in `quantbench.quant.packing`:
- `int4_pack.py`: Vectorized bit-shift packing of two INT4 values (unsigned $[0, 15]$ or signed two's complement $[-8, 7]$) into a single `uint8` byte container: `byte = (v0 & 0x0F) | ((v1 & 0x0F) << 4)`. Full support for odd dimension length padding and exact shape restoration.
- `ternary_pack.py`: BitNet 1.58b packing supporting both hardware-friendly 2-bit SIMD packing (4 weights/byte using biased offset $u = v + 1 \in \{0, 1, 2\}$) and theoretical maximal density Radix-3 base-3 packing (5 weights/byte via $3^5 = 243 < 256$).
- `sparse_pack.py`: NVIDIA Ampere/Ada/Hopper 2:4 structured sparsity layout. Automated row pruning, value condensation to $50\%$ storage ($M, N/2$), and 2-bit metadata column index packing into 4-bit nibbles ($M, N/8$). Decompression scatter preserves exact zeros and non-zero positions.
- Added CLI command `pack-inspect` to visualize sub-byte bit layouts and theoretical memory compression directly from the terminal.
- 22/22 unit tests passing with 93% test coverage in 2.18s. All Ruff checks passing.

15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ Partitions weights into blocks of size $G \in \{32, 64, 128\}$ to isolate channe
### 4. OCP FP8 Emulation
Bit-exact simulation of **E4M3FN** (higher mantissa precision, range $\pm 448$, no infinity) for GEMM weights/activations and **E5M2** (wider dynamic range $\pm 57344$) for gradients and KV caches.

### 5. Sub-Byte Bit-Packing & 2:4 Sparsity
Because hardware cannot address sub-byte boundaries, weights are packed into vectorized `uint8` containers:
* **INT4**: Two 4-bit nibbles packed per byte: `(v0 & 0x0F) | ((v1 & 0x0F) << 4)` ($4\times$ memory compression vs FP16).
* **BitNet Ternary**: Four $\{-1, 0, 1\}$ weights per byte using offset binary mapping ($8\times$ compression vs FP16).
* **2:4 Structured Sparsity**: Two non-zero values retained per 4-element block ($50\%$ storage) with 2-bit column positions packed into 4-bit metadata nibbles for Ampere/Ada/Hopper Sparse Tensor Cores ($2\times$ TFLOPS).

---

## 🚀 Quickstart
Expand All @@ -78,7 +84,12 @@ git clone https://github.com/Prajwal7-2002/quantbench.git
cd quantbench
uv sync

# Run the complete test suite
# Inspect sub-byte bit layouts and theoretical memory compression
uv run quantbench pack-inspect --format int4
uv run quantbench pack-inspect --format ternary
uv run quantbench pack-inspect --format sparse24

# Run the complete test suite (22 tests, 93% coverage)
uv run pytest
```

Expand All @@ -87,7 +98,7 @@ uv run pytest
## 🗺️ Roadmap & Staged Milestones

- [x] **Phase 1: Mathematical Primitives & Invariants**: Affine, AbsMax, Group-wise, and FP8 (E4M3/E5M2) simulation with rigorous error bound verification.
- [ ] **Phase 2: Integer Bit-Packing Runtimes**: Vectorized INT4 nibble packing (`uint8`), BitNet ternary packing, and 2:4 sparsity metadata.
- [x] **Phase 2: Integer Bit-Packing Runtimes**: Vectorized INT4 nibble packing (`uint8`), BitNet ternary packing, and 2:4 sparsity metadata.
- [ ] **Phase 3: Advanced Optimization Algorithms**: SmoothQuant outlier migration, AWQ grid search, and GPTQ second-order Hessian updates.
- [ ] **Phase 4: Drop-in Neural Layers**: `QuantLinear` PyTorch module, in-place Hugging Face model converter, and layer SQNR diagnostics.
- [ ] **Phase 5: Perplexity & Evaluation Engine**: Standardized sliding-window perplexity on WikiText-2 and C4.
Expand Down
18 changes: 18 additions & 0 deletions src/quantbench/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@
)
from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise
from quantbench.quant.fp8 import FP8Format, dequantize_fp8, quantize_fp8
from quantbench.quant.packing import (
decompress_2_4,
pack_2_4_indices,
pack_int4,
pack_ternary,
prune_and_compress_2_4,
unpack_2_4_indices,
unpack_int4,
unpack_ternary,
)

__all__ = [
"__version__",
Expand All @@ -22,4 +32,12 @@
"quantize_fp8",
"dequantize_fp8",
"FP8Format",
"pack_int4",
"unpack_int4",
"pack_ternary",
"unpack_ternary",
"pack_2_4_indices",
"unpack_2_4_indices",
"prune_and_compress_2_4",
"decompress_2_4",
]
89 changes: 89 additions & 0 deletions src/quantbench/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,17 @@

import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

import quantbench
from quantbench.quant.packing import (
pack_int4,
pack_ternary,
prune_and_compress_2_4,
unpack_int4,
unpack_ternary,
)

app = typer.Typer(
name="quantbench",
Expand Down Expand Up @@ -49,6 +57,11 @@ def info():
"INT8 AbsMax, INT8 Affine, INT4 Groupwise",
"CPU / Tensor Core / Metal",
)
table.add_row(
"Bit-Packing",
"INT4 (2 vals/byte), BitNet Ternary (4 or 5 vals/byte), 2:4 Sparsity",
"Vectorized Sub-Byte Runtimes",
)
table.add_row(
"Modern FP8",
"OCP E4M3FN (GEMM), OCP E5M2 (KV/Gradients)",
Expand All @@ -73,5 +86,81 @@ def info():
console.print(table)


@app.command("pack-inspect")
def pack_inspect(
fmt: str = typer.Option(
"int4",
"--format",
"-f",
help="Format to inspect: int4, ternary, sparse24",
),
):
"""Inspect bit-packing layout, sub-byte representation, and theoretical memory savings."""
import torch

fmt_lower = fmt.lower()
if fmt_lower == "int4":
sample = torch.tensor([5, 12], dtype=torch.int32)
packed, orig_len = pack_int4(sample, signed=False)
unpacked = unpack_int4(packed, original_len=orig_len, signed=False)
byte_val = packed.item()

panel = Panel(
f"[bold green]INT4 Sub-Byte Packing (2 values per uint8 byte)[/bold green]\n\n"
f"Input values: [cyan]{sample.tolist()}[/cyan]\n"
f"• Low nibble [0:3]: {sample[0].item()} -> [yellow]{sample[0].item():04b}[/yellow]\n"
f"• High nibble [4:7]: {sample[1].item()} -> [yellow]{sample[1].item():04b}[/yellow]\n"
f"Packed uint8 byte: [bold magenta]{byte_val}[/bold magenta] "
f"(binary: [yellow]{byte_val:08b}[/yellow], hex: [yellow]0x{byte_val:02X}[/yellow])\n"
f"Unpacked roundtrip: [cyan]{unpacked.tolist()}[/cyan]\n"
f"Memory compression: [bold green]4.0x vs FP16[/bold green] (2.0x vs INT8)",
title="INT4 Bit Layout",
border_style="cyan",
)
console.print(panel)

elif fmt_lower == "ternary":
sample = torch.tensor([-1, 0, 1, -1])
packed, orig_len = pack_ternary(sample, mode="2bit")
unpacked = unpack_ternary(packed, original_len=orig_len, mode="2bit")
byte_val = packed.item()

panel = Panel(
f"[bold green]BitNet 1.58b Ternary Packing (4 weights per uint8 byte)[/bold green]\n\n"
f"Input weights: [cyan]{sample.tolist()}[/cyan]\n"
f"Offset mapping: u = v + 1 in {{0, 1, 2}}\n"
f"Packed uint8 byte: [bold magenta]{byte_val}[/bold magenta] "
f"(binary: [yellow]{byte_val:08b}[/yellow], hex: [yellow]0x{byte_val:02X}[/yellow])\n"
f"Unpacked roundtrip: [cyan]{unpacked.tolist()}[/cyan]\n"
f"Memory compression: [bold green]8.0x vs FP16[/bold green] (Multiplication-free GEMM)",
title="BitNet 1.58b Layout",
border_style="green",
)
console.print(panel)

elif fmt_lower in ("sparse24", "2:4", "sparse"):
sample = torch.tensor([[0.0, 3.5, 0.0, -1.2, 4.0, 0.0, 0.0, -2.1]])
condensed, metadata = prune_and_compress_2_4(sample)
meta_byte = metadata.item()

panel = Panel(
f"[bold green]2:4 Structured Sparsity (NVIDIA Sparse Tensor Cores)[/bold green]\n\n"
f"Dense input row (8 values): [cyan]{sample.tolist()[0]}[/cyan]\n"
f"Condensed non-zeros (4 values): [cyan]{condensed.tolist()[0]}[/cyan]\n"
f"Packed metadata byte: [bold magenta]{meta_byte}[/bold magenta] "
f"(binary: [yellow]{meta_byte:08b}[/yellow], hex: [yellow]0x{meta_byte:02X}[/yellow])\n"
f"Storage reduction: [bold green]50% weight + 2-bit metadata/val[/bold green]\n"
f"Theoretical math throughput: [bold green]2.0x Tensor Core TFLOPS[/bold green]",
title="2:4 Sparse Tensor Layout",
border_style="magenta",
)
console.print(panel)

else:
err_msg = f"Unknown format '{fmt}'. Choose 'int4', 'ternary', or 'sparse24'."
console.print(f"[bold red]{err_msg}[/bold red]")
raise typer.Exit(code=1)


if __name__ == "__main__":
app()
20 changes: 19 additions & 1 deletion src/quantbench/quant/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""First-principles quantization primitives and algorithms."""
"""First-principles quantization primitives, algorithms, and bit-packing runtimes."""

from quantbench.quant.affine import (
dequantize_absmax,
Expand All @@ -8,6 +8,16 @@
)
from quantbench.quant.blockwise import dequantize_blockwise, quantize_blockwise
from quantbench.quant.fp8 import FP8Format, dequantize_fp8, quantize_fp8
from quantbench.quant.packing import (
decompress_2_4,
pack_2_4_indices,
pack_int4,
pack_ternary,
prune_and_compress_2_4,
unpack_2_4_indices,
unpack_int4,
unpack_ternary,
)

__all__ = [
"quantize_affine",
Expand All @@ -19,4 +29,12 @@
"quantize_fp8",
"dequantize_fp8",
"FP8Format",
"pack_int4",
"unpack_int4",
"pack_ternary",
"unpack_ternary",
"pack_2_4_indices",
"unpack_2_4_indices",
"prune_and_compress_2_4",
"decompress_2_4",
]
27 changes: 27 additions & 0 deletions src/quantbench/quant/packing/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Bit-packing runtimes for sub-byte quantization formats.

Provides vectorized bit-shift packing and unpacking for:
- INT4 (4-bit integers: unsigned [0, 15] or signed [-8, 7]) -> 2 values per uint8 byte.
- Ternary (BitNet 1.58b: {-1, 0, +1}) -> 4 values per uint8 byte.
- 2:4 Structured Sparsity Metadata -> two 2-bit indices per 4-bit nibble.
"""

from quantbench.quant.packing.int4_pack import pack_int4, unpack_int4
from quantbench.quant.packing.sparse_pack import (
decompress_2_4,
pack_2_4_indices,
prune_and_compress_2_4,
unpack_2_4_indices,
)
from quantbench.quant.packing.ternary_pack import pack_ternary, unpack_ternary

__all__ = [
"pack_int4",
"unpack_int4",
"pack_ternary",
"unpack_ternary",
"pack_2_4_indices",
"unpack_2_4_indices",
"prune_and_compress_2_4",
"decompress_2_4",
]
Loading
Loading