AI Wiki中文/EN

乘积量化:用几本小码本表示大量向量

Product quantization

训练子空间码本,对比ADC与SDC,核算实际存储。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

存几个地址的组合,不存每个坐标

假设向量有八个坐标。可以不为每项都存八个数,而把向量切成小块,每块用一个学得的近邻中心编号表示。重建时查出这些中心,再拼起来。信息会损失,但存储编码可以小得多。

一个包含大量高维中心的码本很昂贵。乘积量化 PQ 隐式组合多本小码本:每块各选一个中心,就定义一种重建向量,而无需保存全部组合。Jégou、Douze、Schmid 同时讨论了这种表示和直接从编码进行最近邻评分的方法。期刊文章发表于2011年,所引 HAL v2 存档提交于2013-05-22,这是不同事件。PQ 封面及第II节

本篇研究表示误差与查表距离,近似最近邻搜索另行研究跳过候选。即使扫描每个存储编码,也可以使用压缩。

压缩会改变距离;码本与实际数组字节都要计数。
压缩会改变距离;码本与实际数组字节都要计数。

码本是笛卡尔积

假设维数 D 能被块数 m 整除,将向量与重建表示为子块拼接:

x=[x(1);…;x(m)],x^=[c1,a1;…;cm,am],x(j)∈RD/m.x=[x^{(1)};\ldots;x^{(m)}],\qquad \hat x=[c_{1,a_1};\ldots;c_{m,a_m}],\quad x^{(j)}\in\mathbb R^{D/m}.

每块用本块训练坐标做 k-means,得到 K 个中心;编码选择最近中心,本实现同分时选最小中心编号:

aj=arg⁡min⁡0≤r<K∥x(j)−cj,r∥22,∣C1×⋯×Cm∣=Km.a_j=\arg\min_{0\leq r<K}\|x^{(j)}-c_{j,r}\|_2^2,\qquad |C_1\times\cdots\times C_m|=K^m.

笛卡尔积有 K^m 种可能重建,而码本只存 mK 个子块中心。每个中心 D/m 维,因此总标量数只有 KD。平方重建误差等于各块平方误差之和,分别学习子块就能最小化可加失真目标;不过 Lloyd 迭代只找到局部解,结果依赖初始化。PQ 第II.B节

定长子编码与未压缩码本需要:

Bideal=m⌈log⁡2K⌉ bits per vector,Bbooks=bKD bytes.B_{\mathrm{ideal}}=m\lceil\log_2K\rceil\ \text{bits per vector},\qquad B_{\mathrm{books}}=bKD\ \text{bytes}.

b 是每个中心坐标的存储字节,不含编号、容器开销和补齐。八个中心理论上每个子码只需三位,但 NumPy uint8 仍占八位;要三位存储,必须显式按位打包。固定 K 增加块数会增长码长,因此收益不能当成固定码率比较。

非对称距离计算 ADC 不压缩查询 q,只使用重建数据库向量。先计算查询每块到全部中心的距离表,再每块查一项求和:

Tj,r=∥q(j)−cj,r∥22,d~ADC2(q,x)=∑j=1mTj,aj=∥q−x^∥22.T_{j,r}=\|q^{(j)}-c_{j,r}\|_2^2,\qquad \tilde d_{\mathrm{ADC}}^2(q,x)=\sum_{j=1}^{m}T_{j,a_j}=\|q-\hat x\|_2^2.

查表精确等于到重建向量的距离,不一定等于到原始 x 的距离。对称距离计算 SDC 还会量化查询,记查询子码为 b_j:

d~SDC2(q,x)=∑j=1m∥cj,bj−cj,aj∥22=∥q^−x^∥22.\tilde d_{\mathrm{SDC}}^2(q,x)=\sum_{j=1}^{m}\|c_{j,b_j}-c_{j,a_j}\|_2^2 =\|\hat q-\hat x\|_2^2.

ADC 避免了查询量化误差,不保证每条查询的排名都更好。原论文描述两种方法;Faiss 的 IVFADC 还对粗分区中的残差做量化。本例只用普通 PQ,扫描每个编码。PQ 第III.A节 Faiss 第2及5.2节

反三角不等式给出欧氏距离误差界:

∣∥q−x∥2−∥q−x^∥2∣≤∥x−x^∥2.\left|\|q-x\|_2-\|q-\hat x\|_2\right|\leq\|x-\hat x\|_2.

平方距离不直接满足同一个界。即使距离误差很小,也可能交换两个几乎并列的邻居。重建失真和邻居召回有关联,但不能互换。PQ 第III.B节

训练、编码、查表,再核算账单

使用 Python 3.12 和 NumPy 1.26。种子37产生共同的八维线性变换,以及分别有256、128、20行的训练、数据库和查询数组。这些合成数组共享分布,但采样行不同。每块训练八个中心,采用确定性最远点初始化,最多30次 Lloyd 更新;空簇保留旧中心。

比较 m=1、2、4、8。编码使用 uint8,码本和原向量使用 NumPy float64,不做位打包。对照精确、ADC、SDC 的前五项,同分按编号升序。每个编码都评分,不让候选剪枝掩盖压缩本身的影响。

