Metadata-Version: 2.4
Name: leech-quant
Version: 0.1.0
Summary: Structured full-shell Leech quantization, packed cosine search, and soft routing
License-Expression: Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE.txt
Requires-Dist: torch>=2.2
Requires-Dist: numpy>=1.24
Dynamic: license-file

# leech-quant 0.1.0

Structured 24D minimal-shell Leech quantization, bit-packed cosine search, and differentiable full-shell soft routing. The dictionary has 196,560 unit vectors; the encoder uses Golay octads and a six-column parity/marked contraction instead of a dense dictionary. No centroid training is needed; reconstruction gains are shared and calibrated (or explicitly supplied).

**Release status:** Apache-2.0 experimental research library. The installed pre-license wheel passed compiled search and low-temperature routing/JVP smoke checks on a Tesla T4. The release changes license metadata and documentation only; runtime Python source is unchanged. Historical performance measurements come from the original notebooks, not the refactored wheel.

## Install locally

```sh
python -m pip install .
```

Requires Python 3.10+, PyTorch 2.2+ and NumPy 1.24+. Install the appropriate PyTorch CUDA build separately if necessary. The minimum dependency versions are declared, not comprehensively compatibility-tested. CPU regression checks used PyTorch 2.10.0+cpu; historical T4 runs used 2.14.1+cu130. CUDA compilation is enabled by default on CUDA devices; use `compile=False` for eager execution. Compilation errors propagate rather than being silently hidden.

## Search a packed index

```python
from leech_quant import LeechIndex
index = LeechIndex(dim=768, stages=2, device='cuda')
index.build(embeddings, calibration=calibration_embeddings)
scores, ids = index.search(queries, k=10, mode='tiled')
```

`embeddings`, `calibration_embeddings`, and `queries` are finite matrices of floating-point vectors. Supported dimensions are positive multiples of 96 (four 24D blocks per packing group), including 384, 768 and 1536. The index normalizes each vector and query to unit norm. Supply an independent calibration set for scientific comparisons; omitting it fits the shared gains on the first 256 input rows. Explicit `gains` bypass calibration. The index retains actual packed uint8 codes, FP32 inverse reconstruction norms, and shared gains; no persistent dense database is stored. `mode='tiled'` reconstructs one bounded tile at a time and batches queries; `mode='lut'` scores packed codes directly and processes one query at a time. `ids` are zero-based database row positions. Tie ordering is unspecified. `index.index_bytes` reports payload + inverse norms + gains, excluding tables and Python/allocator overhead.

## Encode and decode without a search index

```python
from leech_quant import LeechQuantizer
quantizer = LeechQuantizer(stages=3, device='cuda')
quantizer.fit_gains(calibration_embeddings)
packed = quantizer.encode(embeddings)
reconstructed = quantizer.decode(packed)
```

Unlike `LeechIndex`, `LeechQuantizer` does not normalize inputs. `encode(..., return_ids=True)` returns `(packed, canonical_ids)`. `packed` is a `PackedVectors` dataclass with `payload`, `gains`, `inverse_norm`, `dim`, `stages`; use `.to(device)` to transfer it, or `index.load_packed(packed)` to load a compatible index. The raw packing format is described in [FORMAT.md](FORMAT.md). No file serialization protocol or persistence guarantee beyond that layout is implied by the prototype. For one, two, or three greedy stages, the index payload is 18, 36, or 54 bits per 24D block, plus one FP32 inverse norm per full vector for cosine search.

## Exact soft routing

```python
from leech_quant import LeechSoftRouter
router = LeechSoftRouter(T=0.07, device='cuda')
logZ, mean = router(blocks)    # [B,24] inputs; logZ [B], mean [B,24]
jvp = router.jvp(blocks, upstream_gradient)
```

The partition and soft mean use positive log-semiring contractions; `jvp` computes the exact covariance Jacobian product up to numerical error. FP64 inputs are preserved; other inputs are promoted to FP32. The soft mean is differentiable. The explicit JVP has a stable `logsumexp` fallback for nonfinite second derivatives of `logaddexp` (observed at low temperature on local CPU PyTorch). For low-temperature automatic differentiation, use `stable_derivatives=True`, which selects the stable contraction up front. This fallback/option is CPU-regression-tested and passed CUDA finiteness checks, not part of the historical GPU timings. At T=0.001, the two FP32 derivative modes differed by a maximum absolute 0.0112152 in the CUDA smoke test; this is not a high-precision JVP accuracy certificate. A hard-forward/soft-backward surrogate is not the derivative of hard quantization.

## Frozen T4 evidence

Source-domain calibration versus target-domain calibration on the same held-out target evaluation data, means over seeds 49/50/51; 18,118 filtered 20 Newsgroups documents, 13,766 database documents per seed across both domains. Relative squared reconstruction error (SSE divided by input squared norm). Standard PQ here is a custom independent 4D subspace Lloyd implementation, **not a measured FAISS implementation**.

| Model | Method | Index bits/dim | Target-calibrated error | Source-calibrated error | Relative shift penalty | Source-calibrated target recall@10 |
|---|---|---:|---:|---:|---:|---:|
| MPNet 768D | Leech18 | 0.75 | .409743 | .409743 | +0.000036% | 78.62% |
| MPNet 768D | PQ18 standard | 0.75 | .406867 | .443371 | +8.97% | 77.08% |
| MPNet 768D | Leech36 | 1.50 | .167366 | .167362 | -0.002591% | 87.24% |
| MPNet 768D | PQ36 standard | 1.50 | .169412 | .184877 | +9.13% | 86.28% |
| MPNet 768D | Leech54 | 2.25 | .068527 | .068527 | -0.000602% | 92.32% |
| MPNet 768D | PQ54 pooled | 2.25 | .073601 | .074210 | +0.83% | 91.90% |
| MiniLM 384D | Leech18 | 0.75 | .407552 | .407552 | -0.000002% | 67.47% |
| MiniLM 384D | PQ18 standard | 0.75 | .433407 | .467596 | +7.89% | 64.66% |
| MiniLM 384D | Leech36 | 1.50 | .165652 | .165657 | +0.003019% | 82.50% |
| MiniLM 384D | PQ36 standard | 1.50 | .179375 | .194101 | +8.21% | 80.16% |
| MiniLM 384D | Leech54 | 2.25 | .067488 | .067485 | -0.004438% | 88.62% |
| MiniLM 384D | PQ54 pooled | 2.25 | .071997 | .072774 | +1.08% | 87.47% |

