AutoR&D-Engineer

What if AI could find hidden performance wins in complex software—and prove that every methodological change is both faster and correct?

That’s the challenge we’re tackling in our auto Engineer.

Performance optimization is hugely valuable, but this is not just about finding bugs or making small code-level fixes. The real opportunity is to uncover methodological and algorithmic improvements—new ways to structure computation, reduce unnecessary work, or improve how a system uses memory and hardware—then validate that those changes preserve correctness.

Our Auto Engineer does exactly that. Given an engineering goal, it works like a careful research engineer: it identifies bottlenecks, forms hypotheses, proposes new methods, implements them, runs controlled experiments, and keeps only improvements that are supported by evidence. The resulting artifacts are more than patches: they are working implementations of verified improvements, packaged with the benchmark results and analysis that explain why they are better.

Input Repository + research goalSystem, target & constraints
AutoR&D-Engineer
Output Verified implementationPatch + benchmark evidence

This page shares the first four codebases it improved—three open-source projects and one from Salesforce’s own AI infrastructure.

Inside the Auto Engineer's working loop

Watch our Auto Engineer turn a performance goal into a hypothesis, a controlled experiment, and a verified improvement across three heavily used and optimized open-source libraries—pandas, hnswlib, and USearch.

An AutoR&D-Engineer discoverypandas · nullable buffer views

Find the allocation hiding in the hot path.

AutoR&D-Engineer traces row-wise reductions and identifies a throwaway row-label array allocated for every element in the frame.

What this step producesBottleneck + correctness contract

What It Found

Here we present the findings across those open-source libraries plus our own RL training infrastructure (SFR-RL).

1
Open Source · Dataframes

pandas: three speedups in the workhorse of data science

We ran our Auto Engineer on pandas to make common operations faster while preserving correctness. It found, implemented, and verified three optimizations, which you can explore below.

pandas supports many data types, missing-value conventions, and memory layouts. That flexibility can add conversion, masking, and copying work even when the data is already ready to use. The three optimizations share an approach: check the data first, then skip unnecessary work when it is safe. Each uses a fast path for inputs that meet specific conditions; other inputs follow pandas’ existing implementation.

Up to 1.84× on nullable dtypes 4–28% faster primary workloads Up to +64.6% best case 136K checks, 0 mismatches

Optimization 1Row-wise math on nullable dtypes

pandas' nullable integer, float, and boolean columns, including their Arrow-backed variants, take their own route for row-wise sum, prod, min, and max: the frame is flattened and run through the groupby kernels, which meant first building a "row label" for every single element, a throwaway array as large as the frame itself, just to tell the kernel which row each value belongs to. AutoR&D's patch views the existing data and mask buffers in the layout the kernel already expects and reduces with a single group, so that label array is never allocated and the kernels and reduction order stay exactly as they were. Across pandas' own 40-cell benchmark that's 1.22–1.84× faster (median 1.38×) with every confidence interval above parity, and 12–15% lower peak memory on a 10-million-element frame.

Speedup over unpatched pandas 40 benchmark cells: 4 ops × 5 nullable dtypes × 2 frame shapes 1.0× 1.2× 1.4× 1.6× 1.8× 2.0× parity Range across all 40 cells: 1.22× to 1.84× faster; every bootstrap confidence interval is above 1 1.22× 1.84× Median speedup across the 40 cells: 1.377× median 1.38× ✓ all 40 confidence intervals above parity Both tall (100K × 4) and wide (1K × 400) frames benefit
Figure 2. Speedup of row-wise reductions on nullable-dtype frames over unpatched pandas, across 40 benchmark cells (sum/prod/min/max × Int64, Float64, boolean, int64[pyarrow], float64[pyarrow] × tall and wide 400K-element frames). Paired, CPU-pinned runs; every bootstrap interval is above 1.
0 100 200 300 400 500 MB Baseline Patched sum · Int64, baseline peak: 449 MB sum · Int64, patched peak: 396 MB (−12%) −12% sum Int64 sum · float64[pyarrow], baseline peak: 472 MB sum · float64[pyarrow], patched peak: 401 MB (−15%) −15% sum float64[pyarrow] max · Int64, baseline peak: 448 MB max · Int64, patched peak: 396 MB (−12%) −12% max Int64 max · float64[pyarrow], baseline peak: 456 MB max · float64[pyarrow], patched peak: 401 MB (−12%) −12% max float64[pyarrow]
Figure 3. Peak memory on a 2,000,000 × 5 nullable frame (10M elements). The eliminated per-element label array shows up directly as 12–15% less peak RSS.
Technical details: formulation & implementation
Formulation

Take a frame X with n rows and c columns that share one nullable dtype. To evaluate X.sum(axis=1), pandas concatenates the columns into a single one-dimensional extension array A of length n·c, laid out column-major, and hands the groupby aggregation kernel a label vector L so that group r collects row r:

A[c·n + r] = X[r, c],    L = tile(arange(n), c),    |L| = n·c

That label vector is an n·c array of 8-byte integers (on 64-bit builds) whose only job is to tell the kernel which row each element belongs to. The new route views the same data and mask buffers as a (c, n) matrix, transposes to (n, c), and calls the kernel with one group and c ids. Each of the kernel's n "columns" is then one frame row, aggregated over its c observations. Every output cell consumes the same values in the same column order as the labelled formulation, so results are bit-identical; the only thing that disappears is the label array.

Implementation
  • BaseMaskedArray._groupby_op_axis1(how, nrows, ncols, min_count, skipna) reshapes _data and _mask as views and calls WrappedCythonOp._cython_op_ndim_compat with ngroups=1; it raises NotImplementedError for anything it does not handle so the caller falls back.
  • ArrowExtensionArray._groupby_op_axis1 covers the eleven Arrow int, uint, float and bool types by delegating through _to_masked() and converting the result back. String, decimal and timestamp Arrow types fall through.
  • DataFrame._reduce tries the route first for sum, prod, min and max, and otherwise continues to the existing np.tile label path. Two ASV benchmark classes (FrameOpsAxis1EA, FrameOpsAxis1EAPeakmem) cover it.
# pandas/core/arrays/masked.py (condensed: the real guard also checks ndim and positive shape)
def _groupby_op_axis1(self, *, how, nrows, ncols, min_count, skipna, **kwargs):
    if how not in ("sum", "prod", "min", "max") or self.size != nrows * ncols:
        raise NotImplementedError                      # caller falls back to _groupby_op
    kind = WrappedCythonOp.get_kind_from_how(how)
    op = WrappedCythonOp(how=how, kind=kind, has_dropped_na=False)
    values = self._data.reshape(ncols, nrows).T        # views of the existing buffers
    mask = self._mask.reshape(ncols, nrows).T
    ids = np.zeros(ncols, dtype=np.intp)               # one group: c ids, no n*c label array
    result_mask = np.zeros((nrows, 1), dtype=bool)
    result = op._cython_op_ndim_compat(values, min_count=min_count, ngroups=1, comp_ids=ids,
                                       mask=mask, result_mask=result_mask, skipna=skipna, **kwargs)
    return self._maybe_mask_result(result.squeeze(axis=1), result_mask.squeeze(axis=1))
Evidence
  • 134,064 differential cases (141,120 calls) across every supported dtype, both skipna settings, min_count 0 through 4, degenerate shapes, infinities and NA patterns: zero result, mask, dtype, index-dtype or exception differences. 1,584 of 1,584 routing checks used the new kernel, and a test that monkeypatches _groupby_op to raise proves the old path is never reached.
  • ASV: 29 of 40 timing cells flagged improved (ratios 0.51 to 0.82) and 10 more with faster point estimates. A paired CPU-pinned study gives 1.215× to 1.837× (median 1.377×) with every bootstrap interval above 1.
  • Peak memory on a 2,000,000 × 5 frame: 449 → 396 MB (sum, Int64) and 472 → 401 MB (sum, float64[pyarrow]). 437 new tests and 44,458 existing tests pass.

Optimization 2Counting and de-duplicating strings

For nullable string columns, duplicated() and value_counts() now hand their backing array straight to pandas' own hashing kernel: 4.4–12.2% faster on million-value workloads, with peak memory for value_counts down by about a third. Total change: a 28-line diff.

0% 5% 10% 15% value_counts: 4.4% faster on one million strings, exact same output +4.4% value_counts duplicated (first): 9.6% faster on one million strings, exact same output +9.6% duplicated (first) duplicated (last): 12.2% faster on one million strings, exact same output +12.2% duplicated (last) duplicated (False): 8.7% faster on one million strings, exact same output +8.7% duplicated (False)
Figure 4. Median speedup of pandas string operations on one million values (500K distinct, 10% missing). Outputs verified identical.
Technical details: formulation & implementation
Formulation

Write the baseline operator as F0 and the candidate as F1. A route is a guard g, a specialized kernel K and a reconstruction Q, with P a zero-copy (or bounded-copy) projection of the physical representation:

F1(x) = Q(K(P(x)))  if  g(x) = 1,    F1(x) = F0(x)  otherwise

The obligation is stronger than equal values. With Π the public projection (values or exception type, value dtype, shape, index dtype, index values and names), the route must satisfy Π(F1(x)) = Π(F0(x)) for every input, so the guard has to cover aliasing and mutability as well as dtype.

Here the representation is a StringArray whose backing store is an object ndarray with pd.NA as the sentinel. The inherited duplicated first materializes an NA mask, and the generic value_counts exports through to_numpy, hashes, then converts the result index back to the extension dtype. All of that is adapter work around a kernel that already accepts the backing array as it is.

Implementation

One file, pandas/core/arrays/string_.py: 28 lines inserted, 2 deleted. The guard for duplicated is that the sentinel is exactly pd.NA; value_counts additionally requires dropna=True. No new hash table, encoding or NA rule is introduced, so the review surface is just the guard and the reconstruction.

# pandas/core/arrays/string_.py
def duplicated(self, keep="first"):
    if self.dtype.na_value is libmissing.NA:
        return duplicated(self._ndarray, keep=keep)   # algorithms-layer kernel, no NA-mask pass
    return super().duplicated(keep=keep)

def value_counts(self, dropna=True):
    if self.dtype.na_value is libmissing.NA and dropna:
        result = value_counts_internal(self._ndarray, sort=False, dropna=True)
        index_arr = self._from_backing_data(np.asarray(result.index._data))
        index = Index(index_arr, name=result.index.name, copy=False)
        result = Series(result._values, index=index, name=result.name, copy=False)
    else:
        result = super().value_counts(dropna=dropna)
Evidence
  • A 130-case differential matrix over object, Python-string and Arrow-string representations; ASCII, empty, embedded-NUL, composed and decomposed Unicode, CJK and emoji payloads; every NA variant; all keep modes and value_counts options. Baseline and candidate serializations share the same SHA-256.
  • 30 paired timings per case in alternating order on a pinned core: all four activated routes have simultaneous 95% upper ratio bounds below parity (0.899 to 0.970). A deliberate Unicode fallback control behaves exactly as the unchanged path should, confirming the route counter.
  • Fresh-process memory: value_counts peak RSS increase 37.13 → 24.45 MB and traced peak 31.65 → 24.66 MB; duplicate detection is non-increasing on both metrics.

Optimization 3Row-wise math on numeric frames

sum, prod, min, and max across rows used to allocate fresh intermediate arrays for every internal block; the patch folds blocks into one reused accumulator. That's 12–28% faster on a typical 100,000-row mixed frame, and up to 64.6% on the fragmented frames real pipelines accumulate.

0% 20% 40% 60% sum, typical mixed frame (100,000 rows): 15.7% faster sum, fragmented frame (32 blocks): 30.1% faster +30.1% sum prod, typical mixed frame (100,000 rows): 28.0% faster prod, fragmented frame (32 blocks): 38.2% faster +38.2% prod min, typical mixed frame (100,000 rows): 12.7% faster min, fragmented frame (32 blocks): 64.4% faster +64.4% min max, typical mixed frame (100,000 rows): 12.3% faster max, fragmented frame (32 blocks): 64.6% faster +64.6% max
Figure 5. Median speedup of row-wise reductions. Fragmented frames, common in real pipelines, benefit most, because that's where the eliminated allocations multiply.
Technical details: formulation & implementation
Formulation

For sum, prod, min and max with axis=1, the baseline avoids a transpose. Each physical block is reduced to a length-n vector middle, the first is copied into result, and every later block produces a fresh ufunc(result, middle). With B blocks that is B block temporaries, one copy and B − 1 combine temporaries; nullable float sum and prod add mask and filled-copy allocations inside nanops. The candidate reduces the first eligible block straight into an owned accumulator and folds each later block through one reused scratch array, combining in place: one accumulator and at most one scratch, whatever B is.

Bitwise fidelity is the constraint. Float sum and prod are identity-seeded in the baseline, and that seed is observable:

(+0.0) + (−0.0) = +0.0,   whereas copying the first row would preserve −0.0

The fold therefore seeds with 0 or 1, visits rows in order, and substitutes the identity for NaN only on rows that contain one. Integer operations and min/max use ufunc.reduce(..., out=).

Implementation

pandas/core/frame.py, 151 lines added, most of them guards. A block is eligible when it is a C-contiguous, native-byte-order, two-dimensional ndarray of int64, uint64, float32 or float64 whose ufunc.resolve_dtypes resolves without a cast; the accumulator must be owned, writable, shape-compatible and non-aliasing. Unlike dtypes are accepted only when one side dominates promotion (the accumulator is promoted once); promotions that change both operands, such as int64 + uint64 → float64, stay on the generic path. min and max use the route from 4,096 rows; sum and prod at any length.

# pandas/core/frame.py, inside the block loop of DataFrame._reduce_axis1
if result is None and _can_fuse_axis1_block(vals, ufunc):
    result = np.empty(vals.shape[1], dtype=vals.dtype)
    _fold_axis1_block(vals, result, name, skipna, ufunc)  # reduce straight into the accumulator
    continue
elif _can_fuse_axis1_into(vals, result, ufunc):
    if np.promote_types(result.dtype, vals.dtype) == vals.dtype:
        result = result.astype(vals.dtype)                # promote the accumulator once
    if vals.shape[0] == 1 and singleton_is_bitwise_safe:
        ufunc(result, vals[0], out=result)
    else:
        scratch = ensure_scratch(dtype=vals.dtype)        # one scratch array, reused
        _fold_axis1_block(vals, scratch, name, skipna, ufunc)
        ufunc(result, scratch, out=result)                # combine in place
    continue
Evidence
  • A 900-case broad matrix (four dtypes, four operations, both skipna settings, min_count boundaries, several shapes) plus an 880-case edge matrix (both orders of 12 promotion pairs at 17, 4,095 and 4,096 rows; signed-zero, NaN and infinity patterns; near-limit integers), compared by value-byte hash, dtype, index dtype, shape and name: zero mismatches.
  • Primary 100,000-row mixed frame over 11 paired samples: sum 556.5 → 469.3 µs, prod 675.3 → 486.5 µs, min 437.8 → 382.2 µs, max 439.0 → 384.8 µs.
  • A 32-cell topology sweep (8 frame layouts × 4 operations, 9 pairs each, bootstrap 95% intervals) shows where routing overhead dominates: homogeneous float frames sit near parity, homogeneous integer frames lose up to 9%, 1,024-row mixed frames lose 4–16%, and the 4,096-row min/max gate admits one narrow case that costs about 31%. Those cells are reported as the data for a production dispatch policy over rows, blocks, columns per block, dtype and NA density.

The verification is what makes this upstream-ready: 1,910 differential test cases for the first two patches and 134,064 more for the nullable-dtype patch, each comparing patched and unpatched pandas on identical inputs, from Unicode and emoji to integer overflow, infinities, min_count edge cases, and the sign bit of zero. Every output matched exactly, and anything unusual simply takes the original code path.

2
Open Source · Vector Search

hnswlib: a clean +4% in the engine behind AI retrieval

+4.1% median query throughput Bit-for-bit identical results

hnswlib powers vector search inside databases, RAG pipelines, and recommendation systems, and has been tuned by experts for years, which is exactly why we chose it. AutoR&D found a remaining win in the batch query path: every query was taking a lock to borrow scratch memory from a shared pool. Its patch has each worker thread lease that scratch once and reuse it across the batch: roughly 4,000 lock operations collapsed to 32 in the diagnostic workload, while leaving the search logic untouched.

The result: +4.1% median queries-per-second across three independently built indexes, faster in every paired run, with labels, distances, and recall verified identical to the byte.

Scratch-pool lock round-trips per batch 2,000-query diagnostic batch, 16 worker threads Standard hnswlib Standard hnswlib: about 4,000 pool lock/unlock operations for a 2,000-query batch, two per query row 4,000 With worker-scoped leases (ours) With worker-scoped leases: 32 pool lock/unlock operations, two per worker, reused across the whole batch 32 −99.2% +4.1% median queries-per-second gain +3.96% · +4.12% · +4.34% across three index builds ✓ search results bit-for-bit identical
Figure 10. Why it’s faster, and by how much. Left: the patch removes per-query synchronization: scratch-buffer lock round-trips per batch collapse from 4,000 to 32. Right: the resulting throughput gain, consistent across three independently built indexes, with search results unchanged.
Technical details: formulation & implementation
Formulation

