Skip to content

Fix vector/matrix product (@) silently overflowing for narrow value dtypes - #44

Merged
aarmey merged 1 commit into
mainfrom
fix-43-matmul-narrow-dtype-overflow
Sep 11, 2026
Merged

aarmey merged 1 commit into
mainfrom
fix-43-matmul-narrow-dtype-overflow

Conversation

@aarmey

@aarmey aarmey commented Sep 11, 2026

Copy link
Copy Markdown
Member

Summary

  • vector @ VCSRArray / VCSRArray @ vector (and the 2-D @ matrix variants) allocated their output accumulator using values.dtype — the compact stored-element dtype (e.g. uint16 for single-cell counts) — instead of a dtype wide enough for the accumulated total, so results silently wrapped modulo 2**bits while sum() (which already accumulates in float64) stayed correct.
  • Fix: promote values and the other operand to their common np.result_type before running the _ops.py kernels, matching the dtype promotion an equivalent dense-array product would get.

Test plan

  • Added test_matmul_does_not_overflow_narrow_value_dtype in tests/test_ops.py, covering both @ directions and both vector/matrix operands, for both VCSRArray and VCSCArray, reproducing the issue's uint16 repro.
  • uv run pytest -q — 1662 passed, 109 skipped.
  • uv run ruff check — clean.

Fixes #43.

🤖 Generated with Claude Code

…types

_major_matvec/_minor_matvec/_major_matmat/_minor_matmat allocated their
output accumulator as values.dtype, the compact per-element storage
dtype (e.g. uint16 for single-cell counts), instead of a dtype sized
for the accumulated total. Contributions landing in the same output
slot wrapped modulo 2**bits instead of promoting, unlike sum() which
already accumulates in float64.

Promote values and the other operand to their common numpy dtype
(np.result_type) before running the kernels, matching the dtype
promotion an equivalent dense-array product would get.

Fixes #43.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@aarmey
aarmey merged commit aa171bd into main Sep 11, 2026
6 checks passed
@aarmey
aarmey deleted the fix-43-matmul-narrow-dtype-overflow branch September 11, 2026 17:05
fishidaho added a commit that referenced this pull request Sep 18, 2026
`_ops._major_matvec`/`_major_matmat` -- the scatter direction, reached by
`VCSC @ B` and `B @ VCSR` -- ran single-threaded with no strategy at all,
losing to scipy by up to 4x:

    VCSC @ x            8.7 ms   vs scipy   6.7 ms   1.30x
    VCSC @ B  (k=8)    20.1 ms   vs scipy  21.0 ms   0.96x
    x @ VCSR           20.5 ms   vs scipy   5.1 ms   3.99x
    B @ VCSR  (p=8)    28.5 ms   vs scipy  14.6 ms   1.96x

They cannot be parallelized over the major axis directly, since two major
slices can collide on the same output index.

Regrouping a chunk into the opposite format and running an aligned kernel --
the strategy `_vcs_matmul` uses for the normalized view -- was tried first and
is much worse here. That path caches its transposed copy and amortizes it
across an iterative algorithm's many products; a bare `A @ B` pays the regroup
once per call, which turned the 8.7 ms product into 700 ms. Reverted.

Thread-local accumulators instead -- the shape `minor_sums`/`minor_extrema`
already use -- reduced across threads afterwards. The thread count is the
whole design problem: the scatter is `nnz * width` work split across threads
while the reduction is `nthreads * n_minor * width`, so more threads is not
better. Measured on 6M nonzeros over 60k x 2k, letting the existing 64 MiB
accumulator budget pick 48 threads for a width-8 product ran it in 56.6 ms,
*slower than the serial kernel's* 23.3 ms; 4 threads and 15 MB ran it in
11.6 ms.

`scatter_threads()` takes the smaller of two bounds. Setting the derivative of
scatter-plus-reduction to zero puts the optimum at `sqrt(nnz / n_minor)`,
which is 10 for that array against a measured best of 16/8/4 at widths 1/4/8 --
right in magnitude, but blind to width. A 16 MiB byte cap supplies the missing
width-dependence, admitting fewer threads exactly as the accumulator grows.
Together they track the measured optimum across widths:

    VCSC @ x            2.4 ms   vs scipy   6.7 ms   0.35x   (was 1.30x)
    VCSC @ B  (k=8)    12.0 ms   vs scipy  21.6 ms   0.56x   (was 0.96x)
    x @ VCSR            1.8 ms   vs scipy   5.2 ms   0.36x   (was 3.99x)
    B @ VCSR  (p=8)     5.2 ms   vs scipy  14.3 ms   0.36x   (was 1.96x)

Peak allocation stays bounded by the cap rather than by `nnz`: 5.3 MB at
width 1, 19.2 MB at width 8, 23.0 MB at width 16. Single-thread cases fall
back to the serial kernels rather than pay an allocation and a reduction pass
for one partial.

