Skip to content

TurboQuant hadamard Rotation - #8657

Merged
JojiiOfficial merged 13 commits into
devfrom
tq-hadamard
Apr 16, 2026
Merged

JojiiOfficial merged 13 commits into
devfrom
tq-hadamard

Conversation

@JojiiOfficial

@JojiiOfficial JojiiOfficial commented Apr 13, 2026 •

Copy link
Copy Markdown
Member

Implements Hadamard rotation required for the TurboQuant implementation.

Statistics

Below are two important statistics collected from dbpedia vectors, showing that the rotation from this PR properly relaxes the distributions.

Energy distribution

Max component value of each vector. Rotated vectors are tightly clustered around 0.1, meaning that max values of the previously non-rotated vectors (blue) are properly distributed upon the other coordinates.

image

Excess Kurtosis

Measurement of how heavy-tailed / peaked the distribution of components is. Rotated vectors show a very small value, making the individual coordinates/components distribution much more uniform.

image

Performance

Performance of the current implementation (not vectorized with SIMD).

image

@JojiiOfficial JojiiOfficial added this to the TurboQuant milestone Apr 13, 2026
@JojiiOfficial JojiiOfficial mentioned this pull request Apr 14, 2026
63 of 69 tasks
@JojiiOfficial
JojiiOfficial marked this pull request as ready for review April 14, 2026 12:09

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 the current code and only fix it if needed.

Inline comments:
In `@lib/quantization/benches/hadamard.rs`:
- Around line 13-20: The benchmark currently uses dim in BenchmarkId but only
runs the transform on chunk_size = compute_chunk_sizes(dim).first(), so the
BenchmarkId is misleading; update the benchmark to either iterate over all chunk
sizes from compute_chunk_sizes(dim) and run in_place_walsh_hadamard_transform on
each chunk (using BenchmarkId::from_parameter(chunk_size) or similar), or change
the BenchmarkId to reflect the actual chunk_size being measured (use chunk_size
instead of dim). Locate the loop over DIMS, the compute_chunk_sizes call, and
the group.bench_with_input / BenchmarkId::from_parameter usage to apply this
fix.

In `@lib/quantization/src/turboquant/rotation.rs`:
- Around line 124-126: The public function in_place_walsh_hadamard_transform
currently uses debug_assert! for the power-of-two precondition which is disabled
in release builds and can lead to OOB access; change the debug_assert! to a
regular assert! to enforce the check at runtime (or alternatively make
in_place_walsh_hadamard_transform non-public/private if you intend callers to
guarantee the invariant). Update the assertion on n.is_power_of_two() inside the
function so the check runs in release, ensuring safety before the transform
loops execute.
🪄 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: CHILL

Plan: Pro

Run ID: f9ec5f7f-70b6-40a4-852d-a1d15df63ba5

📥 Commits

Reviewing files that changed from the base of the PR and between 6115d76 and fa49ac3.

📒 Files selected for processing (6)
  • lib/quantization/Cargo.toml
  • lib/quantization/benches/hadamard.rs
  • lib/quantization/src/lib.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/src/turboquant/permutation.rs
  • lib/quantization/src/turboquant/rotation.rs

