真人照片转二次元后怎么换画风?原照与二次元成图的两种用法
2026-11-21
2026-11-25 0
Elasticsearch 检索向量时,候选数量、候选占用的字节数及打分用时都会影响成本。这里固定输入向量与查询,逐一验证 HNSW、标量量化、BBQ 与全精度重排。
实验环境为 Elasticsearch 9.2.5 单节点及 Python 3.10 或更高版本,Python 脚本仅用标准库。启动独立测试节点并绑定本机环回地址,使用 19238 端口;示例面向这个无认证实验节点。两个脚本放在同一目录,在索引名尚未使用的节点上先运行 python3 build_indices.py,再运行 python3 measure_recall.py。
脚本创建五个单主分片索引,写入相同的 4096 条 128 维归一化合成向量,统一使用余弦相似度和文档 ID。flat 扫描全精度向量,充当精确基准;hnsw 使用全精度向量遍历近似图;int8_hnsw、int4_hnsw 和 bbq_hnsw 保留 HNSW 检索结构,换用量化编码进行候选打分。
import json
import math
import os
import random
from urllib.request import Request, urlopen
BASE = os.getenv("ES_URL", "http:" + "//127.0.0.1:19238")
DIMS, COUNT = 128, 4096
KINDS = ("flat", "hnsw", "int8_hnsw", "int4_hnsw", "bbq_hnsw")
PREFIX = "simd-bbq-demo"
def name(kind):
return f"{PREFIX}-{kind.replace('_', '-')}"
def request(method, path, data=None):
headers = {}
if isinstance(data, bytes):
headers["Content-Type"] = "application/x-ndjson"
elif data is not None:
headers["Content-Type"] = "application/json"
data = json.dumps(data).encode()
req = Request(BASE + path, data=data, headers=headers, method=method)
with urlopen(req, timeout=60) as response:
return json.load(response)
def make_vector(rng):
values = [rng.gauss(0, 1) for _ in range(DIMS)]
norm = math.sqrt(sum(x * x for x in values))
return [x / norm for x in values]
def main():
print("Elasticsearch", request("GET", "/")["version"]["number"])
rng = random.Random(38)
lines = []
for i in range(COUNT):
lines.append(json.dumps({"index": {"_id": str(i)}}))
lines.append(json.dumps({"v": make_vector(rng)}))
payload = ("\n".join(lines) + "\n").encode()
print(f"seed=38 dims={DIMS} primary_shards=1")
for kind in KINDS:
path = "/" + name(kind)
request("PUT", path, {
"settings": {"number_of_shards": 1, "number_of_replicas": 0},
"mappings": {"properties": {"v": {
"type": "dense_vector", "dims": DIMS, "index": True,
"similarity": "cosine", "index_options": {"type": kind}
}}}
})
bulk = request("POST", path + "/_bulk?refresh=true", payload)
if bulk["errors"]:
raise RuntimeError(next(item for item in bulk["items"]
if "error" in item["index"]))
mapping = request("GET", path + "/_mapping")
actual = mapping[name(kind)]["mappings"]["properties"]["v"]
assert actual["index_options"]["type"] == kind
count = request("GET", path + "/_count")["count"]
assert count == COUNT
print(f"{kind:12} indexed={count} mapping=OK")
if __name__ == "__main__":
main()

让每条独立查询先从 flat 索引取得精确的前 10 条,再用重合的文档 ID 数除以 10,算出 Recall@10。对 24 次查询求平均,固定 k=10 和 num_candidates=120。量化索引先测 oversample=0,BBQ 再加测 oversample=3。
import random
from statistics import mean
from build_indices import KINDS, make_vector, name, request
K, N, QUERIES = 10, 120, 24
BARE = [(kind, 0) for kind in KINDS if kind != "flat"]
CASES = BARE + [("bbq_hnsw", 3)]
def top_ids(kind, vector, oversample=0):
knn = {"field": "v", "query_vector": vector, "k": K,
"num_candidates": N}
if kind.startswith(("int", "bbq")):
knn["rescore_vector"] = {"oversample": oversample}
result = request("POST", f"/{name(kind)}/_search",
{"size": K, "_source": False, "knn": knn})
assert result["_shards"]["failed"] == 0
ids = {hit["_id"] for hit in result["hits"]["hits"]}
assert len(ids) == K
return ids
rng = random.Random(2038)
recalls = {case: [] for case in CASES}
for _ in range(QUERIES):
query = make_vector(rng)
exact = top_ids("flat", query)
for kind, oversample in CASES:
hits = top_ids(kind, query, oversample)
recalls[kind, oversample].append(len(exact & hits) / K)
print(f"queries={QUERIES} k={K} num_candidates={N}")
print("baseline=flat metric=mean Recall@10")
for (kind, oversample), values in recalls.items():
print(f"{kind:12} oversample={oversample} recall={mean(values):.4f}")

这次运行中,无重排的 HNSW、INT8、INT4、BBQ 平均 Recall@10 分别为 0.9667、0.8417、0.7333、0.2750。BBQ 启用三倍过采样重排后为 0.9542。这些数字描述当前样本的候选命中情况。
num_candidates 决定每个分片近似搜索考虑的候选范围。启用 oversample=3 后,本例每分片最多取大约 30 个排名靠前的候选,用保留的原始向量重新打分,再返回 Top 10。原始邻居如果没进入重排池,重排也找不回来:可以分别增大候选范围和重排池,观察哪一步收益更明显。
SIMD(单指令多数据)在打分内核中并行处理多个向量分量,例如同时做乘加或位运算。Elastic 公开的实现从 Lucene 的 Java Vector API 演进到 C++ 原生 simdvec 内核,通过 Java FFI 调用,在支持的平台上为 x86 和 ARM 选择指令集路径,例如 AVX-512 和 NEON。HNSW 减少需要打分的向量数量,SIMD 降低执行一次评分的计算成本。实际使用的内核取决于 Elasticsearch、底层库、CPU 和运行环境,映射里只需选索引类型。
标量量化把浮点分量近似成更短的整数编码。INT8 每维 8 位,INT4 每维 4 位,能让更多候选数据进入同一块缓存,并使用适合整数的评分运算。BBQ 把库存向量的残差信息编码成每维 1 位,再用附加校正信息减小评分偏差。其近似打分采用非对称量化,查询可以使用较高精度的编码,再用位运算及计数等操作计算相似性。
对 128 维的向量,仅按编码主体估算,float32、INT8、INT4 和 BBQ 分别为 512、128、64 和 16 字节。HNSW 图、校正信息及其他结构还占空间,磁盘也保留原始浮点向量供重排和重建索引。INT4 要求维度为偶数,本例的 128 维也满足 BBQ 的维度要求。
本实验验证映射、检索、重排和召回计算。选生产配置时,在相同分片、段和过滤条件下使用真实查询,按同一精确基准比较 Recall@k,再记录预热后的 p95 延迟、向量文件大小和进程或页缓存占用。固定召回目标比较配置,能把更省内存、打分更快与候选覆盖不足带来的延迟变化区分开。