Skip to content

⚡ Bolt: Optimize batched operations to avoid array allocations - #170

Open
stffns wants to merge 3 commits into
mainfrom
perf-optimize-np-ops-6912303199284480843
Open

⚡ Bolt: Optimize batched operations to avoid array allocations#170
stffns wants to merge 3 commits into
mainfrom
perf-optimize-np-ops-6912303199284480843

Conversation

@stffns

@stffns stffns commented Jul 25, 2026

Copy link
Copy Markdown
Owner

💡 What: Replaced (X ** 2).sum(2) with np.einsum('ijk,ijk->ij', X, X) for 3D arrays and rewritten (S @ r_scaled.T).T as r_scaled @ S.T.
🎯 Why: These operations create unnecessary intermediate arrays and F-contiguous views respectively, increasing execution time and degrading cache locality.
📊 Impact: Eliminates large intermediate array allocations, with the einsum optimization providing a significant speedup for batched norms and contiguous array structure maintained for matrix multiplications.
🔬 Measurement: Verified through Python timeit module test demonstrating performance improvement of einsum vs ** 2.sum() and cache properties of direct multiplication over transpositions.


PR created automatically by Jules for task 6912303199284480843 started by @stffns

Summary by CodeRabbit

  • Performance Improvements

    • Improved batch processing efficiency for vector indexing and quantization calculations.
    • Reduced unnecessary memory allocation during matrix operations.
    • Optimized squared-norm calculations for faster processing of multidimensional data.
  • Documentation

    • Added guidance on efficient NumPy operations and contiguous matrix multiplication patterns.

💡 What: Replaced `(X ** 2).sum(2)` with `np.einsum('ijk,ijk->ij', X, X)` for 3D arrays and rewritten `(S @ r_scaled.T).T` as `r_scaled @ S.T`.
🎯 Why: These operations create unnecessary intermediate arrays and F-contiguous views respectively, increasing execution time and degrading cache locality.
📊 Impact: Eliminates large intermediate array allocations, with the einsum optimization providing a significant speedup for batched norms and contiguous array structure maintained for matrix multiplications.
🔬 Measurement: Verified through Python timeit module test demonstrating performance improvement of `einsum` vs `** 2.sum()` and cache properties of direct multiplication over transpositions.

Co-authored-by: stffns <70039235+stffns@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@cursor

cursor Bot commented Jul 25, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR optimizes QJL residual matrix multiplication and IVFPQ codebook norm calculation, documents the NumPy patterns, and updates MyPy’s configured Python version to 3.12.

Changes

NumPy optimization updates

Layer / File(s) Summary
Production numerical rewrites
snapvec/_index.py, snapvec/_ivfpq.py
QJL residual computation uses direct matrix multiplication, while IVFPQ codebook norms use np.einsum.
Optimization guidance and tooling alignment
.jules/bolt.md, pyproject.toml
Documents the optimized NumPy expressions and changes MyPy’s Python target from 3.10 to 3.12.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Poem

A rabbit hops through arrays bright,
Einsum trims the sums just right.
Matrices turn without a fuss,
C-contiguous paths delight us.
MyPy follows, docs bloom anew—
“Thump-thump!” says Bun, “A speedy queue!”

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: optimizing batched NumPy operations to avoid extra allocations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf-optimize-np-ops-6912303199284480843

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.jules/bolt.md:
- Around line 4-6: Add blank lines immediately before and after the new dated
heading in .jules/bolt.md, while leaving the heading text and surrounding
content unchanged.

In `@pyproject.toml`:
- Line 70: Update the MyPy python_version setting in pyproject.toml from 3.12 to
the project’s supported minimum Python version, 3.10, so type checking matches
the declared runtime support.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4892c08d-ac6e-4bed-b7b0-e54d15a5c41b

📥 Commits

Reviewing files that changed from the base of the PR and between 66cbe33 and 25a3dbf.