Comment thread lib/quantization/benches/hadamard.rs Outdated
Comment on lines +13 to +20
for &dim in DIMS {
let chunk_size = *compute_chunk_sizes(dim).first().unwrap();
let mut data: Vec<f64> = (0..chunk_size).map(|i| i as f64 * 0.01).collect();

group.bench_with_input(BenchmarkId::from_parameter(dim), &dim, |b, _| {
b.iter(|| {
in_place_walsh_hadamard_transform(black_box(&mut data));
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Benchmark the same workload you label.

bench_wht currently measures only compute_chunk_sizes(dim).first(), so non-power-of-two cases benchmark the largest chunk rather than the full dimension (384 -> 256, 768 -> 512, 1536 -> 1024, ...). That makes the BenchmarkId look like a full-dimension run while the actual work is smaller. Either benchmark every chunk in the decomposition or label the run with the chunk size instead.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/benches/hadamard.rs` around lines 13 - 20, The benchmark
currently uses dim in BenchmarkId but only runs the transform on chunk_size =
compute_chunk_sizes(dim).first(), so the BenchmarkId is misleading; update the
benchmark to either iterate over all chunk sizes from compute_chunk_sizes(dim)
and run in_place_walsh_hadamard_transform on each chunk (using
BenchmarkId::from_parameter(chunk_size) or similar), or change the BenchmarkId
to reflect the actual chunk_size being measured (use chunk_size instead of dim).
Locate the loop over DIMS, the compute_chunk_sizes call, and the
group.bench_with_input / BenchmarkId::from_parameter usage to apply this fix.

Comment on lines +124 to +126
pub fn in_place_walsh_hadamard_transform(x: &mut [f64]) {
let n = x.len();
debug_assert!(n.is_power_of_two(), "WHT requires power-of-2 length");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Make the WHT precondition enforceable in release.

in_place_walsh_hadamard_transform is public, but its power-of-two guard is debug_assert! only. On a non-power-of-two slice, the inner loop can still hit an out-of-bounds index in release builds. Use assert! here or keep the helper private.

Minimal fix
 pub fn in_place_walsh_hadamard_transform(x: &mut [f64]) {
     let n = x.len();
-    debug_assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
+    assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn in_place_walsh_hadamard_transform(x: &mut [f64]) {
let n = x.len();
debug_assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
pub fn in_place_walsh_hadamard_transform(x: &mut [f64]) {
let n = x.len();
assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` around lines 124 - 126, The
public function in_place_walsh_hadamard_transform currently uses debug_assert!
for the power-of-two precondition which is disabled in release builds and can
lead to OOB access; change the debug_assert! to a regular assert! to enforce the
check at runtime (or alternatively make in_place_walsh_hadamard_transform
non-public/private if you intend callers to guarantee the invariant). Update the
assertion on n.is_power_of_two() inside the function so the check runs in
release, ensuring safety before the transform loops execute.

@JojiiOfficial JojiiOfficial changed the title [WIP] TurboQuant hadamard Rotation TurboQuant hadamard Rotation Apr 14, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
lib/quantization/src/turboquant/rotation.rs (1)

124-126: ⚠️ Potential issue | 🟠 Major

The public WHT helper still needs a release-build precondition check.

On Line 126, the power-of-two guard disappears in release, so a non-power-of-two slice can still run the inner j + h access out of bounds. Either keep this helper private or enforce the invariant at runtime.

Minimal fix
 pub fn in_place_walsh_hadamard_transform(x: &mut [f64]) {
     let n = x.len();
-    debug_assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
+    assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` around lines 124 - 126, The
public function in_place_walsh_hadamard_transform currently uses debug_assert!
which is removed in release builds and can lead to OOB when x.len() isn't a
power-of-two; change the precondition to a runtime check by replacing
debug_assert! with assert!(n.is_power_of_two(), "WHT requires power-of-2
length") (or return a Result/Err if you prefer non-panicking API) so the
invariant is enforced in release, referencing the function name
in_place_walsh_hadamard_transform to locate the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/quantization/src/turboquant/rotation.rs`:
- Around line 50-57: The apply method currently uses debug_assert_eq! and then
zips x with self.signs1 which silently truncates mismatched lengths; before
building buf (and before any uses of wht_normalized_chunks) validate x.len() ==
self.dim at runtime and return a Result to propagate errors (or at minimum
replace debug_assert_eq! with assert_eq!); update the signature of apply (or add
an internal check) to return Result<Vec<f32>, RotationError> (or similar) and
return an Err when lengths differ, referencing apply, self.dim, buf, signs1 and
wht_normalized_chunks so callers get a clear runtime failure instead of silent
truncation or panics.

---

Duplicate comments:
In `@lib/quantization/src/turboquant/rotation.rs`:
- Around line 124-126: The public function in_place_walsh_hadamard_transform
currently uses debug_assert! which is removed in release builds and can lead to
OOB when x.len() isn't a power-of-two; change the precondition to a runtime
check by replacing debug_assert! with assert!(n.is_power_of_two(), "WHT requires
power-of-2 length") (or return a Result/Err if you prefer non-panicking API) so
the invariant is enforced in release, referencing the function name
in_place_walsh_hadamard_transform to locate the change.
🪄 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: CHILL

Plan: Pro

Run ID: fba4e632-981b-44be-af7c-4265e3ece195

📥 Commits

Reviewing files that changed from the base of the PR and between fa49ac3 and 308b3da.

📒 Files selected for processing (5)
  • lib/quantization/Cargo.toml
  • lib/quantization/benches/hadamard.rs
  • lib/quantization/src/turboquant/mod.rs
  • lib/quantization/src/turboquant/permutation.rs
  • lib/quantization/src/turboquant/rotation.rs
✅ Files skipped from review due to trivial changes (2)
  • lib/quantization/Cargo.toml
  • lib/quantization/src/turboquant/mod.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • lib/quantization/benches/hadamard.rs
  • lib/quantization/src/turboquant/permutation.rs

Comment on lines +50 to +57
pub fn apply(&self, x: &[f32]) -> Vec<f32> {
debug_assert_eq!(x.len(), self.dim);

let mut buf: Vec<f64> = x
.iter()
.zip(&self.signs1)
.map(|(&v, &s)| f64::from(v) * s)
.collect();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Reject length mismatches in release, not only in debug.

On Lines 53-57 and 80-84, zip silently truncates longer inputs, and shorter inputs crash later when wht_normalized_chunks slices past the collected buffer. Please enforce self.dim before building buf—ideally by returning a Result, or at minimum with a runtime assert_eq!.

Minimal fix
     pub fn apply(&self, x: &[f32]) -> Vec<f32> {
-        debug_assert_eq!(x.len(), self.dim);
+        assert_eq!(x.len(), self.dim, "HadamardRotation::apply expects {} elements", self.dim);

     pub fn apply_inverse(&self, y: &[f32]) -> Vec<f32> {
-        debug_assert_eq!(y.len(), self.dim);
+        assert_eq!(y.len(), self.dim, "HadamardRotation::apply_inverse expects {} elements", self.dim);

Also applies to: 77-84

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` around lines 50 - 57, The apply
method currently uses debug_assert_eq! and then zips x with self.signs1 which
silently truncates mismatched lengths; before building buf (and before any uses
of wht_normalized_chunks) validate x.len() == self.dim at runtime and return a
Result to propagate errors (or at minimum replace debug_assert_eq! with
assert_eq!); update the signature of apply (or add an internal check) to return
Result<Vec<f32>, RotationError> (or similar) and return an Err when lengths
differ, referencing apply, self.dim, buf, signs1 and wht_normalized_chunks so
callers get a clear runtime failure instead of silent truncation or panics.

@qdrant qdrant deleted a comment from coderabbitai Bot Apr 15, 2026
@IvanPleshkov

Copy link
Copy Markdown
Contributor

Permutations can be implemented without tmp buffers and persistent map-remap arrays.
You did a Fisher–Yates shuffle already. It makes permutations in-place, so for the forward permutation, we don't need to have a map buffer because that's how the Fisher–Yates shuffle is designed.
For backward permutation, the question is more interesting.
It seems we can restore the permutation when we just reverse the for loop in the alg. But we need to restore randomly generated values. It's possible. The trivial way of such a kind of generator is random(i) = hash(seed + i), such an approach can predict "which value will be generated after N gen calls?". But I propose a linear congruential generator, which is more performant.

the ai generated code snippet based on my proposals:

struct ReversibleLcg {
    state: u64,
}

impl ReversibleLcg {
    const A: u64 = 6_364_136_223_846_793_005;
    const C: u64 = 1_442_695_040_888_963_407;
    const A_INV: u64 = 13_877_824_140_714_322_085;

    fn new(seed: u64) -> Self {
        Self { state: seed }
    }

    fn next(&mut self) -> u64 {
        self.state = self.state.wrapping_mul(Self::A).wrapping_add(Self::C);
        self.state
    }

    fn prev(&mut self) -> u64 {
        let val = self.state;
        self.state = self.state.wrapping_sub(Self::C).wrapping_mul(Self::A_INV);
        val
    }
}

struct Permutor {
    seed: u64,
    count: usize,
    end_state: u64,
}

impl Permutor {
    fn new(seed: u64, count: usize) -> Self {
        let mut rng = ReversibleLcg::new(seed);
        for _ in 1..count {
            rng.next();
        }
        Self { seed, count, end_state: rng.state }
    }

    fn permute<T>(&self, arr: &mut [T]) {
        assert_eq!(arr.len(), self.count);
        let mut rng = ReversibleLcg::new(self.seed);
        for i in (1..self.count).rev() {
            let j = (rng.next() % (i as u64 + 1)) as usize;
            arr.swap(i, j);
        }
    }

    fn unpermute<T>(&self, arr: &mut [T]) {
        assert_eq!(arr.len(), self.count);
        let mut rng = ReversibleLcg { state: self.end_state };
        for i in 1..self.count {
            let j = (rng.prev() % (i as u64 + 1)) as usize;
            arr.swap(i, j);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_lcg_reversibility() {
        let mut rng = ReversibleLcg::new(12345);
        let values: Vec<u64> = (0..10).map(|_| rng.next()).collect();

        for v in values.iter().rev() {
            assert_eq!(rng.prev(), *v);
        }
    }

    #[test]
    fn test_permute_unpermute() {
        let original: Vec<u32> = (0..100).collect();
        let permutor = Permutor::new(42, 100);

        let mut arr = original.clone();
        permutor.permute(&mut arr);
        assert_ne!(arr, original);

        permutor.unpermute(&mut arr);
        assert_eq!(arr, original);
    }

    #[test]
    fn test_edge_cases() {
        let mut arr = vec![42];
        let p = Permutor::new(0, 1);
        p.permute(&mut arr);
        assert_eq!(arr, vec![42]);
        p.unpermute(&mut arr);
        assert_eq!(arr, vec![42]);

        let original = vec![1, 2];
        let p = Permutor::new(99, 2);
        let mut arr = original.clone();
        p.permute(&mut arr);
        p.unpermute(&mut arr);
        assert_eq!(arr, original);
    }
}

@coderabbitai

coderabbitai Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Hadamard rotation functionality and supporting permutation logic to the quantization library. Introduces a new public rotation module (HadamardRotation, apply, apply_inverse, chunk-size computation, and in-place Walsh–Hadamard transform), a new internal permutation module (reversible 64-bit LCG and public Permutation with permute/unpermute), unit tests for both modules, a Criterion benchmark hadamard, and a corresponding [[bench]] entry in lib/quantization/Cargo.toml. Also updates turboquant module to expose rotation and declare permutation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'TurboQuant hadamard Rotation' directly describes the main change—implementing a Hadamard rotation for TurboQuant. It is concise, specific, and clearly summarizes the primary change across all modified and new files.
Description check ✅ Passed The description explains that the PR implements Hadamard rotation required for TurboQuant, provides statistical validation showing the rotation properly distributes vector components, and includes performance benchmarks demonstrating linear scaling behavior.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tq-hadamard

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 and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (2)
lib/quantization/src/turboquant/rotation.rs (2)

45-52: ⚠️ Potential issue | 🟠 Major

Validate input length in release builds.

zip silently truncates overlong inputs, while shorter inputs panic later once wht_normalized_chunks or Permutation::apply indexes past the collected buffer. Because both entry points are public, debug_assert_eq! leaves a real release-path failure here.

Minimal fix
     pub fn apply(&self, x: &[f32]) -> Vec<f32> {
-        debug_assert_eq!(x.len(), self.dim);
+        assert_eq!(
+            x.len(),
+            self.dim,
+            "HadamardRotation::apply expects {} elements",
+            self.dim
+        );

     pub fn apply_inverse(&self, y: &[f32]) -> Vec<f32> {
-        debug_assert_eq!(y.len(), self.dim);
+        assert_eq!(
+            y.len(),
+            self.dim,
+            "HadamardRotation::apply_inverse expects {} elements",
+            self.dim
+        );

Also applies to: 69-72

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` around lines 45 - 52, Replace
the release-only debug_assert_eq! in the pub fn apply(&self, x: &[f32]) ->
Vec<f32> with an explicit runtime check that validates x.len() == self.dim and
panics with a clear message (include actual x.len() and self.dim) if it does
not; do the same for the other similar check around the second buffer
construction (the block that zips with self.signs2). This ensures overlong or
short inputs fail fast before wht_normalized_chunks or Permutation::apply index
past the buffer and makes the error visible in release builds.

112-115: ⚠️ Potential issue | 🟠 Major

Keep the WHT precondition enforceable in release.

This helper is public, but its power-of-two check disappears in release builds. On invalid input, x[j + h] can go out of bounds once the transform loop starts.

Minimal fix
 pub fn in_place_walsh_hadamard_transform(x: &mut [f64]) {
     let n = x.len();
-    debug_assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
+    assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` around lines 112 - 115, The
public function in_place_walsh_hadamard_transform currently uses debug_assert!
for the power-of-two precondition which disappears in release builds and can
lead to out-of-bounds accesses; replace the debug_assert! with a runtime check
that enforces the precondition (e.g., assert!(n.is_power_of_two(), "WHT requires
power-of-2 length") or an explicit if !n.is_power_of_two() { panic!(...) }), so
callers get a clear error before the transform loop that uses x and h runs.
🧹 Nitpick comments (1)
lib/quantization/src/turboquant/rotation.rs (1)

57-63: Avoid allocating a scratch buffer on every rotation call.

tmp = vec![0.0; buf.len()] adds a second full-size heap allocation and zero-fill per vector in both hot paths. Reusing caller-provided scratch space, or switching the permutation layer to an in-place/replay approach, would reduce allocator pressure noticeably.

Also applies to: 77-83

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` around lines 57 - 63, The code
currently allocates a fresh scratch buffer with let mut tmp = vec![0.0f64;
buf.len()] inside Rotation::rotate (and the analogous block at lines 77-83);
change the API to reuse scratch space instead of allocating: add a tmp: &mut
[f64] parameter (or add a reusable Vec<f64> scratch field on the Rotation
struct) and use that slice for permutation.apply and any other temp work,
ensuring its length >= buf.len(); update calls to Rotation::rotate (and the
second allocation site) to pass the caller-provided scratch buffer and remove
the per-call vec! allocation so no heap allocation/zero-fill happens inside the
hot path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@lib/quantization/src/turboquant/rotation.rs`:
- Around line 45-52: Replace the release-only debug_assert_eq! in the pub fn
apply(&self, x: &[f32]) -> Vec<f32> with an explicit runtime check that
validates x.len() == self.dim and panics with a clear message (include actual
x.len() and self.dim) if it does not; do the same for the other similar check
around the second buffer construction (the block that zips with self.signs2).
This ensures overlong or short inputs fail fast before wht_normalized_chunks or
Permutation::apply index past the buffer and makes the error visible in release
builds.
- Around line 112-115: The public function in_place_walsh_hadamard_transform
currently uses debug_assert! for the power-of-two precondition which disappears
in release builds and can lead to out-of-bounds accesses; replace the
debug_assert! with a runtime check that enforces the precondition (e.g.,
assert!(n.is_power_of_two(), "WHT requires power-of-2 length") or an explicit if
!n.is_power_of_two() { panic!(...) }), so callers get a clear error before the
transform loop that uses x and h runs.

---

Nitpick comments:
In `@lib/quantization/src/turboquant/rotation.rs`:
- Around line 57-63: The code currently allocates a fresh scratch buffer with
let mut tmp = vec![0.0f64; buf.len()] inside Rotation::rotate (and the analogous
block at lines 77-83); change the API to reuse scratch space instead of
allocating: add a tmp: &mut [f64] parameter (or add a reusable Vec<f64> scratch
field on the Rotation struct) and use that slice for permutation.apply and any
other temp work, ensuring its length >= buf.len(); update calls to
Rotation::rotate (and the second allocation site) to pass the caller-provided
scratch buffer and remove the per-call vec! allocation so no heap
allocation/zero-fill happens inside the hot path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 26ff0577-116d-410f-8064-a599cb8bcc31

📥 Commits

Reviewing files that changed from the base of the PR and between 308b3da and c3b23a7.

📒 Files selected for processing (1)
  • lib/quantization/src/turboquant/rotation.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
lib/quantization/src/turboquant/rotation.rs (2)

77-77: Minor: Redundant slice in apply_inverse.

Since buf is created with length y.len() (which should equal self.dim), the slice buf[..self.dim] is equivalent to buf. This could be simplified to buf.iter().map(...) for consistency with apply.

Suggested simplification
-        buf[..self.dim].iter().map(|&v| v as f32).collect()
+        buf.iter().map(|&v| v as f32).collect()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` at line 77, In apply_inverse,
remove the redundant slice operation buf[..self.dim] and simply iterate over buf
directly; update the expression that builds the Vec<f32> from buf to use
buf.iter().map(|&v| v as f32).collect() (refer to the apply_inverse function and
the buf variable and self.dim) so it matches the simpler style used in apply.

1-1: Consider removing unused generate_signs function.

The generate_signs function (Lines 141-152) is unused, which is why #![allow(dead_code)] is needed. If this is leftover from a previous design iteration, consider removing it. If it's planned for future use, a brief // TODO: comment would clarify intent.

Also applies to: 141-152

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` at line 1, The unused function
generate_signs should be removed (or explicitly documented) to avoid the blanket
#![allow(dead_code)]; either delete the generate_signs function (and then remove
the module-level #![allow(dead_code)] if no other dead code remains) or keep it
but add a clear TODO comment above generate_signs explaining why it is retained
for future use; update or remove the #![allow(dead_code)] attribute accordingly
so dead-code suppression is only present if truly needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/quantization/src/turboquant/rotation.rs`:
- Line 77: In apply_inverse, remove the redundant slice operation
buf[..self.dim] and simply iterate over buf directly; update the expression that
builds the Vec<f32> from buf to use buf.iter().map(|&v| v as f32).collect()
(refer to the apply_inverse function and the buf variable and self.dim) so it
matches the simpler style used in apply.
- Line 1: The unused function generate_signs should be removed (or explicitly
documented) to avoid the blanket #![allow(dead_code)]; either delete the
generate_signs function (and then remove the module-level #![allow(dead_code)]
if no other dead code remains) or keep it but add a clear TODO comment above
generate_signs explaining why it is retained for future use; update or remove
the #![allow(dead_code)] attribute accordingly so dead-code suppression is only
present if truly needed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 59ca9e3d-954a-4098-b78a-a1cb8dd16358

📥 Commits

Reviewing files that changed from the base of the PR and between c3b23a7 and 0ede077.

📒 Files selected for processing (2)
  • lib/quantization/src/turboquant/permutation.rs
  • lib/quantization/src/turboquant/rotation.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (2)
lib/quantization/src/turboquant/rotation.rs (2)

98-100: ⚠️ Potential issue | 🟠 Major

Enforce the WHT precondition in release too.

This helper is public, and a non-power-of-two slice can reach x[j + h] out of bounds once the debug_assert! is compiled out. Use assert! here or reduce the function visibility.

Minimal fix
 pub fn in_place_walsh_hadamard_transform(x: &mut [f64]) {
     let n = x.len();
-    debug_assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
+    assert!(n.is_power_of_two(), "WHT requires power-of-2 length");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` around lines 98 - 100, The
public function in_place_walsh_hadamard_transform currently uses debug_assert!
to check that x.len() is a power of two, which is elided in release builds and
can lead to OOB access; replace the debug_assert! with a runtime assertion
(assert!) to enforce the precondition in all builds (or alternatively reduce the
function's visibility to non-public if you intend to keep checks only for
tests), ensuring the assertion references x.len() and the same message so
callers get a clear failure if the length is not a power of two.

46-49: ⚠️ Potential issue | 🟠 Major

Reject length mismatches outside debug builds.

debug_assert_eq! disappears in release. Short inputs then panic when wht_normalized_chunks slices past buf, and overlong inputs are handled inconsistently—apply_inverse even drops the tail on Line 77. Check the length before building buf (or return a Result from the public API).

Minimal fix
     pub fn apply(&self, x: &[f32]) -> Vec<f32> {
-        debug_assert_eq!(x.len(), self.dim);
+        assert_eq!(
+            x.len(),
+            self.dim,
+            "HadamardRotation::apply expects {} elements",
+            self.dim
+        );

     pub fn apply_inverse(&self, y: &[f32]) -> Vec<f32> {
-        debug_assert_eq!(y.len(), self.dim);
+        assert_eq!(
+            y.len(),
+            self.dim,
+            "HadamardRotation::apply_inverse expects {} elements",
+            self.dim
+        );

Also applies to: 63-65, 77-77

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` around lines 46 - 49, Replace
the disappearing debug-only assertions with an explicit runtime length check
before allocating or slicing buffers: in pub fn apply and pub fn apply_inverse
(and the other affected sites that reference wht_normalized_chunks and buf),
validate x.len() == self.dim at the top of the function; either return a
Result::Err with a clear error (preferred if you can change the public
signature) or else panic with a descriptive message (if you must keep the
current signature), and apply the same check before converting x into buf to
prevent slicing past its end or silently dropping tails.
🧹 Nitpick comments (1)
lib/quantization/src/turboquant/rotation.rs (1)

1-1: Narrow the dead-code allowance.

#![allow(dead_code)] at file scope will also hide future unused private helpers/fields in this module. Prefer removing it, or move the allowance onto the specific item that still isn't wired up.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/quantization/src/turboquant/rotation.rs` at line 1, The file-wide
#[allow(dead_code)] should be removed and the allowance narrowed to only the
specific items that need it (e.g., private helper functions or structs in this
module); locate the top-level attribute in rotation.rs and either delete it or
move an #[allow(dead_code)] attribute onto the particular symbols (for example,
helper function names or private structs/enums) that the compiler still warns
about so future unused items are not globally silenced.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@lib/quantization/src/turboquant/rotation.rs`:
- Around line 98-100: The public function in_place_walsh_hadamard_transform
currently uses debug_assert! to check that x.len() is a power of two, which is
elided in release builds and can lead to OOB access; replace the debug_assert!
with a runtime assertion (assert!) to enforce the precondition in all builds (or
alternatively reduce the function's visibility to non-public if you intend to
keep checks only for tests), ensuring the assertion references x.len() and the
same message so callers get a clear failure if the length is not a power of two.
- Around line 46-49: Replace the disappearing debug-only assertions with an
explicit runtime length check before allocating or slicing buffers: in pub fn
apply and pub fn apply_inverse (and the other affected sites that reference
wht_normalized_chunks and buf), validate x.len() == self.dim at the top of the
function; either return a Result::Err with a clear error (preferred if you can
change the public signature) or else panic with a descriptive message (if you
must keep the current signature), and apply the same check before converting x
into buf to prevent slicing past its end or silently dropping tails.

---

Nitpick comments:
In `@lib/quantization/src/turboquant/rotation.rs`:
- Line 1: The file-wide #[allow(dead_code)] should be removed and the allowance
narrowed to only the specific items that need it (e.g., private helper functions
or structs in this module); locate the top-level attribute in rotation.rs and
either delete it or move an #[allow(dead_code)] attribute onto the particular
symbols (for example, helper function names or private structs/enums) that the
compiler still warns about so future unused items are not globally silenced.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: be72c24c-1f82-4f50-992e-910087f400c2

📥 Commits

Reviewing files that changed from the base of the PR and between 0ede077 and 951dcd1.

📒 Files selected for processing (2)
  • lib/quantization/benches/hadamard.rs
  • lib/quantization/src/turboquant/rotation.rs
✅ Files skipped from review due to trivial changes (1)
  • lib/quantization/benches/hadamard.rs

@IvanPleshkov IvanPleshkov left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Love it!

@JojiiOfficial
JojiiOfficial merged commit 8bd1600 into dev Apr 16, 2026
15 checks passed
@JojiiOfficial
JojiiOfficial deleted the tq-hadamard branch April 16, 2026 09:46
This was referenced Apr 29, 2026
timvisee pushed a commit that referenced this pull request May 8, 2026
* [ai + manual] Implement Hadamard rotation

# Conflicts:
#	lib/quantization/src/turboquant/mod.rs

* [ai + manual] Defer normalization and reduce iterations

* Test improvements + Clippy

* [AI] Don't use fixed-size chunks

* [AI + Manual] Extract permutations and add more tests

* Add normalization + Remove signs2

* Remove signs2 too and improve chunk size function

* [ai] Improve code

* [ai] use reversible LCG for O(1) memory shuffle

* Bench fixes + Remove constant in seed

* [ai] Review Remarks

* [ai] Review remarks

* [ai + manual] In-Place rotations
@coderabbitai coderabbitai Bot mentioned this pull request May 28, 2026
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.

2 participants