Three benchmark cases now cover this direction; the existing
`matvec_vs_scipy`/`matmat_vs_scipy` only ever ran VCSR aligned.

Rebased from the pre-0.4.0 branch onto main. Two adaptations were needed,
both from #44's dtype-promotion fix, which landed after this work was
written:

  - The wrappers now call `_promote()` before dispatching, so the serial
    fallback (nthreads <= 1) does not bypass it.
  - The kernels accumulate in `values.dtype` rather than a hardcoded
    float64, and reduce the thread partials into an explicitly-typed
    output. `partial.sum(axis=0)` widens a narrow dtype (uint16 -> uint64),
    which would have made the result dtype depend on the thread count the
    machine happened to pick.

Verified that `uint16 @ uint16` still wraps exactly as numpy and scipy do,
and that the mixed `uint16 @ float64` case matches numpy to 3.7e-12
relative -- tighter than scipy's own agreement with numpy on the same input.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019ZwuJMcTRUacxqARwjMngE
aarmey pushed a commit that referenced this pull request Sep 18, 2026
`_ops._major_matvec`/`_major_matmat` -- the scatter direction, reached by
`VCSC @ B` and `B @ VCSR` -- ran single-threaded with no strategy at all,
losing to scipy by up to 4x:

    VCSC @ x            8.7 ms   vs scipy   6.7 ms   1.30x
    VCSC @ B  (k=8)    20.1 ms   vs scipy  21.0 ms   0.96x
    x @ VCSR           20.5 ms   vs scipy   5.1 ms   3.99x
    B @ VCSR  (p=8)    28.5 ms   vs scipy  14.6 ms   1.96x

They cannot be parallelized over the major axis directly, since two major
slices can collide on the same output index.

Regrouping a chunk into the opposite format and running an aligned kernel --
the strategy `_vcs_matmul` uses for the normalized view -- was tried first and
is much worse here. That path caches its transposed copy and amortizes it
across an iterative algorithm's many products; a bare `A @ B` pays the regroup
once per call, which turned the 8.7 ms product into 700 ms. Reverted.

Thread-local accumulators instead -- the shape `minor_sums`/`minor_extrema`
already use -- reduced across threads afterwards. The thread count is the
whole design problem: the scatter is `nnz * width` work split across threads
while the reduction is `nthreads * n_minor * width`, so more threads is not
better. Measured on 6M nonzeros over 60k x 2k, letting the existing 64 MiB
accumulator budget pick 48 threads for a width-8 product ran it in 56.6 ms,
*slower than the serial kernel's* 23.3 ms; 4 threads and 15 MB ran it in
11.6 ms.

`scatter_threads()` takes the smaller of two bounds. Setting the derivative of
scatter-plus-reduction to zero puts the optimum at `sqrt(nnz / n_minor)`,
which is 10 for that array against a measured best of 16/8/4 at widths 1/4/8 --
right in magnitude, but blind to width. A 16 MiB byte cap supplies the missing
width-dependence, admitting fewer threads exactly as the accumulator grows.
Together they track the measured optimum across widths:

    VCSC @ x            2.4 ms   vs scipy   6.7 ms   0.35x   (was 1.30x)
    VCSC @ B  (k=8)    12.0 ms   vs scipy  21.6 ms   0.56x   (was 0.96x)
    x @ VCSR            1.8 ms   vs scipy   5.2 ms   0.36x   (was 3.99x)
    B @ VCSR  (p=8)     5.2 ms   vs scipy  14.3 ms   0.36x   (was 1.96x)

Peak allocation stays bounded by the cap rather than by `nnz`: 5.3 MB at
width 1, 19.2 MB at width 8, 23.0 MB at width 16. Single-thread cases fall
back to the serial kernels rather than pay an allocation and a reduction pass
for one partial.

Three benchmark cases now cover this direction; the existing
`matvec_vs_scipy`/`matmat_vs_scipy` only ever ran VCSR aligned.

Rebased from the pre-0.4.0 branch onto main. Two adaptations were needed,
both from #44's dtype-promotion fix, which landed after this work was
written:

  - The wrappers now call `_promote()` before dispatching, so the serial
    fallback (nthreads <= 1) does not bypass it.
  - The kernels accumulate in `values.dtype` rather than a hardcoded
    float64, and reduce the thread partials into an explicitly-typed
    output. `partial.sum(axis=0)` widens a narrow dtype (uint16 -> uint64),
    which would have made the result dtype depend on the thread count the
    machine happened to pick.

Verified that `uint16 @ uint16` still wraps exactly as numpy and scipy do,
and that the mixed `uint16 @ float64` case matches numpy to 3.7e-12
relative -- tighter than scipy's own agreement with numpy on the same input.


Claude-Session: https://claude.ai/code/session_019ZwuJMcTRUacxqARwjMngE

Co-authored-by: Claude Opus 5 <noreply@anthropic.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.

Vector/matrix product (@) silently overflows for narrow value dtypes (e.g. uint16), unlike sum()

1 participant