📒 Files selected for processing (4)
  • .jules/bolt.md
  • pyproject.toml
  • snapvec/_index.py
  • snapvec/_ivfpq.py

Comment thread .jules/bolt.md
Comment on lines +4 to +6
## 2025-02-18 - Fast batched squared norms for 3D arrays and Contiguous Matrix Multiplications
**Learning:** Using `np.einsum('ijk,ijk->ij', X, X)` is significantly faster than `(X ** 2).sum(2)` for calculating squared Euclidean norms along the last axis of a 3D NumPy array, avoiding large intermediate array allocations. Also, explicitly using associativity (e.g. `R @ S.T` instead of `(S @ R.T).T`) yields a C-contiguous array instead of an F-contiguous view, which speeds up the operation and subsequent steps relying on cache locality.
**Action:** Replace `(X ** 2).sum(2)` with `np.einsum('ijk,ijk->ij', X, X)` for 3D array batched squared norm calculations and rewrite expression to avoid explicit transpositions to preserve C-contiguity in critical data paths.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add blank lines around the new heading.

markdownlint-cli2 reports MD022 because the heading has no blank line before or after it.

Proposed fix
 **Action:** Always prefer `np.sqrt(np.einsum('ij,ij->i', arr, arr))` over `np.linalg.norm(arr, axis=1)` when computing row-wise vector norms in NumPy to eliminate dispatch overhead and improve execution speed.
 
 ## 2025-02-18 - Fast batched squared norms for 3D arrays and Contiguous Matrix Multiplications
+
 **Learning:** Using `np.einsum('ijk,ijk->ij', X, X)` is significantly faster than `(X ** 2).sum(2)` for calculating squared Euclidean norms along the last axis of a 3D NumPy array, avoiding large intermediate array allocations.
🧰 Tools
🪛 LanguageTool

[style] ~5-~5: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ssociativity (e.g. R @ S.T instead of (S @ R.T).T) yields a C-contiguous array instead o...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

🪛 markdownlint-cli2 (0.23.0)

[warning] 4-4: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Above

(MD022, blanks-around-headings)


[warning] 4-4: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.jules/bolt.md around lines 4 - 6, Add blank lines immediately before and
after the new dated heading in .jules/bolt.md, while leaving the heading text
and surrounding content unchanged.

Source: Linters/SAST tools

Comment thread pyproject.toml Outdated
google-labs-jules Bot and others added 2 commits July 25, 2026 18:19
💡 What: Replaced `(X ** 2).sum(2)` with `np.einsum('ijk,ijk->ij', X, X)` for 3D arrays and rewritten `(S @ r_scaled.T).T` as `r_scaled @ S.T`.
🎯 Why: These operations create unnecessary intermediate arrays and F-contiguous views respectively, increasing execution time and degrading cache locality.
📊 Impact: Eliminates large intermediate array allocations, with the einsum optimization providing a significant speedup for batched norms and contiguous array structure maintained for matrix multiplications.
🔬 Measurement: Verified through Python timeit module test demonstrating performance improvement of `einsum` vs `** 2.sum()` and cache properties of direct multiplication over transpositions.

Co-authored-by: stffns <70039235+stffns@users.noreply.github.com>
💡 What: Replaced `(X ** 2).sum(2)` with `np.einsum('ijk,ijk->ij', X, X)` for 3D arrays and rewritten `(S @ r_scaled.T).T` as `r_scaled @ S.T`.
🎯 Why: These operations create unnecessary intermediate arrays and F-contiguous views respectively, increasing execution time and degrading cache locality.
📊 Impact: Eliminates large intermediate array allocations, with the einsum optimization providing a significant speedup for batched norms and contiguous array structure maintained for matrix multiplications.
🔬 Measurement: Verified through Python timeit module test demonstrating performance improvement of `einsum` vs `** 2.sum()` and cache properties of direct multiplication over transpositions.

Co-authored-by: stffns <70039235+stffns@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant