Exact MaxSim: stream document chunks under a memory budget (final)
Browse files102 unmodified lines103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134102 unmodified linesreturn outdef maxsim_topk(Qv, Dv):"""Exact MaxSim over the whole corpus, chunked. Docs sorted by length to limit padding."""dev = "cuda"order = np.argsort([v.shape[0] for v in Dv])nq = len(Qv)best_s = torch.full((nq, K + 1), -1e9, device=dev); best_i = torch.zeros((nq, K + 1), dtype=torch.long, device=dev)dchunks = []for c in range(0, len(order), 256):ids = order[c:c + 256]X, M = _pad([Dv[i] for i in ids], dev)dchunks.append((torch.as_tensor(ids, device=dev), X, M))for qs in range(0, nq, 64):Xq, Mq = _pad(Qv[qs:qs + 64], dev)bq = Xq.shape[0]cs, ci = [best_s[qs:qs + bq]], [best_i[qs:qs + bq]]for ids, X, M in dchunks:s = torch.einsum("qid,njd->qinj", Xq, X).float() # [bq, Lq, nd, Ld]s = s.masked_fill(~M[None, None], -1e4).amax(-1) # [bq, Lq, nd]s = (s * Mq[:, :, None]).sum(1) # [bq, nd]cs.append(s); ci.append(ids[None].expand(bq, -1))if len(cs) > 16:S = torch.cat(cs, 1); I = torch.cat(ci, 1)v, ix = S.topk(K + 1, dim=1); cs, ci = [v], [torch.gather(I, 1, ix)]S = torch.cat(cs, 1); I = torch.cat(ci, 1)v, ix = S.topk(K + 1, dim=1)best_s[qs:qs + bq] = v; best_i[qs:qs + bq] = torch.gather(I, 1, ix)return best_s.cpu().numpy(), best_i.cpu().numpy()102 unmodified lines103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138102 unmodified linesreturn outdef maxsim_topk(Qv, Dv, budget=1.5 * 2**30):"""Exact MaxSim over the whole corpus. Docs are streamed to the GPU in length-sorted chunks of 256 (each moved once);queries stay on the GPU in length-sorted blocks of 64; the [bq, Lq, nd, Ld] score tensor is split to stay under budget."""dev = "cuda"nq = len(Qv)qord = np.argsort([v.shape[0] for v in Qv])qblocks = []for c in range(0, nq, 64):ids = qord[c:c + 64]Xq, Mq = _pad([Qv[i] for i in ids], dev)qblocks.append((torch.as_tensor(ids, device=dev), Xq, Mq))best_s = torch.full((nq, K + 1), -1e9, device=dev); best_i = torch.zeros((nq, K + 1), dtype=torch.long, device=dev)dord = np.argsort([v.shape[0] for v in Dv])for c in range(0, len(dord), 256):ids = dord[c:c + 256]X, M = _pad([Dv[i] for i in ids], dev)dids = torch.as_tensor(ids, device=dev)for qids, Xq, Mq in qblocks:bq, Lq = Xq.shape[:2]step = max(1, int(budget // (bq * Lq * X.shape[1] * 6))) # bf16 einsum out + fp32 copyparts = []for s0 in range(0, X.shape[0], step):s = torch.einsum("qid,njd->qinj", Xq, X[s0:s0 + step]).float() # [bq, Lq, n, Ld]s = s.masked_fill(~M[s0:s0 + step][None, None], -1e4).amax(-1) # [bq, Lq, n]parts.append((s * Mq[:, :, None]).sum(1)) # [bq, n]S = torch.cat([best_s[qids]] + parts, 1)I = torch.cat([best_i[qids], dids[None].expand(bq, -1)], 1)v, ix = S.topk(K + 1, dim=1)best_s[qids] = v; best_i[qids] = torch.gather(I, 1, ix)del X, Mreturn best_s.cpu().numpy(), best_i.cpu().numpy()
code/run2/worker.py+26-22