"""PE-means: e-means with principal-axis, gain-ranked revival. This subclasses the official ``faiss.contrib.e_means.NumpyEmeans``. Every line of the e-means recipe (batch law, step law, cosine schedule, EMA update, closing means) is inherited unchanged. Only dead-cluster revival is replaced: * faiss revival: donors are sampled in proportion to their EMA mass N_j, and the donor is copied with a +/-1e-4 relative nudge, so the two copies are only pulled apart by later assignments. * PE-means revival: 1. Each cluster tracks its principal axis u_j by streaming power iteration on EMA statistics: V_j <- EMA(sum_i (e_i . u_j) e_i), u_j = V_j / |V_j|, with e_i = x_i - c_j. The variance along the axis is lambda_j = EMA(sum_i (e_i . u_j)^2) / N_j. Cost: O(B d) per batch, negligible next to the O(B k d) assignment. 2. Donors are ranked by the distortion a split removes. For a Gaussian cluster, the best 2-means split along u_j cuts distortion by (2/pi) * N_j * lambda_j (each half keeps variance (1 - 2/pi) * lambda_j along u_j), so the score is the EMA sum of squared projections (``gain="greedy"``), or that score used as sampling weight (``gain="sample"``). 3. The donor is split along +/- u_j by delta = sqrt(2/pi) * sqrt(lambda_j), the centroids of the two half-Gaussians, so both children start at the optimal 2-means split position instead of on top of each other. Each component is a switch, so the ablation in benchmarks/ isolates it. """ import math import numpy as np from faiss.contrib.e_means import NumpyEmeans _HALF_GAUSS = math.sqrt(2.0 / math.pi) # E|z| for z ~ N(0,1): child offset in sigma units class PEmeans(NumpyEmeans): def __init__(self, d, k, *args, split="principal", gain="greedy", offset_scale=1.0, score="axis", tau=None, revive_every=5, swap=0.0, swap_window=(0.1, 0.9), split_pass=False, revive_until=1.0, closing_frac=1.0, child_mass=0.5, tau_end=None, every_until=0.0, approx=None, graph=None, approx_last=None, momentum=0.0, momentum_until=1.0, probe_sched=None, polish=0, polish_probes=None, polish_second=None, hnsw=None, codec="flat", anneal=0.0, anneal_until=0.7, batch_sched=None, fused=False, **kwargs): """split: "principal" (PE-means) or "faiss" (official nudge). gain: "greedy" (top expected distortion cut), "sample" (Gumbel top-k on it), or "usage" (official: Gumbel top-k on N_j). offset_scale: multiplies the sqrt(2/pi) sigma child offset (1 = Gaussian optimum). score: "axis" ranks donors by N*lambda_1, "total" by N*trace (total distortion). tau: revival threshold as a fraction of mean mass (None = faiss default, 0.1 here). revive_every: batches between revival checks (faiss: 5). swap: at each revival check, also move up to swap*k live clusters whose deletion cost (EMA of sum of d2 - d1 over their rows) is below the best donor's split gain (2/pi)*N*lambda_1. 0 disables (needs 2-NN assignment). swap_window: fraction of training steps during which swaps are allowed. split_pass: when a split happens in the last epoch, split the donor's closing statistics consistently (half the count each, means at c +/- delta). revive_until: no revival or swaps after this fraction of training steps. closing_frac: build the closing means from only the last closing_frac of the final epoch's batches (fresher assignments; 1.0 = faiss). child_mass: EMA mass each child inherits, as a fraction of the donor's (0.5 = faiss). tau_end: if set, the revival threshold follows a cosine from tau to tau_end. every_until: revive every batch during this first fraction of training, then every revive_every batches. approx: (coarse_lists, nprobe) to assign with an IVF over the centroids in every epoch but the last (exact). None = exact everywhere. graph: (m, refresh) graph-pruned assignment with label memory: in every epoch but the last, a row is compared only with the m nearest centroids of the centroid it was assigned to last time (centroid k-NN graph rebuilt every `refresh` batches). Rows without a previous label, and the whole last epoch, are assigned exactly. momentum: heavy-ball term on centroid displacements, c += beta * (previous step's move), applied during the first momentum_until fraction of steps. probe_sched: (p_first, p_last) probes, linearly interpolated over the non-last epochs' steps (overrides the sqrt(k)/8 rule). polish: number of Lloyd steps after training (assign every row to the final centroids, recompute means); polish_probes = IVF probes (None = exact); polish_second = the mode of every polish step after the first (default: same as the first).""" super().__init__(d, k, *args, **kwargs) if split not in ("principal", "faiss", "half", "abs") or gain not in ("greedy", "sample", "usage") \ or score not in ("axis", "total", "half", "abs"): raise ValueError("unknown split, gain or score rule") self.split, self.gain, self.score = split, gain, score self.offset_scale, self.revive_every = float(offset_scale), int(revive_every) if tau is not None: self._unused_threshold = float(tau) self.swap, self.swap_window = float(swap), tuple(swap_window) self.split_pass, self.revive_until = bool(split_pass), float(revive_until) self.closing_frac = float(closing_frac) self.child_mass, self.tau_end, self.every_until = float(child_mass), tau_end, float(every_until) self.approx = approx self.approx_last = approx_last # probes for an approximate LAST epoch (None = exact) if approx == "auto" and k < APPROX_MIN_K: # Small k: the exact GEMM is cheap and the per-batch index build does not pay # (k = 1,024: sparse 1.80x e-means' time, exact 0.82x; iteration 23). self.approx = None; self.approx_last = None self.graph = graph self.momentum, self.momentum_until = float(momentum), float(momentum_until) self.probe_sched, self.polish, self.polish_probes = probe_sched, int(polish), polish_probes self.polish_second = polish_second self.hnsw = hnsw # (M, efSearch early, efSearch last epoch, rebuild every b batches) self._hnsw = None self.anneal, self.anneal_until = float(anneal), float(anneal_until) self.batch_sched = batch_sched self.fused = bool(fused) # one Numba pass for sums, counts and axis statistics self._in_fused = False # (first, last) multipliers of the batch size, linear in rows self._half = self._b_half = self._absp = self._b_abs = None self.codec = codec # IVF list storage: "flat" (float32) or "fp16" (half-precision scans) self._vel = None self._mem = self._cgraph = self._cur_index = None self._cur_pos = 0 self.n_graph_rows = 0 self.n_graph_fallback = 0 self.graph_checks = [] self._tau0 = self._unused_threshold self._coarse = None self.n_swaps = 0 self._axis = self._axis_sum = self._proj_sq = self._dist = self._delcost = None # ---------------------------------------------------------------- statistics def begin(self, global_n, init_centroids): out = super().begin(global_n, init_centroids) rng = np.random.RandomState(self.seed + 7919) axis = rng.standard_normal((self.k, self.d)).astype("float32") axis /= np.linalg.norm(axis, axis=1, keepdims=True) self._axis = axis # u_j, unit rows self._axis_sum = np.zeros((self.k, self.d), "float32") # EMA of sum (e.u) e self._proj_sq = np.zeros(self.k, "float64") # EMA of sum (e.u)^2 self._b_axis = np.zeros((self.k, self.d), "float32") self._b_proj = np.zeros(self.k, "float64") self._dist = np.zeros(self.k, "float64") # EMA of sum |e|^2 self._b_dist = np.zeros(self.k, "float64") self._delcost = np.zeros(self.k, "float64") # EMA of sum (d2 - d1) self._b_del = np.zeros(self.k, "float64") if self.split in ("half", "abs") or self.score in ("half", "abs"): self._half = np.zeros((self.k, self.d), "float32") # EMA of sum sign(p) e self._b_half = np.zeros((self.k, self.d), "float32") self._absp = np.zeros(self.k, "float64") # EMA of sum |p| self._b_abs = np.zeros(self.k, "float64") if self.graph is not None: self._mem = np.full(int(global_n), -1, "int64") # last label of every row return out def _accumulate(self, x, index=None, labels_out=None): self._cur_index, self._cur_pos = index, 0 return super()._accumulate(x, index, labels_out) def _accumulate_core(self, x, index=None, labels_out=None): """e-means' accumulation with the per-row statistics fused into one Numba pass (same quantities; only the floating-point summation order differs).""" if not (self.fused and self._half is None and self.score == "axis" and self.swap <= 0 and not self.spherical and self._usage is not None and index is not None): return super()._accumulate_core(x, index, labels_out) from aries._kernels import fused_stats n = len(index) pending_n = 0 if self._pending_stats is None else self._pending_stats["n"] if pending_n == 0: self._batch_stats.fill(0) self._batch_objective = np.float64(0) self._batch_centroids = self._readout() self._batch_accumulation = self._batch_stats acc = self._batch_accumulation sums, counts = acc[:, :-1], acc[:, -1] centroids = self._batch_centroids last = self._epoch == len(self.recipe["epoch_rows"]) - 1 captured = None if labels_out is None else labels_out[:n] if captured is None and self.capture_assignments and last: captured = np.empty(n, dtype="int64") objective = self._batch_objective chunk = self.recipe["assignment_chunk_size"] for b0 in range(0, n, chunk): rows = x[index[b0:min(b0 + chunk, n)]] self._in_fused = True try: distance, labels = self._assign_rows(rows, centroids) finally: self._in_fused = False if captured is not None: captured[b0:b0 + len(rows)] = labels objective += distance.sum(dtype="float64") cnt = np.zeros(self.k, np.float64) fused_stats(rows, labels, centroids, self._axis, sums, cnt, self._b_axis, self._b_proj) counts += cnt.astype(counts.dtype) self._batch_objective = objective total_n = pending_n + n complete = total_n == self._local_batch_size() or total_n == 0 stats = {"sums": sums if complete else None, "counts": counts if complete else None, "objective": objective, "n": total_n} if captured is not None: stats["labels"] = captured return stats def _graph_assign(self, x, centroids, ids): import faiss m, refresh = self.graph[:2] verify, tol = (self.graph[2], self.graph[3]) if len(self.graph) > 3 else (0.0, 1.0) if self._cgraph is None or self._step % refresh == 0 and self._cgraph[0] != self._step: _, G = faiss.knn(np.ascontiguousarray(centroids, dtype="float32"), np.ascontiguousarray(centroids, dtype="float32"), m) self._cgraph = (self._step, G) G = self._cgraph[1] prev = self._mem[ids] known = prev >= 0 D = np.empty(len(x), "float32"); L = np.empty(len(x), "int64") if (~known).any(): d0, l0 = faiss.knn(x[~known], centroids, 1) D[~known], L[~known] = d0[:, 0], l0[:, 0] if known.any(): from aries._kernels import cand_assign D[known], L[known] = cand_assign(x[known], centroids, G, prev[known]) if verify > 0: # self-verification on a random subset kidx = np.flatnonzero(known) rs = np.random.RandomState(self._step) chk = kidx[rs.choice(len(kidx), max(1, int(verify * len(kidx))), replace=False)] _, le = faiss.knn(x[chk], centroids, 1) miss = float((le[:, 0] != L[chk]).mean()) self.graph_checks.append(miss) if miss > tol: # unsafe: exact batch, refresh the graph next time d0, l0 = faiss.knn(x[known], centroids, 1) D[known], L[known] = d0[:, 0], l0[:, 0] self._cgraph = None self.n_graph_fallback += 1 return D, L self.n_graph_rows += int(known.sum()) return D, L def _hnsw_assign(self, x, centroids, last): """Nearest centroid through an HNSW graph over the centroids. The graph is rebuilt every `rebuild` batches and after any split; in between, the stored vectors are overwritten in place with the current centroids (positions change, links are kept).""" import faiss M, ef0, ef1, rebuild = self.hnsw C32 = np.ascontiguousarray(centroids, dtype="float32") stale = self._hnsw is None or self._step - self._hnsw[1] >= rebuild or self._hnsw[2] != self.n_splits if stale: h = faiss.IndexHNSWFlat(self.d, int(M)); h.hnsw.efConstruction = 40; h.add(C32) self._hnsw = [h, self._step, self.n_splits] elif self._hnsw[3] != self._step: xb = faiss.rev_swig_ptr(faiss.downcast_index(self._hnsw[0].storage).get_xb(), self.k * self.d) xb[:] = C32.ravel() self._hnsw = self._hnsw[:3] + [self._step] h = self._hnsw[0]; h.hnsw.efSearch = int(ef1 if last else ef0) D, I = h.search(np.ascontiguousarray(x, dtype="float32"), 1) return D[:, 0].copy(), I[:, 0].copy() def _approx_assign(self, x, centroids, nprobe_override=None): import faiss if self.approx == "auto": # rule: sqrt(k) k-means cells, sqrt(k)/8 probes nl = max(8, int(round(math.sqrt(self.k)))); nprobe, mode = max(4, nl // 8), "km" else: nl, nprobe = self.approx[:2] mode = self.approx[2] if len(self.approx) > 2 else "sample" if self.probe_sched is not None and nprobe_override is None: frac = self._step / max(1, self.recipe["total_steps"]) p0, p1 = self.probe_sched nprobe = int(round(p0 + (p1 - p0) * min(1.0, frac))) if nprobe_override is not None: nprobe = int(nprobe_override) if self._coarse is None or self._coarse[0] != self._epoch: C32 = np.ascontiguousarray(centroids, dtype="float32") if mode == "km": # coarse cells grouping nearby centroids km = faiss.Kmeans(self.d, nl, niter=20, seed=self.seed + self._epoch, max_points_per_centroid=10**9) km.train(C32); sub = km.centroids else: sub = C32[np.random.RandomState(self.seed + self._epoch).choice(len(C32), nl, replace=False)] q = faiss.IndexFlatL2(self.d); q.add(np.ascontiguousarray(sub, dtype="float32")) self._coarse = (self._epoch, q) q = self._coarse[1] C32 = np.ascontiguousarray(centroids, dtype="float32"); xq = x if self.codec == "fp16": ivf = faiss.IndexIVFScalarQuantizer(q, self.d, nl, faiss.ScalarQuantizer.QT_fp16, faiss.METRIC_L2) ivf.by_residual = False; ivf.is_trained = True elif self.codec == "sq8r": # 8-bit scan, exact float32 re-rank of the best 4 # faiss' SIMD 8-bit scan needs d % 8 == 0 (else a scalar loop, ~9x slower at d = 100): # zero-pad centroids and rows. Padded coordinates add exactly 0; only the summation order (and so # float rounding, which can flip a rare near-tie) differs from the scalar loop. dp = -(-self.d // 8) * 8 if dp != self.d: pad = lambda a: np.ascontiguousarray(np.pad(np.asarray(a, dtype="float32"), ((0, 0), (0, dp - self.d)))) C32 = pad(C32); xq = pad(x) q = faiss.IndexFlatL2(dp); q.add(pad(faiss.rev_swig_ptr(self._coarse[1].get_xb(), nl * self.d).reshape(nl, self.d))) sq = faiss.IndexIVFScalarQuantizer(q, dp, nl, faiss.ScalarQuantizer.QT_8bit, faiss.METRIC_L2) sq.by_residual = False; sq.train(C32); sq.add(C32); sq.nprobe = nprobe ivf = faiss.IndexRefineFlat(sq, faiss.swig_ptr(C32)); ivf.k_factor = 4 self._ivf_keep = (sq, C32, q) # keep the arrays alive during the search else: ivf = faiss.IndexIVFFlat(q, self.d, nl); ivf.is_trained = True if self.codec != "sq8r": ivf.add(C32); ivf.nprobe = nprobe frac = self._step / max(1, self.recipe["total_steps"]) eps = self.anneal * max(0.0, 1.0 - frac / self.anneal_until) if self.anneal > 0 else 0.0 D, I = ivf.search(np.ascontiguousarray(xq, dtype="float32"), 2 if eps > 0 else 1) if eps > 0: # annealed assignment: a decaying fraction of rows goes to the runner-up flip = (np.random.RandomState(self._step + 17).random_sample(len(x)) < eps) & (I[:, 1] >= 0) D[flip, 0], I[flip, 0] = D[flip, 1], I[flip, 1] D, I = D[:, :1], I[:, :1] miss = I[:, 0] < 0 if miss.any(): D2, I2 = faiss.knn(x[miss], centroids, 1); D[miss], I[miss] = D2, I2 return D[:, 0].copy(), I[:, 0].copy() def _assign_rows(self, x, centroids): last = self.recipe is not None and self._epoch == len(self.recipe["epoch_rows"]) - 1 \ if getattr(self, "recipe", None) is not None else True ids = None if self._mem is not None and self._cur_index is not None: ids = np.asarray(self._cur_index[self._cur_pos:self._cur_pos + len(x)]) self._cur_pos += len(x) if self.hnsw is not None and self._usage is not None and len(x) and not self.spherical: distance, labels = self._hnsw_assign(x, centroids, last) elif self.graph and ids is not None and self._usage is not None and len(x) and not last \ and not self.spherical: distance, labels = self._graph_assign(x, centroids, ids) elif self.approx and self._usage is not None and len(x) and not last and not self.spherical: distance, labels = self._approx_assign(x, centroids) elif self.approx and self.approx_last and self._usage is not None and len(x) and last \ and not self.spherical: npl = self.approx_last if npl == "auto": # rule: sqrt(k)/4 probes in the last epoch npl = max(8, int(round(math.sqrt(self.k))) // 4) distance, labels = self._approx_assign(x, centroids, nprobe_override=npl) elif self.swap > 0 and self._usage is not None and len(x) and not self.spherical: import faiss D, I = faiss.knn(x, centroids, 2) distance, labels = D[:, 0].copy(), I[:, 0].copy() self._b_del += np.bincount(labels, weights=(D[:, 1] - D[:, 0]).astype("float64"), minlength=self.k) else: distance, labels = super()._assign_rows(x, centroids) if self._axis is not None and self._usage is not None and len(x) and not self._in_fused: e = x - centroids[labels] # residuals (m, d) p = np.einsum("ij,ij->i", e, self._axis[labels]) # projections on u_j # Segment sum by label: sort once, then reduceat (np.add.at on 2-D is slow). order = np.argsort(labels, kind="stable") lab = labels[order] uniq, start = np.unique(lab, return_index=True) self._b_axis[uniq] += np.add.reduceat(e[order] * p[order, None], start, axis=0) if self._half is not None: sg = np.sign(p[order]) self._b_half[uniq] += np.add.reduceat(e[order] * sg[:, None], start, axis=0) self._b_abs += np.bincount(labels, weights=np.abs(p).astype("float64"), minlength=self.k) self._b_proj += np.bincount(labels, weights=p.astype("float64") ** 2, minlength=self.k) if self.score == "total": self._b_dist += np.bincount(labels, weights=distance.astype("float64"), minlength=self.k) if ids is not None and self._mem is not None: self._mem[ids] = labels return distance, labels def _apply_statistics(self, ids, sums, counts, objective, alpha, decay, replace_usage=False): if self.closing_frac < 1.0 and self._pass_sums is not None: rows = self.recipe["epoch_rows"][self._epoch] steps = -(-rows // self.recipe["batch_size"]) if self._epoch_steps == int(round((1.0 - self.closing_frac) * steps)): self._pass_counts.fill(0) # restart closing statistics self._pass_sums.fill(0) if self.momentum > 0 and self._centroids is not None: old = self._centroids.copy() super()._apply_statistics(ids, sums, counts, objective, alpha, decay, replace_usage) if self.momentum > 0 and self._centroids is not None: frac = self._step / max(1, self.recipe["total_steps"]) if self._vel is None: self._vel = np.zeros_like(self._centroids) t = counts > 0 move = self._centroids[t] - old[t] if frac <= self.momentum_until: move += self.momentum * self._vel[t] self._centroids[t] = old[t] + move self._vel[t] = move if self._axis is None: return touched = self._b_proj > 0 self._axis_sum *= decay self._proj_sq *= decay self._axis_sum[touched] += alpha * self._b_axis[touched] self._proj_sq[touched] += alpha * self._b_proj[touched] if self._half is not None: self._half *= decay; self._absp *= decay self._half[touched] += alpha * self._b_half[touched] self._absp[touched] += alpha * self._b_abs[touched] self._b_half.fill(0); self._b_abs.fill(0) if self.score == "total": self._dist *= decay self._dist[touched] += alpha * self._b_dist[touched] self._b_dist.fill(0) if self.swap > 0: self._delcost *= decay self._delcost[touched] += alpha * self._b_del[touched] self._b_del.fill(0) norm = np.linalg.norm(self._axis_sum[touched], axis=1) ok = norm > 0 idx = np.flatnonzero(touched)[ok] self._axis[idx] = self._axis_sum[idx] / norm[ok, None] # one power-iteration step self._b_axis.fill(0) self._b_proj.fill(0) # ---------------------------------------------------------------- revival def _choose_splits(self, rng): if self.gain == "usage": return super()._choose_splits(rng) usage = self._usage.astype("float64") threshold = self._unused_threshold * usage.sum() / self.k # same tau as faiss unused = usage < threshold donors = (~unused) & (usage > 0) nsplit = min(int(unused.sum()), int(donors.sum())) if nsplit == 0 and not self._swap_open(): return None, None if self.score == "half": # N * |E[sign(p) e]|^2: exact gain of the half-mean split base = (self._half.astype("float64") ** 2).sum(1) / np.maximum(usage, 1e-12) * (2 / math.pi) * (math.pi / 2) elif self.score == "abs": # N * (E|p|)^2: gain of the split along u at the half-means base = self._absp ** 2 / np.maximum(usage, 1e-12) else: base = self._proj_sq if self.score == "axis" else self._dist score = np.where(donors, base, -np.inf) # ~ N_j * lambda_j (or trace) if self.gain == "sample": u = np.maximum(rng.random_sample(self.k), np.finfo("float64").tiny) with np.errstate(divide="ignore"): score = np.where(donors, np.log(np.maximum(base, 1e-30)) - np.log(-np.log(u)), -np.inf) order = np.argsort(score)[::-1] source = order[:nsplit] target = np.flatnonzero(unused)[:nsplit] if self._swap_open(): source, target = self._add_swaps(source, target, order, unused, donors) if len(source) == 0: return None, None return source, target def _swap_open(self): if self.swap <= 0 or self._delcost is None: return False frac = self._step / max(1, self.recipe["total_steps"]) return self.swap_window[0] <= frac <= self.swap_window[1] def _add_swaps(self, source, target, order, unused, donors): """Pair the next-best donors with the cheapest live clusters while gain > cost.""" gain = (2.0 / math.pi) * self._proj_sq taken = np.zeros(self.k, bool); taken[source] = True; taken[target] = True live = donors & ~taken cheap = np.flatnonzero(live)[np.argsort(self._delcost[live])] rich = [j for j in order[len(source):] if live[j]] extra_s, extra_t, used = [], [], set() budget = int(self.swap * self.k) ci = 0 for j in rich: if len(extra_s) >= budget or ci >= len(cheap): break if j in used: continue while ci < len(cheap) and (cheap[ci] in used or cheap[ci] == j): ci += 1 if ci >= len(cheap): break t = cheap[ci] if gain[j] <= self._delcost[t]: break extra_s.append(j); extra_t.append(t); used.update((j, t)); ci += 1 if extra_s: self.n_swaps += len(extra_s) source = np.concatenate([source, np.array(extra_s, dtype=source.dtype if len(source) else np.int64)]) target = np.concatenate([target, np.array(extra_t, dtype=target.dtype if len(target) else np.int64)]) return source.astype(np.int64), target.astype(np.int64) def _apply_splits(self, source, target): if self.split == "faiss": n = super()._apply_splits(source, target) self._copy_axis(source, target) return n c = self._centroids[source].astype("float64") usage = self._usage[source].astype("float64") lam = self._proj_sq[source] / np.maximum(usage, 1e-12) # variance along u_j if self.split == "half": # distribution-free: children at c +/- E[sign(p) e] delta = self.offset_scale * self._half[source].astype("float64") / np.maximum(usage, 1e-12)[:, None] elif self.split == "abs": # along u at the empirical half-mean E|p| delta = (self.offset_scale * self._absp[source] / np.maximum(usage, 1e-12))[:, None] * self._axis[source] else: delta = (self.offset_scale * _HALF_GAUSS * np.sqrt(np.maximum(lam, 0.0)))[:, None] * self._axis[source] gain = (2.0 / math.pi) * self._proj_sq[source] self._centroids[source] = (c + delta).astype("float32") self._centroids[target] = (c - delta).astype("float32") if self.split_pass and self._pass_sums is not None: pc = self._pass_counts[source].astype("float64") mean = np.where(pc[:, None] > 0, self._pass_sums[source] / np.maximum(pc, 1)[:, None], c) self._pass_counts[source] = pc / 2; self._pass_counts[target] = pc / 2 self._pass_sums[source] = ((mean + delta) * (pc / 2)[:, None]).astype(self._pass_sums.dtype) self._pass_sums[target] = ((mean - delta) * (pc / 2)[:, None]).astype(self._pass_sums.dtype) if self._delcost is not None: self._delcost[source] = gain / 2 # cool-down: not re-swapped at once self._delcost[target] = gain / 2 if self._vel is not None: self._vel[source] = 0; self._vel[target] = 0 half = (self._usage[source] * self.child_mass).astype("float32") self._usage[source] = half self._usage[target] = half self._copy_axis(source, target) self.n_splits += len(source) self._invalidate_readout() return len(source) def _finish_step(self, expected_n): frac = (self._step + 1) / max(1, self.recipe["total_steps"]) if self.tau_end is not None: cos = 0.5 * (1 + math.cos(math.pi * min(1.0, frac))) self._unused_threshold = float(self.tau_end + (self._tau0 - self.tau_end) * cos) # Every-batch revival needs per-batch counts that carry signal: with fewer than EARLY_MIN_ROWS # expected rows per cluster per batch (k = 65,536 at n = 1M: one) it is off (iteration 24). eu = self.every_until if self.recipe["batch_size"] >= EARLY_MIN_ROWS * self.k else 0.0 if self.revive_every == 5 and self.revive_until >= 1.0 and eu <= 0: return super()._finish_step(expected_n) every = 1 if frac <= eu else self.revive_every if (self._step + 1) % every == 0 and frac <= self.revive_until: self._revive_unused(self._split_rng) self._invalidate_readout() self._step += 1 self._epoch_steps += 1 self._epoch_rows += expected_n self._pending_stats = None self._batch_accumulation = self._batch_objective = None self._batch_centroids = None def finalize(self): """Keep each cluster's principal axis and variance along it (faiss clears its state).""" if self._axis is not None and self._usage is not None: self.final_axis = self._axis.copy() self.final_lam = self._proj_sq / np.maximum(self._usage.astype("float64"), 1e-12) return super().finalize() def _train_rows(self, x, init_centroids=None): if self.batch_sched is None: return super()._train_rows(x, init_centroids) from faiss.contrib.e_means.base import _epoch_seed x = np.ascontiguousarray(x, dtype="float32"); n = len(x) if init_centroids is None: init_centroids = x[np.random.RandomState(self.seed).permutation(n)[: self.k]] self.begin(n, init_centroids) B0, a0 = self.recipe["batch_size"], self.recipe["alpha0"] R = float(sum(self.recipe["epoch_rows"])); b_first, b_last = self.batch_sched plan, done = [], 0 for rows in self.recipe["epoch_rows"]: # batch sizes, linear in rows seen ep, r = [], 0 while r < rows: b = int(round(B0 * (b_first + (b_last - b_first) * (done + r) / R) / 256)) * 256 b = max(256, min(b, rows - r)); ep.append(b); r += b plan.append(ep); done += rows self.recipe["total_steps"] = sum(len(ep) for ep in plan) self.recipe["epoch_steps"] = [len(ep) for ep in plan] for epoch, rows in enumerate(self.recipe["epoch_rows"]): order = np.random.RandomState(_epoch_seed(self.seed, epoch)).permutation(n) pos = 0 for b in plan[epoch]: self.recipe["batch_size"] = b self.recipe["alpha0"] = min(1.0, a0 * (b / B0) ** 0.9) # e-means step law: alpha0 ~ B^0.90 self.update(self._accumulate(x, order[pos:pos + b])); pos += b self.end_epoch() self.finalize() self.assignments = None return self.centroids, None def train(self, x, init_centroids=None): c, a = super().train(x, init_centroids) xs = np.ascontiguousarray(x, dtype="float32") for i in range(self.polish): mode = self.polish_probes if i == 0 or self.polish_second is None else self.polish_second c, a = self._lloyd_step(xs, c, a, mode) if self.polish: self.centroids = c return c, a def _lloyd_step(self, x, c, prev=None, pp="default"): """One Lloyd step from the current centroids. polish_probes: None = exact, int = IVF probes, "graph:m" = each row compared only with the m centroids nearest its previous centroid.""" import faiss if pp == "default": pp = self.polish_probes if isinstance(pp, str) and pp.startswith("graph"): m = int(pp.split(":")[1]) from aries._kernels import cand_assign _, G = faiss.knn(c, c, m) _, lab = cand_assign(x, c, G, prev) I = lab[:, None] elif pp is None: _, I = faiss.knn(x, c, 1) else: nl = max(8, int(round(math.sqrt(self.k)))) km = faiss.Kmeans(self.d, nl, niter=20, seed=self.seed + 99, max_points_per_centroid=10**9) km.train(c) q = faiss.IndexFlatL2(self.d); q.add(km.centroids) ivf = faiss.IndexIVFFlat(q, self.d, nl); ivf.is_trained = True ivf.add(c); ivf.nprobe = max(4, nl // 8) if pp == "auto" else int(pp) _, I = ivf.search(x, 1) miss = I[:, 0] < 0 if miss.any(): I[miss] = faiss.knn(x[miss], c, 1)[1] lab = I[:, 0] ok = lab >= 0 cnt = np.bincount(lab[ok], minlength=self.k).astype("float64") from scipy.sparse import csr_matrix M = csr_matrix((np.ones(ok.sum(), "float32"), (lab[ok], np.flatnonzero(ok))), shape=(self.k, len(x))) S = np.asarray(M @ x, dtype="float64") out = c.copy() nz = cnt > 0 out[nz] = (S[nz] / cnt[nz, None]).astype("float32") return out, lab def _remap_memory(self, source, target): """Rows remembering a re-used index now belong to the donor's region.""" if self._mem is None or len(target) == 0: return remap = np.arange(self.k + 1); remap[np.asarray(target)] = np.asarray(source) remap[self.k] = -1 self._mem = remap[np.where(self._mem < 0, self.k, self._mem)] def _copy_axis(self, source, target): self._remap_memory(source, target) self._axis_sum[source] *= 0.5 self._proj_sq[source] *= 0.5 self._axis[target] = self._axis[source] self._axis_sum[target] = self._axis_sum[source] self._proj_sq[target] = self._proj_sq[source] if self._half is not None: self._half[source] *= 0.5; self._absp[source] *= 0.5 self._half[target] = self._half[source]; self._absp[target] = self._absp[source] if self._dist is not None: self._dist[source] *= 0.5 self._dist[target] = self._dist[source] # Frozen configuration after iterations 1-5 (docs/EXPERIMENTS.md): principal-axis gain-ranked # revival, consistent closing statistics, revival threshold 0.2, EMA step law x 1.4. APPROX_MIN_K = 4096 # the 'auto' sparse-assignment rule applies from this k on EARLY_MIN_ROWS = 2 # early every-batch revival needs >= this many expected rows per cluster per batch PE_V2 = dict(split="principal", gain="greedy", split_pass=True, tau=0.2, alpha_scale=1.4) # Frozen after iterations 6-11 (full-scale validation, 5 seeds): v2 + revival every batch during the # first 30% of steps + approximate assignment (sqrt(k) k-means coarse cells, sqrt(k)/8 probes) in # every epoch but the last. Better than v2 and ~35-40% faster than official e-means per epoch. PE_V3 = dict(PE_V2, every_until=0.3, approx="auto") # PISCES (ARIES series #1), frozen after iterations 12-14: v3 + approximate last epoch with # sqrt(k)/4 probes. The approximation helps only together with principal-axis revival: official # e-means with the same approximate assignment is *worse* than official e-means (iteration 12). PISCES_V10 = dict(PE_V3, approx_last="auto") # PISCES (final, iterations 21-22): the same algorithm as PISCES_V10 with two engineering changes that # leave the assignment (practically) unchanged: one fused Numba pass for the per-batch statistics, and # 8-bit IVF scans whose best 4 candidates are re-ranked with exact float32 distances. PISCES = dict(PISCES_V10, fused=True, codec="sq8r") # Candidate after iterations 15-19: PISCES + one closing Lloyd step (sqrt(k)/8 IVF probes) that # re-assigns every row to the closing means and recomputes them. PISCES_POLISH = dict(PISCES_V10, polish=1, polish_probes="auto") # PISCES with the fused statistics kernel (engineering only; same algorithm) PISCES_FUSED = dict(PISCES_V10, fused=True) PISCES_FAST = PISCES