Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

vector-quantization

БесплатноБез исполняемых скриптовНе проверен

Vector compression techniques: scalar quantization (int8, int4), binary quantization (bit vectors + Hamming), product quantization (PQ), optimized PQ…

claude-dev-suiteот claude-dev-suite★ 51 звезда на GitHub

Об этом скилле

Vector Quantization

Why Quantize

A float32 1024-dim embedding is 4 KB. 100M vectors = 400 GB. Quantization cuts this 4-128x with small recall cost — especially when paired with rescoring.

Scheme Bytes/vec (d=1024) Reduction Typical recall impact
Full float32 4096 1x 0
float16 / bfloat16 2048 2x < -0.5%
int8 scalar 1024 4x -1 to -2%
int4 scalar 512 8x -2 to -5%
Binary (1 bit) 128 32x -5 to -15% (recover with rescore)
PQ (64 subvectors x 8 bits) 64 64x -2 to -10%
Binary + MRL (d=256) 32 128x -3 to -8% with rescore

Scalar Quantization (int8 / int4)

Linear mapping: each float32 dim scaled to an 8-bit or 4-bit integer with per-index or per-dim scale/zero-point.

import numpy as np

def int8_quantize(x: np.ndarray):
    # Symmetric per-dim scale
    scale = np.max(np.abs(x), axis=0) / 127
    q = np.round(x / scale).clip(-128, 127).astype(np.int8)
    return q, scale

def int8_dot(q: np.ndarray, q_q: np.ndarray, s_a: np.ndarray, s_b: np.ndarray) -> np.ndarray:
    return (q.astype(np.int32) @ q_q.astype(np.int32).T) * (s_a * s_b).sum()

For production, use framework support (Faiss, pgvector halfvec/int8, Qdrant scalar quantizer, Elasticsearch int8_hnsw) — they handle numerical issues and SIMD.

Faiss scalar quantization

import faiss

quantizer = faiss.IndexFlatL2(d)
index = faiss.IndexIVFScalarQuantizer(
    quantizer, d, nlist=1024,
    qtype=faiss.ScalarQuantizer.QT_8bit, metric=faiss.METRIC_L2,
)
index.train(sample)
index.add(corpus)
index.nprobe = 32

Binary Quantization

Each float becomes 1 bit: bit = (value > 0). Distance becomes Hamming distance (XOR + popcount), which is 10-40x faster than cosine on modern CPUs.

import numpy as np

def binary_quantize(vecs: np.ndarray) -> np.ndarray:
    return np.packbits((vecs > 0).astype(np.uint8), axis=1)   # (N, d/8)

def hamming_topk(qbits: np.ndarray, cbits: np.ndarray, k: int):
    # XOR + popcount via numpy
    xor = np.bitwise_xor(cbits, qbits)
    dists = np.unpackbits(xor, axis=1).sum(axis=1)
    topk = np.argpartition(dists, k)[:k]
    return topk[np.argsort(dists[topk])]

Recovery via Rescoring

Binary alone loses 5-15% recall. Fix: oversample on binary, then rescore the shortlist with full float vectors.

def search_binary_then_rescore(qvec: np.ndarray, corpus: np.ndarray,
                               cbits: np.ndarray, top_k: int, oversample: int = 20):
    qbits = binary_quantize(qvec[None])[0]
    shortlist = hamming_topk(qbits, cbits, top_k * oversample)
    # Rescore with full float32
    sub = corpus[shortlist]
    scores = sub @ qvec
    order = np.argsort(-scores)[:top_k]
    return shortlist[order], scores[order]

Typical result: ~99% of full-float recall at 5-10x lower search latency and 32x less stored vector data.

Binary in pgvector

-- Column
embedding_bit bit(1024)

-- Populate
UPDATE chunks SET embedding_bit = binary_quantize(embedding::vector)::bit(1024);

-- Index (pgvector 0.7+)
CREATE INDEX ON chunks USING hnsw (embedding_bit bit_hamming_ops);

-- Search then rescore
WITH shortlist AS (
  SELECT id, embedding
  FROM chunks
  ORDER BY embedding_bit <~> binary_quantize($1::vector)::bit(1024)
  LIMIT 100
)
SELECT id, 1 - (embedding <=> $1::vector) AS score
FROM shortlist
ORDER BY embedding <=> $1::vector
LIMIT 10;

Binary in Qdrant

from qdrant_client import models

client.update_collection(
    "docs",
    quantization_config=models.BinaryQuantization(
        binary=models.BinaryQuantizationConfig(always_ram=True),
    ),
)
client.query_points(
    "docs",
    query=qvec.tolist(),
    using="dense",
    limit=10,
    search_params=models.SearchParams(
        quantization=models.QuantizationSearchParams(
            rescore=True, oversampling=3.0,
        ),
    ),
)

Product Quantization (PQ)

Split each d-dim vector into m subvectors of size d/m. Quantize each subvector to one of ksub = 2^nbits centroids learned by k-means on a training sample. Stored code: m * nbits bits per vector.

Faiss PQ

import faiss

m, nbits = 64, 8                             # 64 bytes per vector
index = faiss.IndexPQ(d, m, nbits)
index.train(sample)                          # needs ~256 * 2^nbits points
index.add(corpus)
D, I = index.search(queries, 10)

IVF + PQ (standard huge-scale combo)

quantizer = faiss.IndexFlatL2(d)
index = faiss.IndexIVFPQ(quantizer, d, nlist=8192, m=64, nbits=8)
index.train(sample)
index.add(corpus)
index.nprobe = 64

Faiss computes query-to-centroid distances once per query (m * 256 values) and sums them per candidate, which is very SIMD-friendly.

Optimized PQ (OPQ)

Apply a learned orthogonal rotation before PQ so subvectors are better balanced. Gains ~1-3% recall at the same code size.

import faiss
opq = faiss.OPQMatrix(d, m)
opq.train(sample)
rotate
Полный SKILL.md на GitHub

Установить vector-quantization в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Grep
Glob
Write
Edit

FAQ

Что делает скилл vector-quantization?

Vector compression techniques: scalar quantization (int8, int4), binary quantization (bit vectors + Hamming), product quantization (PQ), optimized PQ, residual quantization. Covers rescoring workflow, storage math, accuracy tradeoffs, and Faiss/Qdrant/pgvector implementations. USE WHEN: user mentions "quantization", "int8 embeddings", "binary embeddings", "product quantization", "PQ", "OPQ", "residual quantization", "Hamming distance", "compress embeddings", "rescoring" DO NOT USE FOR: Matryoshka dimension truncation - use `matryoshka-embeddings`; ANN algorithm choice - use `ann-algorithms`

Как установить скилл vector-quantization?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл vector-quantization запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить vector-quantization с