The complete release log contains 22 synthetic search measurements and 396 real-corpus measurements, zero recorded failures. Across overlapping paired PQ comparisons, Leech wins 177/180 on distortion and 159/180 on recall. Largest absolute relative distortion change between calibration domains among 54 paired Leech conditions was 0.0094%; largest absolute recall change was 0.391 percentage points. These are not independent trials or a universal guarantee of OOD robustness. There is no standard (independent) PQ54 baseline in this experiment.

### Packed search, 100,000 x 768D, Tesla T4

| Method | Actual index MB (decimal) | Single-query QPS | Batched (32 queries) QPS |
|---|---:|---:|---:|
| FP32 | 307.200000 | 248.15 | 6154.53 |
| FP16 | 153.600000 | 194.27 | 6440.40 |
| Leech18 | 7.600004 | 79.45 | 1604.05 |
| Leech36, greedy | 14.800008 | 60.57 | 306.20 |
| Leech36, one refinement sweep | 14.800008 | 60.24 | 1422.69 |
| Pooled PQ36 | 14.800000 | 105.96 | not measured |

Actual packed index compression relative to FP32: ~40.42x and ~20.76x, including inverse norms and gains but excluding static implementation tables. Direct LUT scoring matched tiled-decoding top-10 IDs on all measured search configurations, score discrepancy at most 2.98e-8. This is agreement on *quantized* vectors, not on original vectors. At 100K, greedy Leech18 and Leech36 had original-neighbor recalls of 15.0% and 40.31%, respectively, on the synthetic random-direction workload. The two-stage tiled timings vary substantially; no cause was established. Coordinate refinement did not materially reduce distortion in this test, but that does not prove global optimality. This package uses greedy encoding only.

### Routing / dictionary footprint

The original V3 T4 benchmark measured up to 13.03x speedup over unchunked dense FP32 and 13.34x over the tested chunked dense FP32, with 90.9% lower peak additional allocated memory vs unchunked dense at batch 1024. Soft tables occupy 65,712 bytes; adding hard backtracking tables yields 82,576 bytes (80.64 KiB, 228.51x smaller than the 18,869,760-byte dense FP32 dictionary). The scanner requires additional decoder tensors; the implementation exposes `quantizer.table_bytes`, including total tensor bytes (197,652 bytes in the CPU-tested implementation). Historical scanner table accounting overlaps the encoder tables. The entire query LUT for 768D occupies 727,808 bytes, not 22.2 KiB; the latter is per 24D block. Do not assume L1 residency. Timing excludes compilation warmup; baselines are the specific notebook implementations, not all optimized alternatives.

## When not to use this

- For learned low-dimensional image autoencoder bottlenecks, binary FSQ won both distortion and throughput in the tested Fashion-MNIST workload; the fixed-temperature soft surrogate also underused its dictionary.
- For maximum GPU QPS when dense vectors fit comfortably, the current direct LUT and tiled scan were slower than dense batched search; no production ANN or fused CUDA/AVX scanner is provided.
- For arbitrary unnormalized LLM weights, block scale information and downstream model accuracy matter. No LLM weight/KV-cache evaluation has been performed. This is minimal-shell quantization, not exact nearest-point decoding of the infinite lattice.

## Installed-wheel CUDA verification

The archived `benchmarks/results/leech_wheel_cuda_smoke_results.json` records two passed checks and zero failures on Tesla T4 / PyTorch 2.14.1+cu130. Compiled tiled and direct LUT search agreed on the top-10 sets (100%) and to 3.7253e-8 in score, with 303,112 index bytes exactly as expected. At T=0.001 the router and JVP were finite; stable-mode mean and JVP maximum absolute differences were 2.6822e-7 and 0.0112152, respectively. The JVP comparison used atol=rtol=0.02, not a dense FP64 oracle. The checks took 62.56 and 356.47 seconds including compilation. This establishes smoke-test compatibility on the tested configuration, not universal GPU compatibility.

To run just the installed-package smoke test on CUDA: `python benchmarks/cuda_smoke.py`.

## Reproduce and audit

`benchmarks/notebooks/` contains the four original T4 notebooks and original wheel smoke notebook, `benchmarks/results/` contains the four immutable original research logs plus the installed-wheel smoke log, and `benchmarks/SHA256SUMS` hashes both. To verify and recompute the OOD table without a GPU:

```sh
(cd benchmarks && sha256sum -c SHA256SUMS)
python benchmarks/summarize.py
python -m unittest discover -s tests -v
```

Open the notebooks in a Colab session, choose T4, and run all cells to reproduce the historical experiments. Alternatively:

```sh
python benchmarks/run.py release --output-dir ./new-release-run
```

The launcher extracts the unmodified code cells and runs them in a separate, empty directory; additional notebook-specific dependencies (torchvision, pandas, scikit-learn, sentence-transformers) and model/dataset downloads may be required. Original benchmark code and results are separate from the package API; running the launcher does not establish package-level GPU performance. The original CPU regression log and the separate CUDA smoke log are retained.
