From a92dd479b8771067dee9526ec1310552a351a87a Mon Sep 17 00:00:00 2001 From: Aaron Meyer Date: Sat, 21 Nov 2026 17:41:40 -0800 Subject: [PATCH 1/4] CPU matmul kernels: balance work by nonzeros and evaluate g once per value group Two changes to the normalized-view products in _vcs_matmul.py. Balance: every kernel gave each thread the same number of major slices. Real counts have heavy-tailed slice lengths (on 250,000 Lupus cells, 28% of the nonzeros sit in 1% of the genes, and the long genes are contiguous), so for B @ VCSC the busiest thread held up to 20x the mean and the product could not use more than about 2.4 of 48 threads. The aligned kernels now loop over nonzero-balanced chunks (four per thread) and the misaligned ones give each private accumulator a nonzero-balanced range of slices (_nnz_balanced_bounds, one serial pass over the pointers). Hoist: when the recipe has no per-gene scaling, g(v / row_scale / gene_scale) depends only on the row and the value, so VCSR X @ B and B @ X evaluate it once per value group and not once per stored entry. VCSC cannot, since the argument changes with the row of every index. Results are unchanged: the hoisted expression is the one evaluated before, with gene_scale == 1. Tests cover skewed matrices for every recipe, direction and thread count, and the chunking helper. --- src/vsparse/_vcs_matmul.py | 173 +++++++++++++++++++++++++---------- tests/test_matmul_balance.py | 94 +++++++++++++++++++ 2 files changed, 221 insertions(+), 46 deletions(-) create mode 100644 tests/test_matmul_balance.py diff --git a/src/vsparse/_vcs_matmul.py b/src/vsparse/_vcs_matmul.py index f00043b..bf542b7 100644 --- a/src/vsparse/_vcs_matmul.py +++ b/src/vsparse/_vcs_matmul.py @@ -61,6 +61,43 @@ if TYPE_CHECKING: from vsparse._vcs_norm import _VCSNormalizedBase +#: The major-aligned kernels cut the major axis into this many nonzero-balanced chunks per +#: thread. More than one lets a thread that finishes early take up the remaining work only if +#: the schedule is dynamic, which Numba's is not; the extra chunks cost nothing, and they keep +#: each chunk small enough that the rounding of a cut to a slice boundary cannot unbalance it. +_CHUNKS_PER_THREAD = 4 + + +@numba.njit(cache=True) +def _nnz_balanced_bounds(major_ptr, value_ptr, nchunks): + """Cut the major slices into ``nchunks`` contiguous ranges of about equal nonzeros. + + Returns ``bounds`` of length ``nchunks + 1`` with ``bounds[0] == 0`` and + ``bounds[-1] == n_major``; chunk ``c`` is slices ``bounds[c]:bounds[c + 1]`` + (possibly empty). Real count matrices have heavy-tailed slice lengths (28% of + Lupus's nonzeros sit in 1% of its genes, and the longest gene is in every cell), + and the long slices cluster along the axis, so an equal-count split leaves the + thread that owns them with many times the mean work. One serial pass over the + ``n_major + 1`` pointers; the cut falls at the first slice end that reaches each + target, so no chunk is more than one slice over its share. + """ + n_major = major_ptr.shape[0] - 1 + bounds = np.empty(nchunks + 1, dtype=np.int64) + bounds[0] = 0 + base = value_ptr[major_ptr[0]] + total = value_ptr[major_ptr[n_major]] - base + c = 1 + for j in range(n_major): + done = value_ptr[major_ptr[j + 1]] - base + while c < nchunks and done * nchunks >= c * total: + bounds[c] = j + 1 + c += 1 + while c <= nchunks: + bounds[c] = n_major + c += 1 + return bounds + + __all__ = ["dense_at_normalized", "normalized_at_dense"] @@ -69,21 +106,42 @@ @numba.njit(cache=True, parallel=True) def _vcsr_matmul_delta( - major_ptr, values, value_ptr, indices, row_scale, gene_scale, col_post_scale, g_code, B, out + major_ptr, + values, + value_ptr, + indices, + row_scale, + gene_scale, + col_post_scale, + g_code, + hoist, + bounds, + B, + out, ): - n_major = major_ptr.shape[0] - 1 + """``Delta @ B`` for a VCSR array, parallel over nonzero-balanced chunks of rows. + + ``hoist`` is true when ``gene_scale`` is all ones (the recipe has no per-gene + scaling): then ``g(v / rs / gs)`` is the same for every index of a value group, and + is evaluated once per group instead of once per stored entry. + """ k = B.shape[1] - for i in numba.prange(n_major): # ty: ignore[not-iterable] - rs = row_scale[i] - for u in range(major_ptr[i], major_ptr[i + 1]): - v = values[u] - for kk in range(value_ptr[u], value_ptr[u + 1]): - col = indices[kk] - gs = gene_scale[col] - if gs > 0.0: - delta = col_post_scale[col] * _g(v / rs / gs, g_code) - for c in range(k): - out[i, c] += delta * B[col, c] + for t in numba.prange(bounds.shape[0] - 1): # ty: ignore[not-iterable] + for i in range(bounds[t], bounds[t + 1]): + rs = row_scale[i] + orow = out[i] + for u in range(major_ptr[i], major_ptr[i + 1]): + v = values[u] + gv = _g(v / rs, g_code) if hoist else 0.0 + for kk in range(value_ptr[u], value_ptr[u + 1]): + col = indices[kk] + gs = gene_scale[col] + if gs > 0.0: + g = gv if hoist else _g(v / rs / gs, g_code) + delta = col_post_scale[col] * g + brow = B[col] + for c in range(k): + orow[c] += delta * brow[c] # -- major-aligned: VCSC, B @ self (out cols == major slices) --------------- @@ -102,24 +160,39 @@ def _vcsr_matmul_delta( @numba.njit(cache=True, parallel=True) def _vcsc_rmatmul_delta( - major_ptr, values, value_ptr, indices, row_scale, gene_scale, col_post_scale, g_code, Bt, out_t + major_ptr, + values, + value_ptr, + indices, + row_scale, + gene_scale, + col_post_scale, + g_code, + bounds, + Bt, + out_t, ): - n_major = major_ptr.shape[0] - 1 + """``B @ Delta`` for a VCSC array, parallel over nonzero-balanced chunks of columns. + + ``g`` cannot be hoisted out of the group here: the argument ``v / row_scale[row]`` + changes with the row of every index. + """ p = Bt.shape[1] - for j in numba.prange(n_major): # ty: ignore[not-iterable] - gs = gene_scale[j] - if gs == 0.0: - continue - s = col_post_scale[j] - acc = out_t[j] - for u in range(major_ptr[j], major_ptr[j + 1]): - v = values[u] - for kk in range(value_ptr[u], value_ptr[u + 1]): - row = indices[kk] - delta = s * _g(v / row_scale[row] / gs, g_code) - brow = Bt[row] - for c in range(p): - acc[c] += delta * brow[c] + for t in numba.prange(bounds.shape[0] - 1): # ty: ignore[not-iterable] + for j in range(bounds[t], bounds[t + 1]): + gs = gene_scale[j] + if gs == 0.0: + continue + s = col_post_scale[j] + acc = out_t[j] + for u in range(major_ptr[j], major_ptr[j + 1]): + v = values[u] + for kk in range(value_ptr[u], value_ptr[u + 1]): + row = indices[kk] + delta = s * _g(v / row_scale[row] / gs, g_code) + brow = Bt[row] + for c in range(p): + acc[c] += delta * brow[c] # -- misaligned direction: per-thread private accumulators, no regrouping ---- @@ -135,25 +208,23 @@ def _vcsc_matmul_delta_minor( gene_scale, col_post_scale, g_code, + bounds, B, - nthreads, n_rows, ): """``Delta @ B`` for a VCSC array (major=columns), walked directly (no VCSR regroup). ``B`` is ``(n_cols, k)``; returns ``(n_rows, k)``. Parallel-safe because each thread scatters into its own private ``(n_rows, k)`` accumulator - while owning a disjoint, contiguous range of columns. + while owning a disjoint, contiguous range of columns; ``bounds`` has one + range per thread, balanced by nonzeros. """ - n_major = major_ptr.shape[0] - 1 # n_cols + nthreads = bounds.shape[0] - 1 k = B.shape[1] - chunk = (n_major + nthreads - 1) // nthreads partial = np.zeros((nthreads, n_rows, k), dtype=np.float64) for t in numba.prange(nthreads): # ty: ignore[not-iterable] - start = t * chunk - stop = min(n_major, start + chunk) local = partial[t] - for j in range(start, stop): + for j in range(bounds[t], bounds[t + 1]): gs = gene_scale[j] if gs == 0.0: continue @@ -180,8 +251,9 @@ def _vcsr_rmatmul_delta_minor( gene_scale, col_post_scale, g_code, + hoist, + bounds, Bt, - nthreads, n_cols, ): """``B @ Delta`` for a VCSR array (major=rows), walked directly (no VCSC regroup). @@ -189,26 +261,26 @@ def _vcsr_rmatmul_delta_minor( ``Bt`` is ``(n_rows, p)`` (``B`` transposed); returns ``(n_cols, p)``. Parallel-safe because each thread scatters into its own private ``(n_cols, p)`` accumulator while owning a disjoint, contiguous range of - rows. + rows; ``bounds`` has one range per thread, balanced by nonzeros. ``hoist`` + is as for :func:`_vcsr_matmul_delta`. """ - n_major = major_ptr.shape[0] - 1 # n_rows + nthreads = bounds.shape[0] - 1 p = Bt.shape[1] - chunk = (n_major + nthreads - 1) // nthreads partial = np.zeros((nthreads, n_cols, p), dtype=np.float64) for t in numba.prange(nthreads): # ty: ignore[not-iterable] - start = t * chunk - stop = min(n_major, start + chunk) local = partial[t] - for i in range(start, stop): + for i in range(bounds[t], bounds[t + 1]): rs = row_scale[i] brow = Bt[i] for u in range(major_ptr[i], major_ptr[i + 1]): v = values[u] + gv = _g(v / rs, g_code) if hoist else 0.0 for kk in range(value_ptr[u], value_ptr[u + 1]): col = indices[kk] gs = gene_scale[col] if gs > 0.0: - delta = col_post_scale[col] * _g(v / rs / gs, g_code) + g = gv if hoist else _g(v / rs / gs, g_code) + delta = col_post_scale[col] * g acc = local[col] for c in range(p): acc[c] += delta * brow[c] @@ -228,6 +300,11 @@ def _prep_dense(other: Any, expect_rows: int) -> tuple[np.ndarray, bool]: return np.ascontiguousarray(B), squeeze +def _bounds(arr: Any, nchunks: int) -> np.ndarray: + """Nonzero-balanced chunk bounds over the major slices of ``arr`` (see :func:`_nnz_balanced_bounds`).""" + return _nnz_balanced_bounds(arr.major_ptr, arr.value_ptr, nchunks) + + def normalized_at_dense(nview: _VCSNormalizedBase, other: Any) -> np.ndarray: """``nview @ other`` -- normalized-view-on-the-left sparse-dense product.""" arr = nview._arr @@ -248,6 +325,8 @@ def normalized_at_dense(nview: _VCSNormalizedBase, other: Any) -> np.ndarray: nview.gene_scale, nview.col_post_scale, g_code, + not nview.recipe.gene_scale, + _bounds(arr, _CHUNKS_PER_THREAD * numba.get_num_threads()), B, out, ) @@ -263,8 +342,8 @@ def normalized_at_dense(nview: _VCSNormalizedBase, other: Any) -> np.ndarray: nview.gene_scale, nview.col_post_scale, g_code, + _bounds(arr, nthreads), B, - nthreads, arr.shape[0], ) @@ -301,6 +380,7 @@ def dense_at_normalized(nview: _VCSNormalizedBase, other: Any) -> np.ndarray: nview.gene_scale, nview.col_post_scale, g_code, + _bounds(arr, _CHUNKS_PER_THREAD * numba.get_num_threads()), Bt, out_t, ) @@ -316,8 +396,9 @@ def dense_at_normalized(nview: _VCSNormalizedBase, other: Any) -> np.ndarray: nview.gene_scale, nview.col_post_scale, g_code, + not nview.recipe.gene_scale, + _bounds(arr, nthreads), Bt, - nthreads, arr.shape[1], ) diff --git a/tests/test_matmul_balance.py b/tests/test_matmul_balance.py new file mode 100644 index 0000000..42c45bd --- /dev/null +++ b/tests/test_matmul_balance.py @@ -0,0 +1,94 @@ +"""The CPU matmul kernels split work by nonzeros and hoist the transform out of value groups. + +Both are internal to the kernels, so the tests check what they must preserve: the products on matrices with +heavy-tailed slice lengths, for every recipe, direction and thread count, and the chunking helper itself. +""" + +from __future__ import annotations + +from itertools import pairwise + +import numba +import numpy as np +import pytest +import scipy.sparse as sp + +from vsparse import RECIPES, VCSCArray, VCSRArray +from vsparse._vcs_matmul import _nnz_balanced_bounds + + +def _skewed_counts(n_rows: int = 300, n_cols: int = 80, seed: int = 0) -> np.ndarray: + """Integer counts with a few genes in nearly every cell and long runs of rare ones, placed at the end. + + The long columns are contiguous, so an equal-count split of the columns gives one chunk most of the work. + """ + rng = np.random.default_rng(seed) + p = np.concatenate([np.full(n_cols // 8, 0.9), np.full(n_cols - n_cols // 8, 0.03)])[::-1] + dense = rng.geometric(0.5, size=(n_rows, n_cols)) * (rng.random((n_rows, n_cols)) < p) + dense[:, 0] = 1 # every cell has at least one count + return dense.astype(np.float64) + + +def _reference(dense: np.ndarray, recipe: str) -> np.ndarray: + """The normalized matrix from the view itself, densified; the products below test only the kernels.""" + return VCSRArray.from_scipy(sp.csr_array(dense)).normalized(recipe).toarray() + + +@pytest.mark.parametrize("vcls", [VCSRArray, VCSCArray]) +@pytest.mark.parametrize("recipe", sorted(RECIPES)) +@pytest.mark.parametrize("threads", [1, 3, 8]) +def test_products_match_dense_on_skewed_counts(vcls, recipe, threads): + dense = _skewed_counts() + arr = sp.csr_array(dense) if vcls is VCSRArray else sp.csc_array(dense) + nv = vcls.from_scipy(arr).normalized(recipe) + ref = _reference(dense, recipe) + rng = np.random.default_rng(1) + B, L = rng.normal(size=(dense.shape[1], 5)), rng.normal(size=(4, dense.shape[0])) + previous = numba.get_num_threads() + numba.set_num_threads(threads) + try: + np.testing.assert_allclose(nv @ B, ref @ B, atol=1e-9) + np.testing.assert_allclose(L @ nv, L @ ref, atol=1e-9) + np.testing.assert_allclose(nv @ B[:, 0], ref @ B[:, 0], atol=1e-9) + np.testing.assert_allclose(L[0] @ nv, L[0] @ ref, atol=1e-9) + finally: + numba.set_num_threads(previous) + + +@pytest.mark.parametrize("vcls", [VCSRArray, VCSCArray]) +@pytest.mark.parametrize("nchunks", [1, 2, 7, 64, 1000]) +def test_bounds_cover_every_slice_and_balance_the_nonzeros(vcls, nchunks): + dense = _skewed_counts(n_rows=200, n_cols=120) + arr = vcls.from_scipy(sp.csr_array(dense) if vcls is VCSRArray else sp.csc_array(dense)) + bounds = _nnz_balanced_bounds(arr.major_ptr, arr.value_ptr, nchunks) + assert bounds.shape == (nchunks + 1,) + assert bounds[0] == 0 and bounds[-1] == arr.n_major + assert np.all(np.diff(bounds) >= 0) + per_slice = np.diff(arr.value_ptr[arr.major_ptr]) + held = ( + np.add.reduceat(per_slice, bounds[:-1].clip(max=arr.n_major - 1)) + if arr.n_major + else np.zeros(0) + ) + held = np.where(np.diff(bounds) > 0, held, 0) + assert held.sum() == per_slice.sum() + # No chunk exceeds its share by more than the longest slice (a cut lands on a slice boundary). + assert held.max() <= per_slice.sum() / nchunks + per_slice.max() + + +def test_bounds_of_an_empty_array(): + major_ptr = np.zeros(4, dtype=np.int64) + bounds = _nnz_balanced_bounds(major_ptr, np.zeros(1, dtype=np.int64), 5) + assert bounds[0] == 0 and bounds[-1] == 3 and np.all(np.diff(bounds) >= 0) + + +def test_equal_count_split_would_be_unbalanced_here(): + """Guards the premise: on the skewed matrix an equal-count split of the columns is badly unbalanced.""" + dense = _skewed_counts(n_rows=400, n_cols=160) + per_col = (dense != 0).sum(axis=0) + equal = [c.sum() for c in np.array_split(per_col, 8)] + assert max(equal) > 2 * per_col.sum() / 8 + arr = VCSCArray.from_scipy(sp.csc_array(dense)) + bounds = _nnz_balanced_bounds(arr.major_ptr, arr.value_ptr, 8) + balanced = [per_col[a:b].sum() for a, b in pairwise(bounds)] + assert max(balanced) < max(equal) From dd967363660d6dee0034f1600d1c6733ca9a1c21 Mon Sep 17 00:00:00 2001 From: Aaron Meyer Date: Sun, 22 Nov 2026 09:04:08 -0800 Subject: [PATCH 2/4] Clamp thread count in matmul balance test to numba's maximum numba.set_num_threads raises when asked for more threads than the process launched with, which broke the threads=8 cases on 4-thread CI runners. --- tests/test_matmul_balance.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_matmul_balance.py b/tests/test_matmul_balance.py index 42c45bd..ea42d77 100644 --- a/tests/test_matmul_balance.py +++ b/tests/test_matmul_balance.py @@ -45,7 +45,8 @@ def test_products_match_dense_on_skewed_counts(vcls, recipe, threads): rng = np.random.default_rng(1) B, L = rng.normal(size=(dense.shape[1], 5)), rng.normal(size=(4, dense.shape[0])) previous = numba.get_num_threads() - numba.set_num_threads(threads) + # numba refuses more threads than the machine launched with (4 on CI runners). + numba.set_num_threads(min(threads, numba.config.NUMBA_NUM_THREADS)) try: np.testing.assert_allclose(nv @ B, ref @ B, atol=1e-9) np.testing.assert_allclose(L @ nv, L @ ref, atol=1e-9) From edb536e5534aab90eafe468c1abae48ca24df6eb Mon Sep 17 00:00:00 2001 From: Aaron Meyer Date: Sun, 22 Nov 2026 09:05:01 -0800 Subject: [PATCH 3/4] Use numba.get_num_threads() as the thread cap in matmul balance test numba.config.NUMBA_NUM_THREADS is not visible to ty. --- tests/test_matmul_balance.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_matmul_balance.py b/tests/test_matmul_balance.py index ea42d77..a8a0cc4 100644 --- a/tests/test_matmul_balance.py +++ b/tests/test_matmul_balance.py @@ -45,8 +45,8 @@ def test_products_match_dense_on_skewed_counts(vcls, recipe, threads): rng = np.random.default_rng(1) B, L = rng.normal(size=(dense.shape[1], 5)), rng.normal(size=(4, dense.shape[0])) previous = numba.get_num_threads() - # numba refuses more threads than the machine launched with (4 on CI runners). - numba.set_num_threads(min(threads, numba.config.NUMBA_NUM_THREADS)) + # numba refuses more threads than it launched with (4 on CI runners); other tests restore the default. + numba.set_num_threads(min(threads, previous)) try: np.testing.assert_allclose(nv @ B, ref @ B, atol=1e-9) np.testing.assert_allclose(L @ nv, L @ ref, atol=1e-9) From 29c7c0a68f8c9730501bc3d2e373fc2a6c1c172c Mon Sep 17 00:00:00 2001 From: Aaron Meyer Date: Sun, 22 Nov 2026 09:07:55 -0800 Subject: [PATCH 4/4] CUDA CI: use the self-hosted runner's local uv cache instead of the GitHub cache --- .github/workflows/ci.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3057442..bdfcc41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -109,7 +109,10 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@v10.0.1 with: - enable-cache: true + # Self-hosted: keep uv's cache on the runner's own disk (the default + # ~/.cache/uv) instead of round-tripping GBs of CUDA wheels through + # GitHub's cache service on every run. + enable-cache: false python-version: "3.12" # Informational, and deliberately non-fatal: on a runner with no GPU at