Skip to content

Broken matrix-matrix multiplication with single-column matrices #1521

@nvb

Description

@nvb

Hi maintainers, thanks for the beautiful library!

I've noticed a bug with matrix-matrix multiplication that materializes only with single-column matrices. Explanation and reproduction below.

Description:

  • Single-column matrices (shape [N, 1]) produce all-zero results when used with matrix-matrix multiplication (dot product) in ndarray 0.16.1 with BLAS enabled
  • The bug affects matrices with 16+ dimensions but not smaller ones (3D works fine)
  • Both column-major and row-major layouts are affected
  • Matrix-vector multiplication (SGEMV) works correctly, but matrix-matrix multiplication (SGEMM) with single-column matrices fails

Reproduction:

#[test]
fn test_ndarray_sgemm_bug_simple() {
    // Minimal ndarray bug reproduction: single-column matrices return all zeros
    use ndarray::prelude::*;

    let n = 64; // Bug manifests at 16+ dimensions
    let matrix = Array2::<f32>::eye(n); // Identity matrix
    let vector: Vec<f32> = (1..=n).map(|i| i as f32).collect();

    // This works (SGEMV):
    let correct = matrix.dot(&ArrayView1::from(&vector));

    // This fails (SGEMM with single-column matrix):
    let single_col = ArrayView2::from_shape((n, 1).f(), &vector).unwrap();
    let buggy = matrix.dot(&single_col);

    println!("SGEMV result: {:?}", &correct.to_vec()[..3]);
    println!("SGEMM result: {:?}", &buggy.column(0).to_vec()[..3]);

    // Should be [1.0, 2.0, 3.0, ...] but SGEMM gives [0.0, 0.0, 0.0, ...]
    let all_zeros = buggy.column(0).iter().all(|&x| x == 0.0);
    if all_zeros {
        println!("🐛 BUG: SGEMM with single-column matrix returns all zeros!");
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions