perf(agent): cheaper novelty scoring; complete the consolidation benchmark
consolidation_efficiency never finished: stopped after 19 minutes on one core while building its 100K case. Not the consolidation cycle (linear: 17 us at 100 records, 2.16 ms at 10K) but the setup — every add_memory scores the new record's novelty against the whole working tier, the benchmark lets that tier reach 50K, and each comparison recomputed both norms: ~5e9 comparisons of three passes each. ImportanceScorer::score_surprise now computes the new record's norm once, takes each comparison in one fused, 8-lane pass (dot product and the other norm together), and splits a working tier of 4096+ records across threads with the `parallel` feature. Same results: tested against the old cosine formula, including shorter, empty and zero vectors and the parallel path. The work stays quadratic in the working-tier size by design; with regular consolidation the tier stays near working_capacity (100) and inserts are cheap. The complete run takes 8 min 10 s on tank and fills in the 100K cycle row (46.66 ms) and the memory-reduction table, which had never been published. The binary no longer prints a record-count ratio as a "BM25 Speedup" (never measured; Part 1 measures search latency) or claims sub-linear cycle scaling (its own numbers grow slightly faster than linearly). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
@@ -144,9 +144,44 @@ pub struct ConsolidationStats {
|
||||
|
||||
pub struct ImportanceScorer;
|
||||
|
||||
/// Sum of squares, in 8-wide lanes so it vectorises.
|
||||
fn sum_of_squares(a: &[f32]) -> f32 {
|
||||
let (blocks, tail) = a.as_chunks::<8>();
|
||||
let mut acc = [0.0f32; 8];
|
||||
for b in blocks {
|
||||
for i in 0..8 {
|
||||
acc[i] += b[i] * b[i];
|
||||
}
|
||||
}
|
||||
acc.iter().sum::<f32>() + tail.iter().map(|x| x * x).sum::<f32>()
|
||||
}
|
||||
|
||||
/// `(a · b, |b|²)` in one pass over equal-length slices, in 8-wide lanes.
|
||||
fn dot_and_norm2(a: &[f32], b: &[f32]) -> (f32, f32) {
|
||||
let (a_blocks, a_tail) = a.as_chunks::<8>();
|
||||
let (b_blocks, b_tail) = b.as_chunks::<8>();
|
||||
let mut dot = [0.0f32; 8];
|
||||
let mut nb = [0.0f32; 8];
|
||||
for (x, y) in a_blocks.iter().zip(b_blocks) {
|
||||
for i in 0..8 {
|
||||
dot[i] += x[i] * y[i];
|
||||
nb[i] += y[i] * y[i];
|
||||
}
|
||||
}
|
||||
let mut d = dot.iter().sum::<f32>();
|
||||
let mut n = nb.iter().sum::<f32>();
|
||||
for (x, y) in a_tail.iter().zip(b_tail) {
|
||||
d += x * y;
|
||||
n += y * y;
|
||||
}
|
||||
(d, n)
|
||||
}
|
||||
|
||||
impl ImportanceScorer {
|
||||
/// Cosine similarity between two embedding slices.
|
||||
/// Returns 0.0 if either norm is zero.
|
||||
/// Returns 0.0 if either norm is zero. The reference that
|
||||
/// [`Self::score_surprise`] is tested against.
|
||||
#[cfg(test)]
|
||||
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
|
||||
let len = a.len().min(b.len());
|
||||
if len == 0 {
|
||||
@@ -167,13 +202,54 @@ impl ImportanceScorer {
|
||||
|
||||
/// Novelty score: 1.0 − max cosine similarity against all existing records.
|
||||
/// Returns 1.0 when there are no existing memories.
|
||||
///
|
||||
/// Same result as [`Self::cosine_similarity`] against each record, but the
|
||||
/// new embedding's norm is computed once rather than per record, each
|
||||
/// record costs one fused pass (dot product and its norm together) rather
|
||||
/// than three, and a large working set is scored in parallel. Every insert
|
||||
/// scores against the whole working tier, so this is what an unbounded
|
||||
/// working tier pays for: at 100K records it was the difference between a
|
||||
/// benchmark finishing and not (`BENCHMARKS.md`, "Consolidation Efficiency").
|
||||
pub fn score_surprise(embedding: &[f32], existing_memories: &[&MemoryRecord]) -> f32 {
|
||||
if existing_memories.is_empty() {
|
||||
return 1.0;
|
||||
}
|
||||
let query_norm2 = sum_of_squares(embedding);
|
||||
let similarity = |r: &&MemoryRecord| -> f32 {
|
||||
let other = &r.embedding;
|
||||
let len = embedding.len().min(other.len());
|
||||
if len == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
let (dot, other_norm2) = dot_and_norm2(&embedding[..len], &other[..len]);
|
||||
// A shorter record compares against the query's matching prefix.
|
||||
let q2 = if len == embedding.len() {
|
||||
query_norm2
|
||||
} else {
|
||||
sum_of_squares(&embedding[..len])
|
||||
};
|
||||
if q2 == 0.0 || other_norm2 == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
dot / (q2.sqrt() * other_norm2.sqrt())
|
||||
};
|
||||
#[cfg(feature = "parallel")]
|
||||
let max_sim = if existing_memories.len() >= 4096 {
|
||||
use rayon::prelude::*;
|
||||
existing_memories
|
||||
.par_iter()
|
||||
.map(similarity)
|
||||
.reduce(|| f32::NEG_INFINITY, f32::max)
|
||||
} else {
|
||||
existing_memories
|
||||
.iter()
|
||||
.map(similarity)
|
||||
.fold(f32::NEG_INFINITY, f32::max)
|
||||
};
|
||||
#[cfg(not(feature = "parallel"))]
|
||||
let max_sim = existing_memories
|
||||
.iter()
|
||||
.map(|r| Self::cosine_similarity(embedding, &r.embedding))
|
||||
.map(similarity)
|
||||
.fold(f32::NEG_INFINITY, f32::max);
|
||||
(1.0 - max_sim).clamp(0.0, 1.0)
|
||||
}
|
||||
@@ -471,6 +547,54 @@ impl ConsolidationEngine {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn score_surprise_matches_the_reference_cosine() {
|
||||
let mut x = 0x2545_F491_4F6C_DD1Du64;
|
||||
let mut next = || {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
(x >> 40) as f32 / (1u64 << 24) as f32 - 0.5
|
||||
};
|
||||
let make = |id: u64, v: Vec<f32>| MemoryRecord {
|
||||
id,
|
||||
chunk: String::new(),
|
||||
embedding: v,
|
||||
tier: MemoryTier::Working,
|
||||
importance: 0.0,
|
||||
access_count: 0,
|
||||
last_accessed: 0.0,
|
||||
created_at: 0.0,
|
||||
source: MemorySource::User,
|
||||
};
|
||||
// Ordinary rows, a shorter one, an empty one and a zero vector; and
|
||||
// enough rows to take the parallel path too.
|
||||
for n in [5usize, 5000] {
|
||||
let mut recs: Vec<MemoryRecord> = (0..n as u64)
|
||||
.map(|i| make(i, (0..37).map(|_| next()).collect()))
|
||||
.collect();
|
||||
recs.push(make(9_000, (0..20).map(|_| next()).collect()));
|
||||
recs.push(make(9_001, Vec::new()));
|
||||
recs.push(make(9_002, vec![0.0; 37]));
|
||||
let refs: Vec<&MemoryRecord> = recs.iter().collect();
|
||||
for _ in 0..5 {
|
||||
let q: Vec<f32> = (0..37).map(|_| next()).collect();
|
||||
let expected = (1.0
|
||||
- refs
|
||||
.iter()
|
||||
.map(|r| ImportanceScorer::cosine_similarity(&q, &r.embedding))
|
||||
.fold(f32::NEG_INFINITY, f32::max))
|
||||
.clamp(0.0, 1.0);
|
||||
let got = ImportanceScorer::score_surprise(&q, &refs);
|
||||
assert!((got - expected).abs() < 1e-5, "n={n}: {got} vs {expected}");
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
ImportanceScorer::score_surprise(&[0.0; 4], &[&make(1, vec![1.0; 4])]),
|
||||
1.0
|
||||
);
|
||||
}
|
||||
|
||||
// Helper: build a simple normalised embedding of given dimension.
|
||||
fn unit_vec(dim: usize, hot: usize) -> Vec<f32> {
|
||||
let mut v = vec![0.0f32; dim];
|
||||
|
||||
Reference in New Issue
Block a user