"""Original product quantizer with Lloyd training, ADC and SDC; no Faiss dependency."""
import json
import math
import numpy as np

def matrix(x):
    x=np.asarray(x,dtype=float)
    if x.ndim!=2 or not 1<=len(x)<=2000 or not 1<=x.shape[1]<=32 or not np.isfinite(x).all() or np.max(np.abs(x))>1e6:
        raise ValueError('bounded nonempty matrix required')
    return x

def squared(x,y):return ((x[:,None,:]-y[None,:,:])**2).sum(axis=2)

def fit(x,parts=2,centroids=8,steps=30):
    x=matrix(x);n,d=x.shape
    if type(parts) is not int or parts<1 or d%parts or type(centroids) is not int or not 2<=centroids<=min(256,n):
        raise ValueError('parts must divide dimension;2..min(256,N) centroids')
    if type(steps) is not int or not 1<=steps<=100:raise ValueError('steps1..100 required')
    books=[];histories=[]
    for block in np.split(x,parts,axis=1):
        c=[block[0].copy()]
        while len(c)<centroids:c.append(block[int(np.argmax(squared(block,np.array(c)).min(axis=1)))].copy())
        c=np.array(c);history=[]
        for _ in range(steps):
            dist=squared(block,c);labels=dist.argmin(axis=1);history.append(float(dist.min(axis=1).mean()))
            updated=np.array([block[labels==j].mean(axis=0) if np.any(labels==j) else c[j] for j in range(centroids)])
            if np.array_equal(updated,c):break
            c=updated
        history.append(float(squared(block,c).min(axis=1).mean()));books.append(c);histories.append(history)
    return np.array(books),histories

def encode(x,books):
    x=matrix(x)
    if books.ndim!=3 or x.shape[1]!=books.shape[0]*books.shape[2] or not np.isfinite(books).all():raise ValueError('compatible finite codebooks required')
    return np.column_stack([squared(block,c).argmin(axis=1) for block,c in zip(np.split(x,len(books),axis=1),books)]).astype(np.uint8)

def validate_codes(codes,books):
    codes=np.asarray(codes)
    if books.ndim!=3 or not np.isfinite(books).all() or np.max(np.abs(books))>1e6:raise ValueError('bounded finite codebooks required')
    if codes.ndim!=2 or codes.shape[1]!=len(books) or not np.issubdtype(codes.dtype,np.integer) or np.any(codes<0) or np.any(codes>=books.shape[1]):raise ValueError('valid integer codes required')
    return codes

def decode(codes,books):
    codes=validate_codes(codes,books)
    return np.concatenate([books[j,codes[:,j]] for j in range(len(books))],axis=1)

def adc(query,codes,books,symmetric=False):
    q=matrix(np.asarray(query,dtype=float).reshape(1,-1));codes=validate_codes(codes,books)
    if q.shape[1]!=books.shape[0]*books.shape[2]:raise ValueError('query dimension mismatch')
    if symmetric:q=decode(encode(q,books),books)
    table=np.array([squared(block,c)[0] for block,c in zip(np.split(q,len(books),axis=1),books)])
    return table[np.arange(len(books))[None,:],codes].sum(axis=1)

def rank(values,k=5):return sorted(range(len(values)),key=lambda i:(float(values[i]),i))[:k]

def fixture():
    rng=np.random.default_rng(37);mix=rng.normal(size=(8,8))
    train=rng.normal(size=(256,8))@mix
    database=rng.normal(size=(128,8))@mix
    queries=rng.normal(size=(20,8))@mix
    return train,database,queries

def demo():
    train,database,queries=fixture();exact=[rank(squared(q[None,:],database)[0]) for q in queries];rows=[]
    for parts in [1,2,4,8]:
        books,_=fit(train,parts);codes=encode(database,books);reconstructed=decode(codes,books)
        adc_scores=[adc(q,codes,books) for q in queries];sdc_scores=[adc(q,codes,books,True) for q in queries]
        rows.append(dict(parts=parts,ideal_bits=parts*3,code_bytes=int(codes.nbytes),codebook_bytes=int(books.nbytes),
            reconstruction_mse=float(np.mean(np.sum((database-reconstructed)**2,axis=1))),
            adc_recall_at5=float(np.mean([len(set(rank(v))&set(e))/5 for v,e in zip(adc_scores,exact)])),
            sdc_recall_at5=float(np.mean([len(set(rank(v))&set(e))/5 for v,e in zip(sdc_scores,exact)])),
            table_max_error=float(max(np.max(np.abs(v-squared(q[None,:],reconstructed)[0])) for q,v in zip(queries,adc_scores)))))
    # Euclidean (not squared-distance) error is bounded by reconstruction error.
    bounds=np.linalg.norm(database-reconstructed,axis=1)
    worst=max(float(np.max(np.abs(np.sqrt(squared(q[None,:],database)[0])-np.sqrt(adc(q,codes,books)))-bounds)) for q in queries)
    return dict(rows=rows,original_database_bytes=int(database.nbytes),euclidean_bound_max_excess=worst,
        scope='Separate seeded synthetic training256/database128/query20 vectors;8 centroids per subspace; uint8 codes are not bit-packed; NumPy float64 codebooks.')

