Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@
## 2026-05-01 - Avoid High-Level Tensor Ops in Scalar Reductions
**Learning:** High-level `Tensor` operations like `sub()` and `mul()` trigger intermediate heap allocations for shape and stride metadata. When computing scalar reductions (like MSE, distances, or loss functions), using these operations introduces severe memory overhead inside hot loops. Attempting to use `.min()` length truncation as a safeguard is an anti-pattern as it masks shape mismatch errors.
**Action:** For scalar reductions, assert shape equality (`assert_eq!(a.shape, b.shape)`) and perform a single-pass iteration directly over the underlying borrowed data arrays (`a.data.borrow()`) to eliminate intermediate allocations and safely compute the result.

## 2026-06-25 - Avoid Exact Distance Calculations When Unexposed
**Learning:** Computing exact Euclidean distances using `libm::sqrt` inside tight spatial scanning loops (like in `auto_k_selection` and `DBSCAN::region_query`) introduces significant overhead. Since these algorithms only use the distances internally for threshold comparisons (`< epsilon`) and do not expose them in the final result, computing the square root is mathematically redundant and computationally expensive.
**Action:** Replace exact distance thresholds with squared distance thresholds (`eps_sq = epsilon * epsilon`). Compute the squared distance inline, explicitly exit early for negative or `NaN` thresholds (e.g., `if !(epsilon > 0.0)`), and use early loop exits with safe conditions like `if !(sum < eps_sq)` to gracefully handle `NaN` coordinate values without invoking costly math functions.
36 changes: 30 additions & 6 deletions crates/aether-core/src/ml/clustering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
// ═══════════════════════════════════════════════════════════════════════════════
//


#![allow(dead_code)]

use libm::{fabs, sqrt};
Expand Down Expand Up @@ -274,18 +273,22 @@ impl<const D: usize> KMeans<D> {

/// Automatically determine optimal K using topological analysis
pub fn auto_k_selection<const D: usize>(data: &[[f64; D]], n: usize, epsilon: f64) -> usize {
if !(epsilon >= 0.0) {
return n.clamp(1, MAX_POINTS);
}

// Build epsilon-neighborhood graph and count connected components (β₀)
let mut components = n.min(MAX_POINTS);
let mut components = 0;
let mut visited = [false; MAX_POINTS];
let n = n.min(MAX_POINTS);
let eps_sq = epsilon * epsilon;

for start in 0..n {
if visited[start] {
continue;
}

// BFS from this point
components -= 1;
let mut stack = [0usize; 64];
let mut top = 1;
stack[0] = start;
Expand All @@ -302,8 +305,15 @@ pub fn auto_k_selection<const D: usize>(data: &[[f64; D]], n: usize, epsilon: f6
// Add neighbors
for i in 0..n {
if !visited[i] && i != current {
let dist = distance(&data[current], &data[i]);
if dist < epsilon && top < 64 {
let mut sum = 0.0;
for d in 0..D {
let diff = data[current][d] - data[i][d];
sum += diff * diff;
if !(sum < eps_sq) {
break;
}
}
if sum < eps_sq && top < 64 {
stack[top] = i;
top += 1;
}
Expand Down Expand Up @@ -450,8 +460,22 @@ impl<const D: usize> DBSCAN<D> {
) -> heapless::Vec<usize, MAX_POINTS> {
let mut neighbors = heapless::Vec::new();

if !(self.epsilon >= 0.0) {
return neighbors;
}

let eps_sq = self.epsilon * self.epsilon;

for j in 0..n {
if distance(&data[i], &data[j]) <= self.epsilon {
let mut sum = 0.0;
for d in 0..D {
let diff = data[i][d] - data[j][d];
sum += diff * diff;
if !(sum <= eps_sq) {
break;
}
}
if sum <= eps_sq {
let _ = neighbors.push(j);
}
}
Expand Down