From 94b3ee6fea7ee0aa3b378ca4842cf0cad022f75a Mon Sep 17 00:00:00 2001 From: Ruyi Chen Date: Thu, 19 Nov 2026 10:04:21 +0800 Subject: [PATCH 1/2] Speed up the prefilter with a blocked, packed-posting kernel Count each target's best diagonal in cache-sized target blocks: posting lists are walked once with one cursor per expanded query code, a dense (targets x diagonals) histogram is stamped per block instead of cleared, and postings are packed as (target << pbits) | position in one uint32, halving the index. The top-N candidates are taken with argpartition on a unique (-score, target) key. Counts, candidates and scores are identical to the counting-sort kernel, which remains the fallback for very large databases and queries of 65,535+ tokens. --- rfoldsearch/prefilter.py | 207 +++++++++++++++++++++++++--- tests/test_prefilter_equivalence.py | 64 +++++++++ 2 files changed, 253 insertions(+), 18 deletions(-) diff --git a/rfoldsearch/prefilter.py b/rfoldsearch/prefilter.py index 02d885e..4a6a9f1 100644 --- a/rfoldsearch/prefilter.py +++ b/rfoldsearch/prefilter.py @@ -1,19 +1,30 @@ -"""The release prefilter: an O(n) compiled kernel over a CSR k-mer index. +"""The release prefilter: a compiled kernel over a CSR k-mer index. Computes exactly what the reference implementation computes -- per-target best-diagonal hit counts under similar-k-mer expansion, Foldseek's -double-match rule, ties broken toward the lower target index -- but in three -linear passes (counting-sort by target, diagonal scatter, per-segment -bincount) instead of materialising and sorting every posting. Equivalence to -`prefilter_reference` is enforced by tests/test_prefilter_equivalence.py and -was verified against the paper pipeline query-for-query at database sizes of -1,000 / 10,000 / 83,156 (20/20 identical rankings and scores at each). +double-match rule, ties broken toward the lower target index. + +Each code's posting list is sorted by (target, position), so the kernel walks +the targets in cache-sized blocks with one cursor per expanded query code and +reads every posting once. Inside a block, a dense (targets x diagonals) +histogram that fits in cache is incremented and each target's best diagonal +updated on the fly; a block stamp in the upper 16 bits of each cell retires +the previous block's counts without a clearing pass. Postings are packed as +``(target << pbits) | position`` in one uint32 when the database allows. +``best[t] = max_d count(t, d)`` does not depend on the order postings are +visited, so the counts are identical to the counting-sort kernel kept below +as the fallback (very large databases or queries of 65,535+ tokens). +Equivalence to `prefilter_reference` is enforced by +tests/test_prefilter_equivalence.py. """ import numpy as np from numba import njit KMER_K = 4 THRESH_FRAC = 0.75 +HIST_BYTES = 1 << 20 # diagonal histogram per target block; ~L2-sized +_COUNT_BITS = 16 # low bits of a histogram cell: the diagonal count +_COUNT_MASK = (1 << _COUNT_BITS) - 1 def build_csr_index(toks, n_codes): @@ -108,6 +119,126 @@ def _best_diagonal_counts(codes, qps, offsets, targets, positions, return best +def pack_postings(index): + """``(target << pbits) | position`` per posting as uint32, or None if it + does not fit in 32 bits.""" + pbits = max(1, int(index["max_tlen"] - 1).bit_length()) + tbits = max(1, int(index["n_targets"] - 1).bit_length()) + if pbits + tbits > 32: + return None + packed = ((index["targets"].astype(np.uint32) << np.uint32(pbits)) + | index["positions"].astype(np.uint32)) + return packed, pbits + + +@njit(cache=True) +def _best_diagonal_blocked(codes, qps, offsets, post, pbits, self_idx, + n_targets, lengths, n_q, bases, best, cursor, hist, + stamp0): + """Per-target best-diagonal counts over packed postings, block by block. + + Fills ``best`` and returns the next free histogram stamp. + """ + nc = codes.shape[0] + pmask = np.uint32((1 << pbits) - 1) + shift = np.uint32(pbits) + high = np.uint32(0xFFFFFFFF ^ _COUNT_MASK) + count_mask = np.uint32(_COUNT_MASK) + for t in range(n_targets): + best[t] = 0 + for i in range(nc): + cursor[i] = offsets[codes[i]] + stamp = stamp0 + t0 = 0 + while t0 < n_targets: + t1 = t0 + used = 0 + while t1 < n_targets: + width = lengths[t1] + n_q + if used + width > hist.size: + break + bases[t1] = used + lengths[t1] + used += width + t1 += 1 + limit = np.uint64(t1) << np.uint64(pbits) + tag = np.uint32(stamp) << np.uint32(_COUNT_BITS) + for i in range(nc): + e = cursor[i] + hi = offsets[codes[i] + 1] + qp = qps[i] + while e < hi: + w = post[e] + if np.uint64(w) >= limit: + break + t = np.int64(w >> shift) + if t != self_idx: + d = bases[t] + qp - np.int64(w & pmask) + c = hist[d] + if (c & high) != tag: + c = tag + c += np.uint32(1) + hist[d] = c + v = np.int32(c & count_mask) + if v > best[t]: + best[t] = v + e += 1 + cursor[i] = e + t0 = t1 + stamp += 1 + if stamp > _COUNT_MASK: + hist[:] = 0 + stamp = 1 + return stamp + + +@njit(cache=True) +def _best_diagonal_counts_packed(codes, qps, offsets, post, pbits, self_idx, + n_targets, span, seg_count, best, span_buf): + """`_best_diagonal_counts` reading packed postings (long-query fallback).""" + pmask = np.uint32((1 << pbits) - 1) + shift = np.uint32(pbits) + for t in range(n_targets): + seg_count[t] = 0 + best[t] = 0 + total = 0 + for i in range(codes.shape[0]): + for e in range(offsets[codes[i]], offsets[codes[i] + 1]): + t = np.int64(post[e] >> shift) + if t != self_idx: + seg_count[t] += 1 + total += 1 + seg_off = np.empty(n_targets + 1, np.int64) + s = 0 + for t in range(n_targets): + seg_off[t] = s + s += seg_count[t] + seg_off[n_targets] = s + diags = np.empty(total, np.int32) + cur = seg_off[:-1].copy() + for i in range(codes.shape[0]): + qp = qps[i] + for e in range(offsets[codes[i]], offsets[codes[i] + 1]): + w = post[e] + t = np.int64(w >> shift) + if t != self_idx: + diags[cur[t]] = qp - np.int64(w & pmask) + span + cur[t] += 1 + for t in range(n_targets): + lo, hi = seg_off[t], seg_off[t + 1] + if lo == hi: + continue + m = 0 + for e in range(lo, hi): + d = diags[e] + span_buf[d] += 1 + if span_buf[d] > m: + m = span_buf[d] + best[t] = m + for e in range(lo, hi): + span_buf[diags[e]] = 0 + return best + + class KmerPrefilter: """Build once per database, then `candidates()` per query.""" @@ -122,23 +253,63 @@ def __init__(self, toks, n_codes, sub, thr=None): self._best = np.zeros(n_t, np.int32) self._span = self.index["max_tlen"] self._buf = np.zeros(self._span + 8192, np.int32) + self.hist_bytes = HIST_BYTES + self._cursor = np.zeros(0, np.int64) + self._lengths = np.asarray([len(t) for t in toks], dtype=np.int64) + self._bases = np.empty(n_t, np.int64) + self._hist = np.zeros(0, np.uint32) + self._stamp = 1 + packed = pack_postings(self.index) + if packed is not None: + # the packed array replaces the two int32 posting arrays + self.index["packed"], self.index["pbits"] = packed + del self.index["targets"], self.index["positions"] + + def _best_diagonals(self, codes, qps, self_idx, n_q): + ix = self.index + n_t = ix["n_targets"] + if "packed" in ix and n_q < _COUNT_MASK: + width = self._span + n_q + 8 + capacity = max(width, self.hist_bytes // 4) + if self._hist.size < capacity: + self._hist = np.zeros(capacity, np.uint32) + self._stamp = 1 + if self._cursor.shape[0] < codes.shape[0]: + self._cursor = np.zeros(codes.shape[0], np.int64) + self._stamp = _best_diagonal_blocked( + codes, qps, ix["offsets"], ix["packed"], ix["pbits"], + self_idx, n_t, self._lengths, n_q, self._bases, self._best, + self._cursor, self._hist, self._stamp) + return self._best + # queries longer than any target need a wider diagonal buffer + need = self._span + n_q + 8 + if need > self._buf.shape[0]: + self._buf = np.zeros(need, np.int32) + if "packed" in ix: + return _best_diagonal_counts_packed( + codes, qps, ix["offsets"], ix["packed"], ix["pbits"], + self_idx, n_t, self._span, self._seg, self._best, self._buf) + return _best_diagonal_counts( + codes, qps, ix["offsets"], ix["targets"], ix["positions"], + self_idx, n_t, self._span, self._seg, self._best, self._buf) def candidates(self, qtok, top_n, min_diag, self_idx=-1): ix = self.index codes, qps = expand_query(qtok, ix["powers"], self.sub, self.diag, self.thr) if codes.size == 0: return np.zeros(0, np.int64), np.zeros(0, np.int64) - # queries longer than any target need a wider diagonal buffer - need = self._span + len(qtok) + 8 - if need > self._buf.shape[0]: - self._buf = np.zeros(need, np.int32) - best = _best_diagonal_counts( - codes, qps.astype(np.int64), ix["offsets"], ix["targets"], - ix["positions"], self_idx, ix["n_targets"], self._span, - self._seg, self._best, self._buf) + best = self._best_diagonals(codes, qps.astype(np.int64), self_idx, + len(qtok) - KMER_K + 1) cand = np.flatnonzero(best >= min_diag) - if cand.size == 0: + if cand.size == 0 or top_n <= 0: return np.zeros(0, np.int64), np.zeros(0, np.int64) scores = best[cand] - order = np.lexsort((cand, -scores)) - return cand[order][:top_n].astype(np.int64), scores[order][:top_n].astype(np.int64) + # (-score, target index) as one unique int64 key: selecting top_n + # before sorting avoids a full sort and keeps the tie rule exactly. + keys = -scores.astype(np.int64) * (ix["n_targets"] + 1) + cand + if cand.size > top_n: + keep = np.argpartition(keys, top_n - 1)[:top_n] + keep = keep[np.argsort(keys[keep], kind="stable")] + else: + keep = np.argsort(keys, kind="stable") + return cand[keep].astype(np.int64), scores[keep].astype(np.int64) diff --git a/tests/test_prefilter_equivalence.py b/tests/test_prefilter_equivalence.py index 990b8cd..4175ddb 100644 --- a/tests/test_prefilter_equivalence.py +++ b/tests/test_prefilter_equivalence.py @@ -3,6 +3,7 @@ import pytest from rfoldsearch import load_matrix +from rfoldsearch import prefilter as pf from rfoldsearch.prefilter import KMER_K, THRESH_FRAC, KmerPrefilter from rfoldsearch import prefilter_reference as ref @@ -43,3 +44,66 @@ def test_query_longer_than_targets(world): exp_c, exp_s = ref.candidates(long_q, toks, idx, expand, 2, -1, 100) assert np.array_equal(got_c, exp_c) assert np.array_equal(got_s, exp_s) + + +@pytest.mark.parametrize("top_n", [0, 1, 7, 50, 200, 1000]) +def test_partial_selection_matches_full_lexicographic_sort(world, top_n): + """The top-N selection preserves the (score, index) ordering exactly.""" + toks, K, sub = world + kernel = KmerPrefilter(toks, K, sub) + idx, powers = ref.build_index(toks, K) + expand = ref.make_expander(sub, K, powers, THRESH_FRAC * KMER_K) + for qi in (1, 19, 77, 149): + got_c, got_s = kernel.candidates(toks[qi], top_n, 1, self_idx=qi) + exp_c, exp_s = ref.candidates(toks[qi], toks, idx, expand, 1, qi, top_n) + assert np.array_equal(got_c, exp_c) + assert np.array_equal(got_s, exp_s) + + +@pytest.mark.parametrize("hist_bytes", [1, 4096, 1 << 16]) +def test_small_target_blocks(world, hist_bytes): + """Many small target blocks (and stamp reuse across queries) change nothing.""" + toks, K, sub = world + kernel = KmerPrefilter(toks, K, sub) + kernel.hist_bytes = hist_bytes + idx, powers = ref.build_index(toks, K) + expand = ref.make_expander(sub, K, powers, THRESH_FRAC * KMER_K) + for qi in range(0, 250, 13): + got_c, got_s = kernel.candidates(toks[qi], 100, 2, self_idx=qi) + exp_c, exp_s = ref.candidates(toks[qi], toks, idx, expand, 2, qi, 100) + assert np.array_equal(got_c, exp_c) + assert np.array_equal(got_s, exp_s) + + +def test_stamp_wraparound(world): + """Histogram stamps wrapping past 16 bits are cleared, not misread.""" + toks, K, sub = world + kernel = KmerPrefilter(toks, K, sub) + kernel.hist_bytes = 1 # one stamp per 8 targets + base_c, base_s = kernel.candidates(toks[5], 100, 2, self_idx=5) + kernel._stamp = pf._COUNT_MASK - 3 # wrap inside the next query + got_c, got_s = kernel.candidates(toks[5], 100, 2, self_idx=5) + assert np.array_equal(got_c, base_c) and np.array_equal(got_s, base_s) + + +def test_fallback_kernels_agree(world, monkeypatch): + """Packed counting-sort fallback and the unpacked kernel give the same counts.""" + toks, K, sub = world + packed = KmerPrefilter(toks, K, sub) + monkeypatch.setattr(pf, "pack_postings", lambda index: None) + unpacked = KmerPrefilter(toks, K, sub) + assert "packed" in packed.index and "packed" not in unpacked.index + for qi in (0, 42, 199): + q = np.asarray(toks[qi], np.int64) + codes, qps = pf.expand_query(q, packed.index["powers"], packed.sub, + packed.diag, packed.thr) + qps = qps.astype(np.int64) + n_q = len(q) - KMER_K + 1 + a = packed._best_diagonals(codes, qps, qi, n_q).copy() + b = unpacked._best_diagonals(codes, qps, qi, n_q).copy() + ix = packed.index + c = pf._best_diagonal_counts_packed( + codes, qps, ix["offsets"], ix["packed"], ix["pbits"], qi, + ix["n_targets"], packed._span, packed._seg, packed._best.copy(), + packed._buf).copy() + assert np.array_equal(a, b) and np.array_equal(a, c) From 6051b2c4cadc2e6d6d370091999fa4b38edafba6 Mon Sep 17 00:00:00 2001 From: Ruyi Chen Date: Thu, 19 Nov 2026 10:04:21 +0800 Subject: [PATCH 2/2] Batch the Smith-Waterman rerank across targets Align up to eight length-sorted candidates at once with the same float32 recurrence and tie rules as smith_waterman_traceback; padding cells can never beat a lane's best cell, so scores, end cells and paths are unchanged. Each batch's traceback pointers stay within 32 MiB (long chains get fewer lanes, down to one), inputs other than a float32 matrix and float32 gap penalties are scored pair by pair, and TM_a skips the block seed when the block is the whole alignment. Results equal score_pair bit for bit. --- rfoldsearch/structure_score.py | 269 +++++++++++++++++++++++++++++++-- tests/test_structure_score.py | 76 ++++++++++ 2 files changed, 333 insertions(+), 12 deletions(-) diff --git a/rfoldsearch/structure_score.py b/rfoldsearch/structure_score.py index 118edee..18d8188 100644 --- a/rfoldsearch/structure_score.py +++ b/rfoldsearch/structure_score.py @@ -1,6 +1,6 @@ """Structure-aware ranking: TM_a of a token Smith-Waterman alignment.""" import numpy as np -from numba import njit, prange +from numba import get_num_threads, njit, prange C4_INDEX = 1 # coords are (C3', C4', O4', C1', base anchor) per residue N_REFINE = 5 # superposition refinements per seed @@ -16,9 +16,11 @@ def smith_waterman_traceback(q, t, sub, go, ge): here; bit 3 the target-gap state was opened here. """ Lq, Lt = len(q), len(t) - ptr = np.zeros((Lq + 1, Lt + 1), np.uint8) + # interior pointer cells are all written before the traceback reads them + ptr = np.empty((Lq + 1, Lt + 1), np.uint8) H_prev = np.zeros(Lt + 1, np.float32) - H_curr = np.zeros(Lt + 1, np.float32) + H_curr = np.empty(Lt + 1, np.float32) + H_curr[0] = 0.0 F = np.full(Lt + 1, -np.inf, np.float32) best, bi, bj = np.float32(0.0), 0, 0 for i in range(1, Lq + 1): @@ -56,9 +58,11 @@ def smith_waterman_traceback(q, t, sub, go, ge): ptr[i, j] = p | src if v > best: best, bi, bj = v, i, j - for j in range(Lt + 1): - H_prev[j] = H_curr[j] - H_curr[j] = 0.0 + # swap rows: every H_curr[j >= 1] is rewritten in the next row + tmp = H_prev + H_prev = H_curr + H_curr = tmp + H_curr[0] = 0.0 qa = np.empty(min(Lq, Lt), np.int64) ta = np.empty(min(Lq, Lt), np.int64) k, i, j, state = 0, bi, bj, 0 @@ -157,7 +161,7 @@ def alignment_tm_a(a, b, Lq, Lt, block_start=0, block_end=0): return 0.0 d0q, d0t = d0(Lq), d0(Lt) best = _refine(a, b, d0q, d0t, Lq, Lt, np.ones(n, np.bool_)) - if block_end - block_start >= MIN_PAIRS: + if block_end - block_start >= MIN_PAIRS and (block_start != 0 or block_end != n): sel = np.zeros(n, np.bool_) sel[block_start:block_end] = True v = _refine(a, b, d0q, d0t, Lq, Lt, sel) @@ -174,13 +178,232 @@ def score_pair(q, qxyz, t, txyz, sub, go, ge): return s, alignment_tm_a(qxyz[qa], txyz[ta], len(q), len(t), bs, be), len(qa) -@njit(parallel=True, cache=True) -def score_candidates(q, qxyz, cand, toks, offsets, xyz, sub, go, ge): - """Return (S_SW, TM_a, aligned pairs) for every candidate in parallel. +LANES = 8 # targets aligned together by the batched SW +_PAD = np.float32(-1e30) # substitution score of the padding token +PTR_BUDGET = 1 << 25 # traceback pointer bytes per batch (32 MiB); a + # longer batch gets fewer lanes, down to one pair - Chain c occupies rows ``offsets[c]:offsets[c + 1]`` of flattened ``toks`` - and ``xyz``. + +@njit(cache=True) +def _sw_lanes(qc, prof, go, ge, ptr, H_prev, H_curr, F, E, best, bi, bj): + """Affine-gap SW of one query against LANES targets at once. + + The same recurrence, float32 operations and tie rules as + `smith_waterman_traceback`, cell for cell; only independent alignments + are interleaved (lane loop innermost). ``prof[c, j, l]`` is the score of + query code ``c`` against position ``j`` of lane ``l``; lanes shorter than + the batch are padded with ``_PAD``. A padded cell can never exceed the + running best of its lane (its value is below an earlier cell of the same + lane, or 0), and the traceback only moves up or left, so padding changes + neither the score, the end cell nor the path. """ + Lq = qc.shape[0] + T = prof.shape[1] + L = prof.shape[2] + ninf = np.float32(-np.inf) + zero = np.float32(0.0) + for j in range(T + 1): + for l in range(L): + H_prev[j, l] = zero + F[j, l] = ninf + for l in range(L): + H_curr[0, l] = zero + best[l] = zero + bi[l] = 0 + bj[l] = 0 + for i in range(1, Lq + 1): + row = prof[qc[i - 1]] + for l in range(L): + E[l] = ninf + for j in range(1, T + 1): + for l in range(L): + f_open = H_prev[j, l] + go + f_ext = F[j, l] + ge + fo = f_open > f_ext + fv = f_open if fo else f_ext + F[j, l] = fv + e_open = H_curr[j - 1, l] + go + e_ext = E[l] + ge + eo = e_open > e_ext + ev = e_open if eo else e_ext + E[l] = ev + v0 = H_prev[j - 1, l] + row[j - 1, l] + c2 = ev > v0 + v1 = ev if c2 else v0 + c3 = fv > v1 + v2 = fv if c3 else v1 + v = zero if v2 < zero else v2 + src = np.uint8(3) if c3 else (np.uint8(2) if c2 else np.uint8(1)) + src = np.uint8(0) if v == zero else src + H_curr[j, l] = v + ptr[i, j, l] = (src | (np.uint8(8) if fo else np.uint8(0)) + | (np.uint8(4) if eo else np.uint8(0))) + better = v > best[l] + best[l] = v if better else best[l] + bi[l] = i if better else bi[l] + bj[l] = j if better else bj[l] + tmp = H_prev + H_prev = H_curr + H_curr = tmp + for l in range(L): + H_curr[0, l] = zero + + +@njit(cache=True) +def _traceback_lane(ptr, l, i, j, Lq, Lt): + """`smith_waterman_traceback`'s traceback, reading lane ``l``.""" + qa = np.empty(min(Lq, Lt), np.int64) + ta = np.empty(min(Lq, Lt), np.int64) + k, state = 0, 0 + while i > 0 and j > 0: + c = ptr[i, j, l] + if state == 0: + src = c & 3 + if src == 0: + break + if src == 1: + qa[k], ta[k] = i - 1, j - 1 + k += 1 + i, j = i - 1, j - 1 + elif src == 2: + state = 1 + else: + state = 2 + elif state == 1: # gap in query: move left + if c & 4: + state = 0 + j -= 1 + else: # gap in target: move up + if c & 8: + state = 0 + i -= 1 + return qa[:k][::-1].copy(), ta[:k][::-1].copy() + + +@njit(cache=True) +def _query_codes(q, n_codes): + """Query recoded to 0..U-1 over the codes it uses, and those codes.""" + remap = np.full(n_codes, -1, np.int64) + used = 0 + for i in range(q.shape[0]): + if remap[q[i]] < 0: + remap[q[i]] = used + used += 1 + codes = np.empty(used, np.int64) + for a in range(n_codes): + if remap[a] >= 0: + codes[remap[a]] = a + qc = np.empty(q.shape[0], np.int64) + for i in range(q.shape[0]): + qc[i] = remap[q[i]] + return qc, codes + + +@njit(cache=True) +def _score_batch(lo, hi, q, qc, qcodes, qxyz, cand, order, lens, toks, offsets, + xyz, sub, go, ge, S, T, A): + """Score candidates ``order[lo:hi]`` (one lane each) into S, T, A.""" + nl = hi - lo + width = 0 + for k in range(lo, hi): + width = max(width, lens[order[k]]) + n_codes = sub.shape[0] + tb = np.full((width, nl), n_codes, np.int64) + for k in range(lo, hi): + c = cand[order[k]] + o = offsets[c] + for j in range(lens[order[k]]): + tb[j, k - lo] = toks[o + j] + prof = np.empty((qcodes.shape[0], width, nl), np.float32) + for u in range(qcodes.shape[0]): + a = qcodes[u] + for j in range(width): + for l in range(nl): + t = tb[j, l] + prof[u, j, l] = sub[a, t] if t < n_codes else _PAD + Lq = q.shape[0] + ptr = np.empty((Lq + 1, width + 1, nl), np.uint8) + H_prev = np.empty((width + 1, nl), np.float32) + H_curr = np.empty((width + 1, nl), np.float32) + F = np.empty((width + 1, nl), np.float32) + E = np.empty(nl, np.float32) + best = np.empty(nl, np.float32) + bi = np.empty(nl, np.int64) + bj = np.empty(nl, np.int64) + _sw_lanes(qc, prof, go, ge, ptr, H_prev, H_curr, F, E, best, bi, bj) + for k in range(lo, hi): + l = k - lo + idx = order[k] + c = cand[idx] + o = offsets[c] + Lt = lens[idx] + qa, ta = _traceback_lane(ptr, l, bi[l], bj[l], Lq, Lt) + t = toks[o:o + Lt] + bs, be = _best_block(q, t, qa, ta, sub) + S[idx] = best[l] + T[idx] = alignment_tm_a(qxyz[qa], xyz[o:o + Lt][ta], Lq, Lt, bs, be) + A[idx] = len(qa) + + +@njit(cache=True) +def _batch_bounds(Lq, lens, order, lanes, ptr_budget): + """Split the length-sorted candidates into batches of at most ``lanes`` + whose pointer matrix ((Lq + 1) x (width + 1) bytes per lane) stays within + ``ptr_budget``; a single candidate always forms a batch on its own.""" + n = order.shape[0] + bounds = np.empty(n + 1, np.int64) + nb = 0 + bounds[0] = 0 + lo = 0 + while lo < n: + hi = lo + 1 + while hi < n and hi - lo < lanes: + # lengths ascend along ``order``, so the newcomer sets the width + if (Lq + 1) * (lens[order[hi]] + 1) * (hi - lo + 1) > ptr_budget: + break + hi += 1 + nb += 1 + bounds[nb] = hi + lo = hi + return bounds[:nb + 1] + + +@njit(cache=True) +def _score_setup(q, cand, offsets, n_codes, lanes, ptr_budget): + n = cand.shape[0] + lens = offsets[cand + 1] - offsets[cand] + order = np.argsort(lens, kind="mergesort") # similar lengths share a batch + qc, qcodes = _query_codes(q, n_codes) + bounds = _batch_bounds(q.shape[0], lens, order, lanes, ptr_budget) + return (lens, order, qc, qcodes, np.zeros(n), np.zeros(n), + np.zeros(n, np.int64), bounds) + + +@njit(cache=True) +def _score_candidates_serial(q, qxyz, cand, toks, offsets, xyz, sub, go, ge, + lanes, ptr_budget): + lens, order, qc, qcodes, S, T, A, bounds = _score_setup( + q, cand, offsets, sub.shape[0], lanes, ptr_budget) + for b in range(bounds.shape[0] - 1): + _score_batch(bounds[b], bounds[b + 1], q, qc, qcodes, qxyz, cand, + order, lens, toks, offsets, xyz, sub, go, ge, S, T, A) + return S, T, A + + +@njit(parallel=True, cache=True) +def _score_candidates_parallel(q, qxyz, cand, toks, offsets, xyz, sub, go, ge, + lanes, ptr_budget): + lens, order, qc, qcodes, S, T, A, bounds = _score_setup( + q, cand, offsets, sub.shape[0], lanes, ptr_budget) + for b in prange(bounds.shape[0] - 1): + _score_batch(bounds[b], bounds[b + 1], q, qc, qcodes, qxyz, cand, + order, lens, toks, offsets, xyz, sub, go, ge, S, T, A) + return S, T, A + + +@njit(parallel=True, cache=True) +def _score_candidates_pairs(q, qxyz, cand, toks, offsets, xyz, sub, go, ge): + """One `score_pair` per candidate: the path for non-float32 inputs.""" n = len(cand) S = np.zeros(n) T = np.zeros(n) @@ -192,6 +415,28 @@ def score_candidates(q, qxyz, cand, toks, offsets, xyz, sub, go, ge): return S, T, A +def score_candidates(q, qxyz, cand, toks, offsets, xyz, sub, go, ge): + """Return (S_SW, TM_a, aligned pairs) for every candidate. + + Chain c occupies rows ``offsets[c]:offsets[c + 1]`` of flattened ``toks`` + and ``xyz``. Values equal `score_pair` on each candidate bit for bit. + With a float32 matrix and float32 gap penalties (what `Searcher` passes) + candidates are aligned up to LANES at a time, with the pointer matrix of + a batch kept within PTR_BUDGET bytes; any other input dtype is scored + pair by pair, since the batched recurrence is float32 throughout. + Batches run in parallel unless Numba is limited to one thread. + """ + cand = np.asarray(cand, np.int64) + if not (sub.dtype == np.float32 and isinstance(go, np.float32) + and isinstance(ge, np.float32)): + return _score_candidates_pairs(q, qxyz, cand, toks, offsets, xyz, + sub, go, ge) + scorer = (_score_candidates_serial if get_num_threads() == 1 + else _score_candidates_parallel) + return scorer(q, qxyz, cand, toks, offsets, xyz, sub, go, ge, + LANES, PTR_BUDGET) + + def c4_coords(entry, n_tokens): """C4' coordinates of the tokenised residues, or None if unavailable.""" coords, mask = entry.get("coords"), entry.get("mask") diff --git a/tests/test_structure_score.py b/tests/test_structure_score.py index 58ca5aa..b85bd8c 100644 --- a/tests/test_structure_score.py +++ b/tests/test_structure_score.py @@ -109,3 +109,79 @@ def test_tm_a_requires_database_coordinates(tmp_path): "checkpoint": "synthetic"}, path) with pytest.raises(ValueError, match="every database chain"): Searcher(str(path)).search_id("c0", top_k=2) + + +def _batched_world(rng): + lens = np.r_[1, 2, 3, 5, rng.integers(4, 260, size=60)] + base = rng.integers(0, 80, size=300) + toks, xyz = [], [] + for n in lens: + t = base[:n].copy() + k = max(1, n // 4) + t[rng.integers(0, n, k)] = rng.integers(0, 80, k) + toks.append(t) + xyz.append(np.cumsum(rng.normal(scale=3.0, size=(n, 3)), axis=0)) + offsets = np.zeros(len(toks) + 1, np.int64) + offsets[1:] = np.cumsum(lens) + return base, np.concatenate(toks).astype(np.int64), offsets, np.concatenate(xyz) + + +def _query(rng, base, qn): + q = base[:qn].copy() + q[rng.integers(0, qn, qn // 5)] = rng.integers(0, 80, qn // 5) + return q, np.cumsum(rng.normal(scale=3.0, size=(qn, 3)), axis=0) + + +@pytest.mark.parametrize("parallel", [False, True]) +# shipped batching; one pair per batch; a budget that mixes lane counts +@pytest.mark.parametrize("lanes,budget", [(ss.LANES, ss.PTR_BUDGET), (ss.LANES, 1), + (3, 150_000)]) +def test_batched_scorer_matches_score_pair_bitwise(parallel, lanes, budget): + """The lane-batched scorer equals score_pair per candidate, bit for bit, + whatever the number of lanes per batch.""" + rng = np.random.default_rng(3) + sub = load_matrix() + base, flat_t, offsets, flat_x = _batched_world(rng) + for qn in (4, 37, 150, 290): + q, qx = _query(rng, base, qn) + cand = rng.permutation(len(offsets) - 1).astype(np.int64)[:61] + scorer = (ss._score_candidates_parallel if parallel + else ss._score_candidates_serial) + S, T, A = scorer(q, qx, cand, flat_t, offsets, flat_x, sub, GO, GE, + lanes, budget) + for k, c in enumerate(cand): + lo, hi = offsets[c], offsets[c + 1] + s, tm, a = ss.score_pair(q, qx, flat_t[lo:hi], flat_x[lo:hi], sub, GO, GE) + assert S[k] == s and T[k] == tm and A[k] == a + + +def test_batch_bounds_respect_lanes_and_budget(): + rng = np.random.default_rng(5) + lens = rng.integers(1, 3000, size=500).astype(np.int64) + order = np.argsort(lens, kind="mergesort") + for Lq, lanes, budget in ((50, 8, 1 << 25), (2800, 8, 1 << 25), (4000, 8, 1), + (300, 5, 1_000_000)): + b = ss._batch_bounds(Lq, lens, order, lanes, budget) + assert b[0] == 0 and b[-1] == len(lens) and np.all(np.diff(b) >= 1) + for lo, hi in zip(b[:-1], b[1:]): + assert hi - lo <= lanes + width = lens[order[lo:hi]].max() + assert hi - lo == 1 or (Lq + 1) * (width + 1) * (hi - lo) <= budget + + +@pytest.mark.parametrize("dtype,gaps", [(np.float64, (GO, GE)), + (np.float32, (float(GAP_OPEN), float(GAP_EXTEND)))]) +def test_non_float32_inputs_match_score_pair(dtype, gaps): + """score_candidates with a float64 matrix or Python-float gaps scores pair + by pair, so it still equals score_pair given the same inputs.""" + rng = np.random.default_rng(4) + sub = load_matrix().astype(dtype) + go, ge = gaps + base, flat_t, offsets, flat_x = _batched_world(rng) + q, qx = _query(rng, base, 120) + cand = rng.permutation(len(offsets) - 1).astype(np.int64)[:40] + S, T, A = ss.score_candidates(q, qx, cand, flat_t, offsets, flat_x, sub, go, ge) + for k, c in enumerate(cand): + lo, hi = offsets[c], offsets[c + 1] + s, tm, a = ss.score_pair(q, qx, flat_t[lo:hi], flat_x[lo:hi], sub, go, ge) + assert S[k] == s and T[k] == tm and A[k] == a