HNSW traversal needs a scratch "visited" set. hnswlib stores it as a dense generation-tag array, so a node v counts as visited in the current search exactly when

mass[v] = curV

Advancing curV clears the set in constant time; only a generation wrap performs a physical clear. The Python batch path calls searchKnn once per row, and each call locks VisitedListPool to acquire and reset a list and locks it again to return it. For Q rows that is about 2Q mutex operations, even though a ParallelFor worker executes many rows back to back. Moving ownership from the row to the worker makes it 2W for W active workers:

Nlock = 2Q = 4,000  →  2W = 32   (Q = 2,000, W = 16, −99.2%)

Every row still gets exactly one generation advance; only pool ownership is amortized.

Implementation
  • A non-copyable RAII VisitedListLease: acquisition prepares the first generation, next() prepares each later row, and the destructor returns the list even when a filter callback or a query throws.
  • A private search helper, searchKnnWithVisitedList, accepts caller-owned scratch. The public searchKnn wrapper is unchanged, so direct C++ callers and single-row queries behave exactly as before.
  • The batch knn_query keeps one lazily created lease per worker slot. Distance arithmetic, graph layout and serialization are untouched, which is why labels and distances are byte-identical.
// python_bindings: batch knn_query, inside the ParallelFor body
auto& lease = visited_list_leases[threadId];
VisitedList* vl;
if (!lease) {
    lease = index->visited_list_pool_->getFreeVisitedListLease();  // lock once per worker
    vl = lease->get();                                             // first row reset on acquire
} else {
    vl = lease->next();                                            // one generation advance per later row
}
auto result = index->searchKnnWithVisitedList(query, k, vl, filter);
// RAII: the lease returns vl to the pool exactly once, when this worker's batch scope ends
Evidence
  • Invariants checked explicitly: a fresh visited set per row (wrap and clearing test), a single owner per slot (concurrent-batch test), return on exception (injected exception, then reuse), search equivalence (labels and distances matched), and coverage of L2, inner product, cosine, filters and deletions. 17 Python-binding regression tests pass.
  • Exploratory A/B on three independently built indexes with the order alternated B/C, C/B, B/C and all 31 timed repetitions retained: +4.34%, +4.12% and +3.96% QPS; recall@10 identical to four decimals; peak RSS within ±0.11%; output hashes identical.
  • Consistent across all three seeds and recommended as the first upstream PR candidate: small, architecture-neutral, and easy to review.
Worker-scoped leases · PR #676 ↗ Upstream pull request for the hnswlib optimization.
3
Open Source · Vector Search

USearch: skipping the math that vector search repeats millions of times

+17.5% search throughput (GCC 11) +7.4% (GCC 13) +4 bytes per vector Same neighbors · recall preserved

USearch is a compact, high-performance vector-search engine that ships as a single header and is embedded in databases and AI applications. Its cosine-similarity kernel, the default for comparing text and image embeddings, needs the length of both vectors for every comparison. AutoR&D spotted a redundancy: the length of a stored vector never changes, yet the built-in kernel recomputed it on every one of the hundreds of comparisons a single query performs, millions of times across a workload.

The patch caches each stored vector's length once, in a 4-byte lock-free "sidecar" that follows the vector through inserts, removals, compaction, copies, and reloads. The query's length is computed once per search, so each comparison shrinks to a dot product and one division: three multiply-adds per element become one, and two square roots become none. The route is deliberately narrow: custom metrics, memory-mapped indexes, non-finite values, and builds that use an external SIMD library all keep the original path, and the on-disk index format is unchanged.

On a one-million-vector Wikipedia-embedding index, single-core search throughput rose 17.5% with GCC 11 and 7.4% with GCC 13, positive in every paired round, while the graph traversal stayed identical: the same 926.5 distance evaluations and 75.8 visited nodes per query. The sidecar adds just 4 bytes per vector (+0.3% memory). Across 10,240 top-10 results, distances agreed to within 4×10−7 and recall was preserved; the change passed the C and C++ suites under Address- and UndefinedBehaviorSanitizer, with ThreadSanitizer confirming the new code is race-free, from C++11 through C++20.