if __name__=='__main__':print(json.dumps(demo(),sort_keys=True,allow_nan=False))

原数据库数组占8,192字节;m增大时,编码占128、256、512、1,024字节,每种另有512字节码本。理想码长为每向量3、6、12、24位,但实际编码数组是8、16、32、64位。应同时报告,不能把理论位数当作已分配内存。

ADC 前五召回为0.20、0.36、0.56、0.77,SDC 为0.20、0.30、0.44、0.66。平均平方重建误差,即每向量坐标平方误差先求和再对向量取平均,约为36.28、28.84、13.48、3.18。更多块在本例有帮助,同时花费更多位;结果不能确立另一份数据的最佳分区或位分配。

查表距离与显式解码后的向量距离在浮点容差内一致。可执行检查还验证两块手算例子、Lloyd失真不增加、子块误差可加以及欧氏误差界。ADC 输入检查只验证编码,不重建整个数据库;另有回归检查保护这一区别。

编码小,不代表成本全消失

每条查询建距离表需要 O(KD) 算术和 O(mK) 存储,随后扫描 N 个编码需 O(Nm) 次查表及相加,再选前 k 项。本实现每次调用检查 O(Nm) 个编码,并对 N 个分数全排序,耗时 O(N log N)。生产引擎可以另行安排检查和选择,本教学代码不声称墙钟加速。

训练、编码也要时间,编码必须配有码本。编号、内存对齐、元数据、索引结构和保留的原始向量都会占空间。精确重排若要使用原向量,也必须把它们算进存储。新码本不能随意解码旧编码,除非保留了兼容版本映射。

坐标分块施加了一种分区,跨块相关可能损害量化。旋转、优化分区、残差量化和其他码长都是可研究替代方案,不是本例已实现功能。Faiss 在 IVFADC 中组合粗量化与残差 PQ,还讨论 GPU 特定布局;本篇没有复现 GPU 内核或完整索引。Faiss 第2及5.2节

在开发数据上选择码长和训练设置,再测留出的邻居召回、失真、延迟与全部保留内存。编码碰撞导致近似距离同分;如果候选短名单已经漏掉真实邻居,精确重排也找不回来。比较方法时,距离与同分规则必须一致。

先数位,再看邻居

  1. D=8、m=4、K=8时,有多少种重建,存多少中心标量?

答案:有8⁴=4,096种组合,只存KD=64个中心标量。表示通过子块码本拼出组合,不保存4,096个完整向量。

  1. 四个三位子码,理论上和本例uint8实现各占多少?

答案:定长位载荷为每向量12位;四个uint8占32位,即四字节。接近理论载荷需要位打包,数组与行对齐还可能增加开销。

  1. ADC查表到底精确还是近似?

答案:对未压缩查询到重建数据库向量的距离,除浮点误差外它是精确的;对原始数据库向量的距离,它是近似的。两者目标不同。

  1. 重建误差小,召回却差,应该看什么?

答案:检查近似并列、编码碰撞、坐标分块和查询分布。很小扰动也会改变十分接近的邻居次序。对失败查询比较精确及近似距离,再在相同总内存和候选预算下,评估更长编码或精确重排。

压缩与候选选择,是两项近似

原 PQ 论文先推导码本乘积、ADC/SDC和距离误差,再加入倒排文件;Faiss 论文展示这些部分如何进入大规模 GPU 设计。按这个顺序阅读,较容易分开“紧凑表示改变了什么”与“候选剪枝跳过了什么”。

先判断,再看解释

八个中心每个子码理论需3位;NumPy uint8会用3位保存吗?

选择一个答案

学习目标

  • 推导乘积码距离,区分理论位数与数组实际字节。
  • 运行原创示例,定位近似误差。

先修与延伸

查看知识关联图 →

参考文献

  1. Product Quantization for Nearest Neighbor Search — HAL inria-00514462v2
    Hervé Jégou; Matthijs Douze; Cordelia Schmid · 2011
  2. Billion-scale similarity search with GPUs — arXiv v1
    Jeff Johnson; Matthijs Douze; Hervé Jégou · 2017

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-20 · Single AI author. Read HAL cover: journal2011, archive deposit2013-05-22. Viewed physical PDF3/4/5/6/8: Lloyd conditions, product codebook, ADC/SDC, Euclidean error bound and inverted lists. No benchmark reproduction. Viewed physical PDF2/6: exact squared-L2, IVFADC coarse/fine quantizers, candidate lists and PQ lookup tables; no GPU kernels or speed claims reproduced. 6 paired equations and four explained exercises. Checked hand ADC/SDC, lookup against reconstruction, nonincreasing Lloyd distortion, additive block error, Euclidean bound and actual uint8/codebook bytes; ADC validation cannot decode the database.

  • 核手算ADC/SDC、查表对照重建、Lloyd失真非增、子块误差可加、欧氏界及实际uint8/码本字节;ADC校验不得解码全库。
  • 每题四张计算SVG,9数值/几何与24响应式组合通过;实看8张最终图,完整页面验收另记。

核对的来源位置:

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。