0 1,000 2,000 3,000 4,000 5,000 QPS Baseline Cached norms GCC 11.4, baseline: 3,785 queries/s GCC 11.4, with cached norms: 4,445 queries/s (+17.5%) +17.5% GCC 11.4 GCC 13.4, baseline: 3,718 queries/s GCC 13.4, with cached norms: 4,000 queries/s (+7.4%) +7.4% GCC 13.4 7 of 7 paired rounds positive on both compilers
Figure 8. Single-core search throughput on a 1-million-vector, 256-dimensional Wikipedia-embedding index (k=10, 1,024 held-out queries, seven paired rounds per compiler). Both binaries search the identical prebuilt graph.
Arithmetic per cosine comparison 256-dim f32 vectors · HNSW search Before After Multiply-adds per vector element Before: 3 3 After: 1 1 Square roots per comparison Before: 2 2 0 (norms cached) ✓ Traversal unchanged: 926.5 distances per query Footprint: 4 bytes per stored vector (+0.3% memory on a 1M-vector index)
Figure 9. What the cached norm removes from every distance comparison. Traversal is untouched (the same distances and nodes are evaluated per query); each distance is simply cheaper.
Technical details: formulation & implementation
Formulation

Cosine distance between a query a and a stored vector b is

d(a, b) = 1 − a·ba‖ ‖b

USearch's built-in f32/bf16 kernel evaluates a·b, ‖a‖² and ‖b‖² in one pass, three multiply-adds per element, then takes two square roots and one division:

1 − a·b√(‖a‖²) · √(‖b‖²)

It does this for every one of the roughly 927 comparisons an HNSW query performs. But b is a stored member whose norm is fixed from insertion, and a is the query, whose norm is the same for every comparison in the search. Caching ‖b‖ per slot and computing ‖a‖ once per query leaves one multiply-add per element, one multiply and one division. The two expressions are algebraically identical and differ only in floating-point rounding.

Implementation
  • Sidecar. index_dense_gt gains cosine_norms_: one lock-free std::atomic<uint32_t> per capacity slot, holding the raw bits of the f32 norm or a quiet-NaN sentinel (0x7fc00000). Insertion publishes with a release store after the vector bytes are written; search loads with acquire before reading them; reserve, clear, compact, copy, load and metric changes use relaxed accesses because they exclude concurrent insertion. A C++11-compatible static_assert guards lock-freedom.
  • Search proxy. metric_proxy_cosine_norms_t carries the prepared query norm and calls cosine_distance_with_valid_norms. A slot holding the sentinel falls back to the full kernel for that comparison; a non-finite query bypasses the route for the whole search.
  • Eligibility and provenance. supports_cosine_norm_cache() identifies the built-in kernel by the address of the exact metric_cos_gt instantiation plus its dimension argument. It deliberately avoids the routing trampoline, which identical-code-folding linkers (/OPT:ICF, --icf=all) can merge, so a cosine-labelled user callback can never be captured. Custom metrics, NumKong-supplied kernels, memory-mapped views, external-vector indexes and other scalar kinds keep the original path.
  • Lifecycle. reserve grows the sidecar with capacity; add and update populate a slot; remove and clear invalidate it; compact remaps and repopulates; copy duplicates a valid sidecar; load rebuilds it; views bypass it; a metric change builds and populates replacement state before committing, so the index is never left in a partial state. The sidecar is never serialized, so the file format is unchanged.
  • Fast-math safety. All finiteness classification is done on integer bit patterns, and the accumulated norm is laundered through a volatile before inspection, so -ffast-math builds cannot assume it is finite.
// include/usearch/index_dense.hpp: the search-only proxy's hot path
distance_t f(byte_t const* query, member_at member) const noexcept {
    std::uint32_t bits = index_->cosine_norms_[get_slot(member)].load(std::memory_order_acquire);
    if (!metric_t::is_valid_cosine_norm_bits(bits))        // sentinel: full kernel for this member
        return index_->metric_(query, v(member));
    f32_t member_norm = 0;
    std::memcpy(&member_norm, &bits, sizeof(member_norm));
    return index_->metric_.cosine_distance_with_valid_norms(query, v(member), query_norm_, member_norm);
}

// include/usearch/index_plugins.hpp: one dot product, no square roots
result_t cosine_distance_with_valid_norms(byte_t const* a, byte_t const* b,
                                          f32_t a_norm, f32_t b_norm) const noexcept {
    f32_t ab = cosine_dot_(a, b, dimensions_);
    bool a_is_zero = /* norm bits are zero */, b_is_zero = /* likewise for b_norm */;
    if (a_is_zero) return b_is_zero ? 0 : 1;              // zero handling matches metric_cos_gt
    if (b_is_zero) return 1;
    return 1 - ab / (a_norm * b_norm);
}
Evidence
  • Wiki-1M (1M × 256 f32), identical prebuilt graph in both binaries, one pinned core, 1,024 held-out queries, 16 timed repeats, seven paired rounds: +17.54% median QPS with GCC 11.4 (95% bootstrap +17.14% to +17.76%) and +7.41% with GCC 13.4 (+7.20% to +7.61%), 7 of 7 rounds positive on both. Computed distances (926.5 per query) and visited members (75.8 per query) are unchanged in every timed row.
  • Memory 1,333,418,176 → 1,337,418,176 bytes at one million slots, exactly four bytes per slot. Load 0.92–0.94 s → 1.04–1.05 s because the sidecar is rebuilt; 96-thread construction 10.2–10.5 s baseline and 10.1–10.2 s patched.
  • Result parity over 10,240 top-10 outputs: maximum distance change 4.1 × 10−7, recall preserved. The C and C++ suites pass under ASan, LSan, UBSan and alignment sanitizers with GCC 11 and 13, the public-header smoke test passes from C++11 through C++20, the full C++ tests pass under a gold --icf=all link, ThreadSanitizer confirms the new code is race-free, and a NumKong build confirms the route is never taken there.
Cached vector norms · PR #787 ↗ Upstream pull request for the USearch optimization.
4
Salesforce Internal · LLM Training

SFR-RL: taming memory and speed in our own RL stack

SFR-RL is the reinforcement-learning stack Salesforce AI Research uses to post-train large models. We report the results here; implementation details remain internal.

Read about SFR-RL on the Salesforce blog

−39% peak training memory Up to 3.14× generation throughput Token-for-token identical outputs

Optimization 1Memory: from roulette to guarantees

In RL training the model generates its own training data, so each step's memory footprint is drawn fresh every update, and one unlucky draw can blow past GPU memory late in an expensive run. AutoR&D's improvements make peak memory predictable and bounded by configuration: on a demanding long-context workload, peak memory fell from 128.5 GiB (an out-of-memory crash) to a stable 78.6 GiB across 19 consecutive updates, with the training computation itself unchanged.

0 40 80 120 GiB Before: peak allocation 128.5 GiB, ran out of memory 128.5 GiB ✕ ran out of memory Before With AutoR&D: peak allocation 78.6 GiB, 19 updates, stable 78.6 GiB ✓ 19 updates, stable With AutoR&D
Figure 6. Peak trainer memory on the same long-context RL workload. The baseline, already using every standard memory-saving technique, ran out of memory on its first big step.

Optimization 2Throughput: the same answers, three times faster

On the serving side of the loop, AutoR&D cut median time per generated token by 60–69% across four workload types, up to 3.14× baseline throughput on long-output workloads, with the accelerated path verified to produce exactly the same tokens, request by request, in every confirmation run.

0% 20% 40% 60% 80% Short chats: median time per generated token down 65.8%, outputs unchanged −65.8% Short chats Long answers: median time per generated token down 69.4%, outputs unchanged −69.4% Long answers Huge context: median time per generated token down 60.8%, outputs unchanged −60.8% Huge context Mixed traffic: median time per generated token down 62.3%, outputs unchanged −62.3% Mixed traffic
Figure 7. Median reduction in time per generated token across four serving workload types, with generated text verified identical.

Benchmarking the research loop

We evaluate our framework on Bespoke Labs’ AutoResearchExam to study its research efficiency and performance. With GPT-6 Astra powering our framework, we compare against published Astra runs using Terminus 2. Explore the progress curves and the ideas behind each result.

Explore benchmark results

What's Next

These artifacts are a starting point. We're scaling AutoR&D along three axes: more targets, from data infrastructure to the wider open-source ecosystem our customers' AI stacks depend on, and more of Salesforce's own platform; deeper autonomy, longer research arcs where one discovery informs the next hypothesis; and open contribution, packaging discoveries as upstream pull requests with the full evidence attached.


The agents we're most excited about find improvements nobody thought to ask for, and prove they're real. AutoR&D is our first step there.