vsparse 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vsparse
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration
5
5
  Keywords: anndata,single-cell,sparse,compression
6
6
  Author: Aaron Meyer
@@ -47,7 +47,15 @@ matrices, e.g. single-cell RNA-seq counts.
47
47
 
48
48
  ## Install
49
49
 
50
- Install from source or via package manager:
50
+ Install from PyPI:
51
+
52
+ ```sh
53
+ pip install vsparse
54
+ # or with uv
55
+ uv add vsparse
56
+ ```
57
+
58
+ From source:
51
59
 
52
60
  ```sh
53
61
  pip install git+https://github.com/meyer-lab/vsparse.git
@@ -17,7 +17,15 @@ matrices, e.g. single-cell RNA-seq counts.
17
17
 
18
18
  ## Install
19
19
 
20
- Install from source or via package manager:
20
+ Install from PyPI:
21
+
22
+ ```sh
23
+ pip install vsparse
24
+ # or with uv
25
+ uv add vsparse
26
+ ```
27
+
28
+ From source:
21
29
 
22
30
  ```sh
23
31
  pip install git+https://github.com/meyer-lab/vsparse.git
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vsparse"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vsparse"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -245,10 +245,15 @@ class VCSCAnnData(ad.AnnData):
245
245
  g: Any,
246
246
  *,
247
247
  format: str = "vcsc",
248
+ convert_strings_to_categoricals: bool = True,
248
249
  dataset_kwargs: Mapping[str, Any] = MappingProxyType({}),
249
250
  ) -> None:
250
251
  if format not in _STORE_FORMATS:
251
252
  raise ValueError(f"format must be one of {_STORE_FORMATS}, got {format!r}")
253
+ if convert_strings_to_categoricals:
254
+ # Writing field-by-field skips what anndata's own writers do here,
255
+ # leaving low-cardinality columns as one string per row.
256
+ self.strings_to_categoricals()
252
257
  write_array = ad.io.write_elem if format == "vcsc" else _io.write_ivcs_elem
253
258
  if self._vcs_X is not None:
254
259
  write_array(g, "X", self._vcs_X, dataset_kwargs=dataset_kwargs)
@@ -277,6 +282,7 @@ class VCSCAnnData(ad.AnnData):
277
282
  filename: str | PathLike[str],
278
283
  *,
279
284
  format: str = "vcsc",
285
+ convert_strings_to_categoricals: bool = True,
280
286
  dataset_kwargs: Mapping[str, Any] | None = None,
281
287
  **_kwargs: Any,
282
288
  ) -> None:
@@ -291,6 +297,10 @@ class VCSCAnnData(ad.AnnData):
291
297
  the cost of extra work on write/read. Either way, ``X``/``raw_X``
292
298
  come back from :meth:`read_h5ad` as ordinary VCSCArray/VCSRArray
293
299
  objects -- ``"ivcsc"`` is purely an on-disk storage format.
300
+ convert_strings_to_categoricals
301
+ Convert ``obs``/``var`` string columns to categorical in place
302
+ before writing, as ``anndata``'s own writers do. Only columns
303
+ with fewer categories than rows are converted.
294
304
  dataset_kwargs
295
305
  Passed to ``h5py.Group.create_dataset`` for every array written.
296
306
  Defaults to Blosc2+LZ4 compression; pass ``{}`` to store
@@ -305,7 +315,12 @@ class VCSCAnnData(ad.AnnData):
305
315
  _compression.numeric_only_compression("h5"),
306
316
  h5py.File(filename, "w") as f,
307
317
  ):
308
- self._write_group(f, format=format, dataset_kwargs=dataset_kwargs)
318
+ self._write_group(
319
+ f,
320
+ format=format,
321
+ convert_strings_to_categoricals=convert_strings_to_categoricals,
322
+ dataset_kwargs=dataset_kwargs,
323
+ )
309
324
 
310
325
  @classmethod
311
326
  def read_h5ad(cls, filename: str | PathLike[str]) -> VCSCAnnData:
@@ -320,14 +335,15 @@ class VCSCAnnData(ad.AnnData):
320
335
  store: Any,
321
336
  *,
322
337
  format: str = "vcsc",
338
+ convert_strings_to_categoricals: bool = True,
323
339
  dataset_kwargs: Mapping[str, Any] | None = None,
324
340
  **_kwargs: Any,
325
341
  ) -> None:
326
342
  """Write to a zarr store. Read back with :meth:`read_zarr`.
327
343
 
328
- See :meth:`write_h5ad` for ``format``/``dataset_kwargs`` (including the
329
- numeric-only compression behavior); the default compression here is
330
- Blosc+LZ4 via ``numcodecs``.
344
+ See :meth:`write_h5ad` for ``format``/``convert_strings_to_categoricals``/
345
+ ``dataset_kwargs`` (including the numeric-only compression behavior);
346
+ the default compression here is Blosc+LZ4 via ``numcodecs``.
331
347
  """
332
348
  import zarr
333
349
 
@@ -335,7 +351,12 @@ class VCSCAnnData(ad.AnnData):
335
351
  dataset_kwargs = _compression.zarr_dataset_kwargs()
336
352
  with _compression.numeric_only_compression("zarr"):
337
353
  f = zarr.open_group(store, mode="w")
338
- self._write_group(f, format=format, dataset_kwargs=dataset_kwargs)
354
+ self._write_group(
355
+ f,
356
+ format=format,
357
+ convert_strings_to_categoricals=convert_strings_to_categoricals,
358
+ dataset_kwargs=dataset_kwargs,
359
+ )
339
360
 
340
361
  @classmethod
341
362
  def read_zarr(cls, store: Any) -> VCSCAnnData:
@@ -20,6 +20,7 @@ import scipy.sparse as sp
20
20
  from vsparse import _construct, _ops
21
21
  from vsparse._indexutils import is_full_slice as _is_full_slice
22
22
  from vsparse._indexutils import normalize_major_idx as _normalize_major_idx
23
+ from vsparse._indexutils import smallest_index_dtype as _smallest_index_dtype
23
24
 
24
25
  __all__ = ["VCSCArray", "VCSRArray"]
25
26
 
@@ -67,6 +68,12 @@ class _VCSBase:
67
68
  if indices.shape[0] and (indices.min() < 0 or indices.max() >= n_minor):
68
69
  raise ValueError("indices out of bounds for the given shape")
69
70
 
71
+ # Narrow after the bounds check above, so an out-of-range index is
72
+ # rejected rather than silently truncated by the cast.
73
+ idx_dtype = _smallest_index_dtype(n_minor)
74
+ if idx_dtype.itemsize < indices.dtype.itemsize:
75
+ indices = indices.astype(idx_dtype, copy=False)
76
+
70
77
  self.shape = (int(shape[0]), int(shape[1]))
71
78
  self.major_ptr = major_ptr
72
79
  self.values = values
@@ -124,9 +131,9 @@ class _VCSBase:
124
131
  def from_scipy(cls, mat) -> _VCSBase:
125
132
  """Build from any scipy sparse array/matrix (converted internally)."""
126
133
  mat = mat.tocsc() if cls._format == "csc" else mat.tocsr()
127
- n_major, _n_minor = cls._swap(mat.shape)
134
+ n_major, n_minor = cls._swap(mat.shape)
128
135
  major_ptr, values, value_ptr, indices = _construct.compress(
129
- mat.indptr, mat.indices, mat.data, n_major
136
+ mat.indptr, mat.indices, mat.data, n_major, n_minor
130
137
  )
131
138
  return cls(mat.shape, major_ptr, values, value_ptr, indices)
132
139
 
@@ -220,10 +227,11 @@ class _VCSBase:
220
227
  return np.bincount(group_of_major, weights=weighted, minlength=self.n_major)
221
228
 
222
229
  def _minor_sums(self) -> np.ndarray:
223
- """Per-minor-index totals -- a scatter-add over every nonzero."""
224
- group_sizes = np.diff(self.value_ptr)
225
- expanded = np.repeat(self.values.astype(np.float64), group_sizes)
226
- return np.bincount(self.indices, weights=expanded, minlength=self.n_minor)
230
+ """A parallel scatter-add over every nonzero to get per-minor-index totals."""
231
+ return _ops.minor_sums(
232
+ self.values, self.value_ptr, self.indices, self.n_minor,
233
+ _ops.accumulator_threads(self.n_minor),
234
+ )
227
235
 
228
236
  def sum(self, axis: int | None = None) -> np.ndarray | float:
229
237
  """Sum of (structural) values along ``axis`` (0=rows, 1=columns), or overall if ``None``."""
@@ -245,8 +253,11 @@ class _VCSBase:
245
253
  )
246
254
 
247
255
  def _minor_nnz(self) -> np.ndarray:
248
- """Per-minor-index stored-element counts -- a scatter-add over every nonzero."""
249
- return np.bincount(self.indices, minlength=self.n_minor).astype(np.int64)
256
+ """A parallel scatter over every nonzero to get per-minor-index counts."""
257
+ return _ops.minor_counts(
258
+ self.value_ptr, self.indices, self.n_minor,
259
+ _ops.accumulator_threads(self.n_minor),
260
+ )
250
261
 
251
262
  def getnnz(self, axis: int | None = None) -> np.ndarray | int:
252
263
  """Count of stored elements along ``axis``, or overall if ``None``."""
@@ -291,11 +302,11 @@ class _VCSBase:
291
302
 
292
303
  def _minor_reduce(self, ufunc: np.ufunc, initial: Any) -> np.ndarray:
293
304
  """Per-minor-index max/min, accounting for implicit zeros in sparse slices."""
294
- group_sizes = np.diff(self.value_ptr)
295
- expanded = np.repeat(self.values, group_sizes)
296
- out = np.full(self.n_minor, initial, dtype=self.values.dtype)
297
- ufunc.at(out, self.indices, expanded)
298
- counts = np.bincount(self.indices, minlength=self.n_minor)
305
+ out, counts = _ops.minor_extrema(
306
+ self.values, self.value_ptr, self.indices, self.n_minor, initial, ufunc is np.maximum
307
+ )
308
+ # A minor index missing from some major slice has a structural zero
309
+ # competing in the reduction.
299
310
  not_dense = counts < self.n_major
300
311
  out[not_dense] = ufunc(out[not_dense], 0)
301
312
  return out
@@ -512,34 +523,60 @@ class _VCSBase:
512
523
  )
513
524
  return type(self)(new_shape, new_major_ptr, new_values, new_value_ptr, new_indices)
514
525
 
526
+ def _major_range(self, start: int, stop: int) -> _VCSBase:
527
+ """The contiguous major-slice range ``[start, stop)``, without copying values.
528
+
529
+ ``values``/``indices`` come back as views; only the two pointer
530
+ arrays are rebuilt, rebased to the new start.
531
+ """
532
+ u0, u1 = int(self.major_ptr[start]), int(self.major_ptr[stop])
533
+ k0, k1 = int(self.value_ptr[u0]), int(self.value_ptr[u1])
534
+ n_sel = stop - start
535
+ new_shape = (
536
+ (self.n_minor, n_sel) if self._format == "csc" else (n_sel, self.n_minor)
537
+ )
538
+ return type(self)(
539
+ new_shape,
540
+ self.major_ptr[start : stop + 1] - u0,
541
+ self.values[u0:u1],
542
+ self.value_ptr[u0 : u1 + 1] - k0,
543
+ self.indices[k0:k1],
544
+ )
545
+
515
546
  def _select_minor(self, key: Any) -> _VCSBase:
516
547
  """Select along the minor axis (rows for VCSC, columns for VCSR).
517
548
 
518
- Unlike :meth:`_select_major`, the kept elements aren't already
519
- contiguous per major slice, so this filters/remaps ``indices`` and
520
- drops any (major, unique-value) slot that no longer has any kept
521
- index, shrinking ``major_ptr``/``value_ptr`` accordingly.
549
+ A key may name the same index more than once, so this is a fan-out
550
+ rather than a remap and one stored element can appear in several
551
+ output positions.
522
552
  """
523
553
  idx = _normalize_major_idx(key, self.n_minor)
524
554
  n_minor_new = idx.shape[0]
525
555
 
526
- remap = np.full(self.n_minor, -1, dtype=np.int64)
527
- remap[idx] = np.arange(n_minor_new, dtype=np.int64)
556
+ # Output positions grouped by the original index they came from.
557
+ fanout = np.bincount(idx, minlength=self.n_minor)
558
+ offsets = np.zeros(self.n_minor + 1, dtype=np.int64)
559
+ np.cumsum(fanout, out=offsets[1:])
560
+ positions = np.argsort(idx, kind="stable").astype(np.int64, copy=False)
528
561
 
529
- keep = remap[self.indices] >= 0
530
- new_indices = remap[self.indices[keep]].astype(self.indices.dtype, copy=False)
562
+ slot_counts = _ops.minor_select_counts(self.value_ptr, self.indices, fanout)
563
+ kept_slots = np.flatnonzero(slot_counts)
531
564
 
532
- n_unique = self.values.shape[0]
533
- value_slot_of_index = np.repeat(np.arange(n_unique, dtype=np.int64), np.diff(self.value_ptr))
534
- kept_per_slot = np.bincount(value_slot_of_index[keep], minlength=n_unique)
535
- surviving = kept_per_slot > 0
565
+ new_values = self.values[kept_slots]
566
+ new_value_ptr = np.zeros(kept_slots.shape[0] + 1, dtype=np.int64)
567
+ np.cumsum(slot_counts[kept_slots], out=new_value_ptr[1:])
536
568
 
537
- new_values = self.values[surviving]
538
- new_value_ptr = np.zeros(int(surviving.sum()) + 1, dtype=np.int64)
539
- np.cumsum(kept_per_slot[surviving], out=new_value_ptr[1:])
569
+ # Keep the parent's index dtype, as every other structural op does.
570
+ new_indices = np.empty(int(new_value_ptr[-1]), dtype=self.indices.dtype)
571
+ _ops.minor_select_fill(
572
+ self.value_ptr, self.indices, offsets, positions,
573
+ kept_slots, new_value_ptr, new_indices,
574
+ )
540
575
 
541
- group_of_major = np.repeat(np.arange(self.n_major, dtype=np.int64), np.diff(self.major_ptr))
542
- major_counts = np.bincount(group_of_major[surviving], minlength=self.n_major)
576
+ # Slots keep their original order, so each major slice owns a
577
+ # contiguous run of them.
578
+ major_of_slot = np.searchsorted(self.major_ptr, kept_slots, side="right") - 1
579
+ major_counts = np.bincount(major_of_slot, minlength=self.n_major)
543
580
  new_major_ptr = np.zeros(self.n_major + 1, dtype=np.int64)
544
581
  np.cumsum(major_counts, out=new_major_ptr[1:])
545
582
 
@@ -11,11 +11,17 @@ categoricals (category labels, ``obs``/``var`` string columns, the
11
11
  ``_index``). At least some HDF5 filter-plugin builds (seen in this
12
12
  environment: h5py 3.16 / HDF5 2.0.0 / hdf5plugin's Blosc2) segfault
13
13
  (``SIGFPE``) when the Blosc2 filter is applied to a variable-length-string
14
- dataset -- and there's no benefit to compressing already-tiny label arrays
15
- anyway. :func:`numeric_only_compression` patches the relevant
14
+ dataset. :func:`numeric_only_compression` patches the relevant
16
15
  ``create_dataset``/``create_array`` calls for the duration of a write so
17
16
  string/object arrays always land uncompressed, regardless of what
18
17
  ``dataset_kwargs`` was passed in -- callers don't have to know about this.
18
+
19
+ Strings are left uncompressed rather than given a different codec: gzip and
20
+ lzf are safe on variable-length strings here, but the size problem is the
21
+ per-row string itself, not its compression. Encoding low-cardinality
22
+ columns as categoricals turns the per-row data numeric, which the existing
23
+ Blosc2 path then compresses -- see
24
+ :meth:`vsparse.VCSCAnnData.write_h5ad`'s ``convert_strings_to_categoricals``.
19
25
  """
20
26
 
21
27
  from __future__ import annotations
@@ -27,6 +27,8 @@ from __future__ import annotations
27
27
  import numba
28
28
  import numpy as np
29
29
 
30
+ from vsparse._indexutils import smallest_index_dtype
31
+
30
32
  __all__ = ["compress", "decompress", "transpose_major"]
31
33
 
32
34
 
@@ -108,14 +110,21 @@ def compress(
108
110
  minor_indices: np.ndarray,
109
111
  data: np.ndarray,
110
112
  n_major: int,
113
+ n_minor: int | None = None,
111
114
  ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
112
115
  """Build the VCS layout from a standard compressed-sparse layout.
113
116
 
114
117
  Parameters mirror scipy's ``indptr``/``indices``/``data`` for either a
115
118
  CSC (major axis = columns) or CSR (major axis = rows) matrix.
119
+
120
+ ``n_minor`` picks the stored ``indices`` dtype; left at ``None`` the
121
+ input's dtype is preserved.
116
122
  """
117
123
  major_ptr = np.ascontiguousarray(major_ptr, dtype=np.int64)
118
- minor_indices = np.ascontiguousarray(minor_indices)
124
+ idx_dtype = None if n_minor is None else smallest_index_dtype(n_minor)
125
+ if idx_dtype is not None and idx_dtype.itemsize > minor_indices.dtype.itemsize:
126
+ idx_dtype = None # never widen a caller's already-narrower indices
127
+ minor_indices = np.ascontiguousarray(minor_indices, dtype=idx_dtype)
119
128
  data = np.ascontiguousarray(data)
120
129
  return _compress(major_ptr, minor_indices, data, n_major)
121
130
 
@@ -188,7 +197,7 @@ def transpose_major(
188
197
  value_ptr_out = np.concatenate([group_starts, [nnz]]).astype(np.int64)
189
198
  major_ptr_out = np.searchsorted(sorted_major[group_starts], np.arange(n_minor + 1)).astype(np.int64)
190
199
 
191
- minor_dtype = np.int32 if n_major <= np.iinfo(np.int32).max else np.int64
192
- indices_out = sorted_minor.astype(minor_dtype, copy=False)
200
+ # The output's minor axis is the input's major axis, so that's the bound.
201
+ indices_out = sorted_minor.astype(smallest_index_dtype(n_major), copy=False)
193
202
 
194
203
  return major_ptr_out, values_out, value_ptr_out, indices_out
@@ -6,7 +6,14 @@ from typing import Any
6
6
 
7
7
  import numpy as np
8
8
 
9
- __all__ = ["is_full_slice", "normalize_major_idx"]
9
+ __all__ = ["is_full_slice", "normalize_major_idx", "smallest_index_dtype"]
10
+
11
+ _INT32_MAX = np.iinfo(np.int32).max
12
+
13
+
14
+ def smallest_index_dtype(n: int) -> np.dtype:
15
+ """Narrowest signed integer dtype that can address an axis of length ``n``."""
16
+ return np.dtype(np.int32) if n <= _INT32_MAX else np.dtype(np.int64)
10
17
 
11
18
 
12
19
  def is_full_slice(key: Any) -> bool:
@@ -25,6 +25,7 @@ import zarr
25
25
 
26
26
  from vsparse import _ivcsc
27
27
  from vsparse._base import VCSCArray, VCSRArray, _VCSBase
28
+ from vsparse._indexutils import smallest_index_dtype
28
29
 
29
30
  if TYPE_CHECKING:
30
31
  from collections.abc import Mapping
@@ -96,7 +97,12 @@ def write_ivcs_elem(
96
97
  """
97
98
  g = f.require_group(k)
98
99
  g.attrs["shape"] = v.shape
99
- g.attrs["indices_dtype"] = np.dtype(v.indices.dtype).name
100
+ # Record the narrowest dtype that can address the minor axis rather than
101
+ # whatever the in-memory array happens to carry.
102
+ in_memory = v.indices.dtype
103
+ narrowest = smallest_index_dtype(v.n_minor)
104
+ stored_dtype = narrowest if narrowest.itemsize < in_memory.itemsize else in_memory
105
+ g.attrs["indices_dtype"] = stored_dtype.name
100
106
  for name in ("major_ptr", "values", "value_ptr"):
101
107
  ad.io.write_elem(g, name, getattr(v, name), dataset_kwargs=dataset_kwargs)
102
108
  packed = _ivcsc.pack_indices(v.value_ptr, v.indices)
@@ -9,6 +9,10 @@ value, so a real materialization is an ``n_rows * n_cols`` dense array; the
9
9
  whole point of a "view" here is to avoid paying for that until (and unless)
10
10
  the caller actually asks for it.
11
11
 
12
+ Statistics are computed once, at construction, over the whole wrapped
13
+ array. Indexing a view windows that matrix and keeps those statistics;
14
+ :meth:`~NormalizedViewBase.select` renormalizes a subset on its own terms.
15
+
12
16
  What's precomputed, once, at construction:
13
17
 
14
18
  - ``row_scale``: per-row (cell) total raw counts, scaled to a median of 1 --
@@ -252,16 +256,29 @@ class NormalizedViewBase:
252
256
  )
253
257
  return out
254
258
 
259
+ # -- selection ---------------------------------------------------------------
260
+
261
+ def select(self, rows: Any = slice(None), cols: Any = slice(None)) -> Any:
262
+ """A normalized view of the selected sub-array, with statistics recomputed for it.
263
+
264
+ Returns a view, not a dense array, so it still composes with
265
+ ``@``/:meth:`toarray`.
266
+ """
267
+ # A column selection re-derives read depth from only the selected
268
+ # columns, which is rarely what a caller wants; select genes first
269
+ # and normalize after if it matters.
270
+ sub: Any = self._arr[_prep_key(rows), _prep_key(cols)]
271
+ if not isinstance(sub, type(self._arr)):
272
+ sub = type(self._arr).from_scipy(sub)
273
+ return type(self)(sub)
274
+
255
275
  # -- on-the-fly elementwise access ------------------------------------------
256
276
 
257
277
  def __getitem__(self, key: Any) -> np.ndarray:
258
- """Compute just the requested sub-block, on the fly, from the raw data.
278
+ """``toarray()[key]``, computed on the fly without materializing the full matrix.
259
279
 
260
- Only the raw counts for the requested rows/columns are ever
261
- decompressed (via the underlying array's own indexing, which stays
262
- compact for a major-axis-only slice); the transform/centering
263
- formula is then applied to that small block directly, using the
264
- precomputed per-row/per-column statistics -- never the full matrix.
280
+ Applies this view's statistics, so it is not the same as normalizing
281
+ the selected sub-matrix; use :meth:`select` for that.
265
282
  """
266
283
  if isinstance(key, tuple):
267
284
  if len(key) != 2:
@@ -0,0 +1,230 @@
1
+ """Numba-accelerated numerical kernels on the VCS layout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numba
6
+ import numpy as np
7
+
8
+ __all__ = [
9
+ "accumulator_threads",
10
+ "major_matmat",
11
+ "major_matvec",
12
+ "minor_counts",
13
+ "minor_extrema",
14
+ "minor_matmat",
15
+ "minor_matvec",
16
+ "minor_select_counts",
17
+ "minor_select_fill",
18
+ "minor_sums",
19
+ ]
20
+
21
+ # Thread-local accumulators for the minor-axis scatters below cost
22
+ # ``nthreads * n_minor * bytes_per_element``. The thread count is capped to
23
+ # keep that block under this budget.
24
+ _ACCUMULATOR_BUDGET_BYTES = 64 << 20 # 64 MiB
25
+
26
+
27
+ def accumulator_threads(n_minor: int, bytes_per_element: int = 8) -> int:
28
+ """Threads to run a minor-axis scatter with, capped by accumulator size."""
29
+ if n_minor <= 0:
30
+ return 1
31
+ affordable = max(1, _ACCUMULATOR_BUDGET_BYTES // (n_minor * max(1, bytes_per_element)))
32
+ return int(min(numba.get_num_threads(), affordable))
33
+
34
+
35
+ @numba.njit(cache=True)
36
+ def _major_matvec(major_ptr, values, value_ptr, indices, x, n_major, n_minor):
37
+ """y = A @ x where A's major axis (columns for VCSC) has length n_major.
38
+
39
+ x has length n_major, output y has length n_minor.
40
+ """
41
+ y = np.zeros(n_minor, dtype=values.dtype)
42
+ for j in range(n_major):
43
+ xj = x[j]
44
+ if xj == 0:
45
+ continue
46
+ for u in range(major_ptr[j], major_ptr[j + 1]):
47
+ val = values[u] * xj
48
+ for k in range(value_ptr[u], value_ptr[u + 1]):
49
+ y[indices[k]] += val
50
+ return y
51
+
52
+
53
+ @numba.njit(cache=True, parallel=True)
54
+ def _minor_matvec(major_ptr, values, value_ptr, indices, x, n_major):
55
+ """y = x @ A, i.e. contract over the minor axis. x has length n_minor.
56
+
57
+ Output y has length n_major. Safe to parallelize over major slices since
58
+ each output element is written by exactly one iteration.
59
+ """
60
+ y = np.zeros(n_major, dtype=values.dtype)
61
+ for j in numba.prange(n_major): # ty: ignore[not-iterable]
62
+ s = 0.0
63
+ for u in range(major_ptr[j], major_ptr[j + 1]):
64
+ acc = 0.0
65
+ for k in range(value_ptr[u], value_ptr[u + 1]):
66
+ acc += x[indices[k]]
67
+ s += values[u] * acc
68
+ y[j] = s
69
+ return y
70
+
71
+
72
+ @numba.njit(cache=True)
73
+ def _major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor):
74
+ """Y = A @ B where A's major axis has length n_major, B is (n_major, k)."""
75
+ k = b.shape[1]
76
+ y = np.zeros((n_minor, k), dtype=values.dtype)
77
+ for j in range(n_major):
78
+ for u in range(major_ptr[j], major_ptr[j + 1]):
79
+ val = values[u]
80
+ for idx in range(value_ptr[u], value_ptr[u + 1]):
81
+ row = indices[idx]
82
+ for c in range(k):
83
+ y[row, c] += val * b[j, c]
84
+ return y
85
+
86
+
87
+ @numba.njit(cache=True, parallel=True)
88
+ def _minor_matmat(major_ptr, values, value_ptr, indices, b, n_major):
89
+ """Y = B @ A, i.e. B is (k, n_minor), contracting over the minor axis."""
90
+ k = b.shape[0]
91
+ y = np.zeros((k, n_major), dtype=values.dtype)
92
+ for j in numba.prange(n_major): # ty: ignore[not-iterable]
93
+ for u in range(major_ptr[j], major_ptr[j + 1]):
94
+ val = values[u]
95
+ for idx in range(value_ptr[u], value_ptr[u + 1]):
96
+ col = indices[idx]
97
+ for c in range(k):
98
+ y[c, j] += val * b[c, col]
99
+ return y
100
+
101
+
102
+ @numba.njit(cache=True, parallel=True)
103
+ def minor_sums(values, value_ptr, indices, n_minor, nthreads):
104
+ n_groups = values.shape[0]
105
+ chunk = (n_groups + nthreads - 1) // nthreads
106
+ partial = np.zeros((nthreads, n_minor), dtype=np.float64)
107
+ for t in numba.prange(nthreads): # ty: ignore[not-iterable]
108
+ start = t * chunk
109
+ end = min(n_groups, start + chunk)
110
+ local = partial[t]
111
+ for u in range(start, end):
112
+ v = np.float64(values[u])
113
+ for k in range(value_ptr[u], value_ptr[u + 1]):
114
+ local[indices[k]] += v
115
+ return partial.sum(axis=0)
116
+
117
+
118
+ @numba.njit(cache=True, parallel=True)
119
+ def _minor_extrema_kernel(values, value_ptr, indices, n_minor, nthreads, initial, is_max):
120
+ # The count comes along for free and tells the caller which minor indices
121
+ # have an implicit zero to fold in.
122
+ n_groups = values.shape[0]
123
+ chunk = (n_groups + nthreads - 1) // nthreads
124
+ part_val = np.full((nthreads, n_minor), initial, dtype=values.dtype)
125
+ part_cnt = np.zeros((nthreads, n_minor), dtype=np.int64)
126
+ for t in numba.prange(nthreads): # ty: ignore[not-iterable]
127
+ start = t * chunk
128
+ end = min(n_groups, start + chunk)
129
+ local_val = part_val[t]
130
+ local_cnt = part_cnt[t]
131
+ for u in range(start, end):
132
+ v = values[u]
133
+ for k in range(value_ptr[u], value_ptr[u + 1]):
134
+ idx = indices[k]
135
+ local_cnt[idx] += 1
136
+ if is_max:
137
+ if v > local_val[idx]:
138
+ local_val[idx] = v
139
+ else:
140
+ if v < local_val[idx]:
141
+ local_val[idx] = v
142
+ return part_val, part_cnt
143
+
144
+
145
+ def minor_extrema(values, value_ptr, indices, n_minor, initial, is_max):
146
+ """Extremum over the stored values, and the stored count, per minor index."""
147
+ nthreads = accumulator_threads(n_minor, values.dtype.itemsize + 8)
148
+ part_val, part_cnt = _minor_extrema_kernel(
149
+ values, value_ptr, indices, n_minor, nthreads, initial, is_max
150
+ )
151
+ extrema = part_val.max(axis=0) if is_max else part_val.min(axis=0)
152
+ return extrema, part_cnt.sum(axis=0)
153
+
154
+
155
+ @numba.njit(cache=True, parallel=True)
156
+ def minor_counts(value_ptr, indices, n_minor, nthreads):
157
+ n_groups = value_ptr.shape[0] - 1
158
+ chunk = (n_groups + nthreads - 1) // nthreads
159
+ partial = np.zeros((nthreads, n_minor), dtype=np.int64)
160
+ for t in numba.prange(nthreads): # ty: ignore[not-iterable]
161
+ start = t * chunk
162
+ end = min(n_groups, start + chunk)
163
+ local = partial[t]
164
+ for u in range(start, end):
165
+ for k in range(value_ptr[u], value_ptr[u + 1]):
166
+ local[indices[k]] += 1
167
+ return partial.sum(axis=0)
168
+
169
+
170
+
171
+
172
+ def major_matvec(major_ptr, values, value_ptr, indices, x, n_major, n_minor):
173
+ return _major_matvec(major_ptr, values, value_ptr, indices, np.asarray(x), n_major, n_minor)
174
+
175
+
176
+ def minor_matvec(major_ptr, values, value_ptr, indices, x, n_major):
177
+ return _minor_matvec(major_ptr, values, value_ptr, indices, np.asarray(x), n_major)
178
+
179
+
180
+ def major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor):
181
+ b = np.ascontiguousarray(b)
182
+ return _major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor)
183
+
184
+
185
+ def minor_matmat(major_ptr, values, value_ptr, indices, b, n_major):
186
+ b = np.ascontiguousarray(b)
187
+ return _minor_matmat(major_ptr, values, value_ptr, indices, b, n_major)
188
+
189
+
190
+ # -- minor-axis selection ----------------------------------------------------
191
+
192
+
193
+ @numba.njit(cache=True, parallel=True)
194
+ def _minor_select_counts(value_ptr, indices, fanout, out_counts):
195
+ # A selection may name one index several times, so each stored element
196
+ # contributes ``fanout`` output entries rather than one.
197
+ n_slots = value_ptr.shape[0] - 1
198
+ for u in numba.prange(n_slots): # ty: ignore[not-iterable]
199
+ c = 0
200
+ for k in range(value_ptr[u], value_ptr[u + 1]):
201
+ c += fanout[indices[k]]
202
+ out_counts[u] = c
203
+
204
+
205
+ @numba.njit(cache=True, parallel=True)
206
+ def _minor_select_fill(
207
+ value_ptr, indices, offsets, positions, kept_slots, new_value_ptr, out_indices
208
+ ):
209
+ for s in numba.prange(kept_slots.shape[0]): # ty: ignore[not-iterable]
210
+ u = kept_slots[s]
211
+ pos = new_value_ptr[s] # each slot fills a disjoint range
212
+ for k in range(value_ptr[u], value_ptr[u + 1]):
213
+ o = indices[k]
214
+ for j in range(offsets[o], offsets[o + 1]): # every destination of o
215
+ out_indices[pos] = positions[j]
216
+ pos += 1
217
+
218
+
219
+ def minor_select_counts(value_ptr, indices, fanout):
220
+ """Output element count per stored (major, value) slot."""
221
+ counts = np.empty(value_ptr.shape[0] - 1, dtype=np.int64)
222
+ _minor_select_counts(value_ptr, indices, fanout, counts)
223
+ return counts
224
+
225
+
226
+ def minor_select_fill(value_ptr, indices, offsets, positions, kept_slots, new_value_ptr, out_indices):
227
+ """Write the remapped minor indices for the surviving slots, in place."""
228
+ _minor_select_fill(
229
+ value_ptr, indices, offsets, positions, kept_slots, new_value_ptr, out_indices
230
+ )
@@ -61,6 +61,8 @@ from scipy.sparse import csr_array
61
61
 
62
62
  from vsparse import _ivcsc
63
63
  from vsparse._anndata_class import VCSCAnnData
64
+ from vsparse._indexutils import smallest_index_dtype
65
+ from vsparse._ops import accumulator_threads
64
66
 
65
67
  if TYPE_CHECKING:
66
68
  from os import PathLike
@@ -159,7 +161,7 @@ def _build_selected_rows(
159
161
  full_indptr = value_ptr[major_ptr]
160
162
  row_nnz = np.diff(full_indptr)[row_mask]
161
163
  nnz = int(row_nnz.sum())
162
- ptr_dtype = np.int64 if nnz > np.iinfo(np.int32).max else np.int32
164
+ ptr_dtype = smallest_index_dtype(nnz)
163
165
 
164
166
  indptr = np.zeros(row_nnz.shape[0] + 1, dtype=ptr_dtype)
165
167
  np.cumsum(row_nnz, out=indptr[1:])
@@ -256,18 +258,22 @@ def _filter_and_compact(
256
258
  gene_mask: np.ndarray,
257
259
  ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int]:
258
260
  kept_rows = np.nonzero(cell_mask)[0]
259
- gene_remap = (np.cumsum(gene_mask) - 1).astype(np.int32)
260
- gene_remap[~gene_mask] = -1
261
261
  n_kept_genes = int(gene_mask.sum())
262
+ gene_remap = (np.cumsum(gene_mask) - 1).astype(smallest_index_dtype(n_kept_genes))
263
+ gene_remap[~gene_mask] = -1
264
+
265
+ # ``new_indptr`` is indexed by nonzero count and needs int64 once nnz
266
+ # passes INT32_MAX; ``out_indices`` holds gene indices and never does.
267
+ ptr_dtype = smallest_index_dtype(int(indices.shape[0]))
268
+ col_dtype = smallest_index_dtype(n_kept_genes)
262
269
 
263
- idx_dtype = np.int64 if indices.shape[0] > np.iinfo(np.int32).max else np.int32
264
- counts = np.empty(kept_rows.shape[0], dtype=idx_dtype)
270
+ counts = np.empty(kept_rows.shape[0], dtype=ptr_dtype)
265
271
  _count_kept(row_indptr, indices, gene_mask, kept_rows, counts)
266
- new_indptr = np.zeros(kept_rows.shape[0] + 1, dtype=idx_dtype)
272
+ new_indptr = np.zeros(kept_rows.shape[0] + 1, dtype=ptr_dtype)
267
273
  np.cumsum(counts, out=new_indptr[1:])
268
274
 
269
275
  nnz_filtered = int(new_indptr[-1])
270
- out_indices = np.empty(nnz_filtered, dtype=idx_dtype)
276
+ out_indices = np.empty(nnz_filtered, dtype=col_dtype)
271
277
  out_data = np.empty(nnz_filtered, dtype=np.float32)
272
278
  _fill_kept(row_indptr, indices, data, gene_remap, kept_rows, new_indptr, out_indices, out_data)
273
279
 
@@ -464,11 +470,11 @@ def load_and_normalize(
464
470
  data = _build_data(values, value_ptr, indices.shape[0])
465
471
  row_indptr = value_ptr[major_ptr]
466
472
 
467
- gene_totals_raw = _weighted_bincount(indices, data, n_genes, numba.get_num_threads())
473
+ gene_totals_raw = _weighted_bincount(indices, data, n_genes, accumulator_threads(n_genes))
468
474
  gene_mask = gene_totals_raw > (gene_threshold * n_cells)
469
475
  if min_cells is not None:
470
476
  gene_detection_counts = _gene_detection_counts(
471
- indices, data, n_genes, numba.get_num_threads()
477
+ indices, data, n_genes, accumulator_threads(n_genes)
472
478
  )
473
479
  gene_mask &= gene_detection_counts >= min_cells
474
480
  metadata_cell_mask = cell_mask
@@ -495,11 +501,11 @@ def load_and_normalize(
495
501
  )
496
502
  del packed
497
503
 
498
- gene_totals_raw = _weighted_bincount(indices, data, n_genes, numba.get_num_threads())
504
+ gene_totals_raw = _weighted_bincount(indices, data, n_genes, accumulator_threads(n_genes))
499
505
  gene_mask = gene_totals_raw > (gene_threshold * selected_rows.shape[0])
500
506
  if min_cells is not None:
501
507
  gene_detection_counts = _gene_detection_counts(
502
- indices, data, n_genes, numba.get_num_threads()
508
+ indices, data, n_genes, accumulator_threads(n_genes)
503
509
  )
504
510
  gene_mask &= gene_detection_counts >= min_cells
505
511
 
@@ -18,15 +18,13 @@ on a given array (:class:`~vsparse.VCSCArray` for ``self @ B``,
18
18
  :class:`~vsparse.VCSRArray` for ``B @ self``) doesn't have that alignment --
19
19
  rather than run a scatter kernel there (thread-local output-shaped
20
20
  accumulators, reduced across threads: cache-unfriendly, and memory-hungry
21
- enough for wide ``B`` to need throttling), :func:`_get_dual` builds and
22
- caches the *other* VCS format's storage for the same underlying array, once,
23
- via :meth:`~vsparse._base._VCSBase._transpose_major` -- a single global sort
24
- (see :func:`vsparse._construct.transpose_major`), not a per-call cost -- and
25
- every subsequent call in the misaligned direction runs the same
26
- major-aligned kernel against that cached dual instead. ``row_scale``/
27
- ``gene_scale``/``col_mean`` are per-row/per-column statistics, so they carry
28
- over unchanged regardless of which physical layout is used to compute
29
- against.
21
+ enough for wide ``B`` to need throttling), the storage is regrouped into the
22
+ other VCS format via :meth:`~vsparse._base._VCSBase._transpose_major`, a
23
+ chunk of major slices at a time so the extra memory is one chunk's worth
24
+ rather than a second copy of the array.
25
+
26
+ ``row_scale``/``gene_scale``/``col_mean`` are per-row/per-column statistics,
27
+ so a chunk just takes the slice of them its own axis covers.
30
28
  """
31
29
 
32
30
  from __future__ import annotations
@@ -62,14 +60,6 @@ def _vcsr_matmul_delta(major_ptr, values, value_ptr, indices, row_scale, gene_sc
62
60
  out[i, c] += delta * B[col, c]
63
61
 
64
62
 
65
- def _matmul_vcsr(arr, row_scale, gene_scale, B: np.ndarray) -> np.ndarray:
66
- n_rows = arr.n_major
67
- k = B.shape[1]
68
- out = np.zeros((n_rows, k), dtype=np.float64)
69
- _vcsr_matmul_delta(arr.major_ptr, arr.values, arr.value_ptr, arr.indices, row_scale, gene_scale, B, out)
70
- return out
71
-
72
-
73
63
  # -- major-aligned: VCSC, B @ self (out cols == major slices) ---------------
74
64
  #
75
65
  # ``B`` arrives as (p, n_rows) and the natural output is (p, n_cols) -- but
@@ -103,20 +93,57 @@ def _vcsc_rmatmul_delta(major_ptr, values, value_ptr, indices, row_scale, gene_s
103
93
  acc[c] += delta * brow[c]
104
94
 
105
95
 
106
- def _rmatmul_vcsc(arr, row_scale, gene_scale, B: np.ndarray) -> np.ndarray:
107
- n_cols = arr.n_major
108
- p = B.shape[0]
109
- Bt = np.ascontiguousarray(B.T) # (n_rows, p)
110
- out_t = np.zeros((n_cols, p), dtype=np.float64)
111
- _vcsc_rmatmul_delta(arr.major_ptr, arr.values, arr.value_ptr, arr.indices, row_scale, gene_scale, Bt, out_t)
112
- return np.ascontiguousarray(out_t.T)
96
+ # ``Delta @ B`` splits over the contracted axis and ``B @ Delta`` over rows,
97
+ # so a contiguous range of major slices can be regrouped on its own,
98
+ # accumulated into the shared output, and dropped.
99
+
100
+ _CHUNK_BUDGET_BYTES = 128 << 20 # 128 MiB of transient regrouping per chunk
113
101
 
102
+ # transpose_major sorts globally over the chunk's nonzeros, so its peak is
103
+ # several nnz-sized temporaries. Deliberately generous, since underestimating
104
+ # means the budget doesn't hold.
105
+ _TRANSPOSE_BYTES_PER_NNZ = 64
114
106
 
115
- # -- dual-format cache: gives every call a major-aligned array to run against
116
107
 
108
+ def _chunk_bounds(arr, budget_bytes: int) -> list[tuple[int, int]]:
109
+ """Contiguous ``[start, stop)`` major-slice ranges, each within the byte budget."""
110
+ n_major = arr.n_major
111
+ if n_major == 0:
112
+ return []
113
+ max_nnz = max(1, budget_bytes // _TRANSPOSE_BYTES_PER_NNZ)
114
+ if arr.nnz <= max_nnz:
115
+ return [(0, n_major)]
117
116
 
118
- def _get_dual(nview: _VCSNormalizedBase):
119
- """The opposite-format raw array for ``nview``'s wrapped array, built once and cached."""
117
+ # nnz of major slices [0, j) -- value_ptr indexed by the group boundary.
118
+ cumulative = arr.value_ptr[arr.major_ptr]
119
+ bounds = []
120
+ start = 0
121
+ while start < n_major:
122
+ # Furthest stop whose chunk stays under budget; always advance by >= 1.
123
+ stop = int(np.searchsorted(cumulative, cumulative[start] + max_nnz, side="right")) - 1
124
+ stop = min(max(stop, start + 1), n_major)
125
+ bounds.append((start, stop))
126
+ start = stop
127
+ return bounds
128
+
129
+
130
+ def _aligned_source(nview: _VCSNormalizedBase, needed_format: str):
131
+ """``(array, None)`` to run one major-aligned pass, or ``(None, chunk bounds)``."""
132
+ arr = nview._arr
133
+ if arr._format == needed_format:
134
+ return arr, None
135
+ if nview._dual_arr is not None:
136
+ return nview._dual_arr, None
137
+ bounds = _chunk_bounds(arr, _CHUNK_BUDGET_BYTES)
138
+ if len(bounds) <= 1:
139
+ # Regrouping the whole array already fits the per-call budget, so
140
+ # keeping it costs no extra peak memory and saves every later call.
141
+ return _build_dual(nview), None
142
+ return None, bounds
143
+
144
+
145
+ def _build_dual(nview: _VCSNormalizedBase):
146
+ """Build and cache the opposite-format copy of ``nview``'s array, once."""
120
147
  if nview._dual_arr is None:
121
148
  nview._dual_arr = nview._arr._transpose_major()
122
149
  return nview._dual_arr
@@ -140,10 +167,27 @@ def normalized_at_dense(nview: _VCSNormalizedBase, other: Any) -> np.ndarray:
140
167
  arr = nview._arr
141
168
  n_cols = arr.shape[1]
142
169
  B, squeeze = _prep_dense(other, n_cols)
170
+ out = np.zeros((arr.shape[0], B.shape[1]), dtype=np.float64)
171
+
172
+ # self @ B is major-aligned for VCSR; a VCSC array needs regrouping.
173
+ src, bounds = _aligned_source(nview, "csr")
174
+ if src is not None:
175
+ _vcsr_matmul_delta(
176
+ src.major_ptr, src.values, src.value_ptr, src.indices,
177
+ nview.row_scale, nview.gene_scale, B, out,
178
+ )
179
+ else:
180
+ # Column chunk at a time: Delta @ B == sum over chunks of
181
+ # Delta[:, chunk] @ B[chunk, :], so each chunk's contribution
182
+ # accumulates into the same output and is then discarded.
183
+ for start, stop in bounds:
184
+ chunk = arr._major_range(start, stop)._transpose_major()
185
+ _vcsr_matmul_delta(
186
+ chunk.major_ptr, chunk.values, chunk.value_ptr, chunk.indices,
187
+ nview.row_scale, nview.gene_scale[start:stop],
188
+ np.ascontiguousarray(B[start:stop]), out,
189
+ )
143
190
 
144
- # self @ B is major-aligned for VCSR; VCSC needs its VCSR dual.
145
- src = arr if arr._format == "csr" else _get_dual(nview)
146
- out = _matmul_vcsr(src, nview.row_scale, nview.gene_scale, B)
147
191
  baseline = (-nview.col_mean) @ B # (k,): every row's implicit-zero contribution
148
192
  out += baseline[None, :]
149
193
  return out[:, 0] if squeeze else out
@@ -159,10 +203,28 @@ def dense_at_normalized(nview: _VCSNormalizedBase, other: Any) -> np.ndarray:
159
203
  if B2.ndim != 2 or B2.shape[1] != n_rows:
160
204
  raise ValueError(f"shape mismatch: expected last dimension {n_rows}, got {B2.shape}")
161
205
  B2 = np.ascontiguousarray(B2)
162
-
163
- # B @ self is major-aligned for VCSC; VCSR needs its VCSC dual.
164
- src = arr if arr._format == "csc" else _get_dual(nview)
165
- out = _rmatmul_vcsc(src, nview.row_scale, nview.gene_scale, B2)
206
+ p = B2.shape[0]
207
+ Bt = np.ascontiguousarray(B2.T) # (n_rows, p) -- see the note above the kernel
208
+ out_t = np.zeros((arr.shape[1], p), dtype=np.float64)
209
+
210
+ # B @ self is major-aligned for VCSC; a VCSR array needs regrouping.
211
+ src, bounds = _aligned_source(nview, "csc")
212
+ if src is not None:
213
+ _vcsc_rmatmul_delta(
214
+ src.major_ptr, src.values, src.value_ptr, src.indices,
215
+ nview.row_scale, nview.gene_scale, Bt, out_t,
216
+ )
217
+ else:
218
+ # Row chunk at a time, accumulating into the same output.
219
+ for start, stop in bounds:
220
+ chunk = arr._major_range(start, stop)._transpose_major()
221
+ _vcsc_rmatmul_delta(
222
+ chunk.major_ptr, chunk.values, chunk.value_ptr, chunk.indices,
223
+ nview.row_scale[start:stop], nview.gene_scale,
224
+ np.ascontiguousarray(Bt[start:stop]), out_t,
225
+ )
226
+
227
+ out = np.ascontiguousarray(out_t.T)
166
228
  baseline = B2.sum(axis=1)[:, None] * (-nview.col_mean)[None, :] # (m, n_cols)
167
229
  out += baseline
168
230
  return out[0, :] if squeeze else out
@@ -29,12 +29,11 @@ class _VCSNormalizedBase(NormalizedViewBase):
29
29
 
30
30
  def __init__(self, arr: _VCSBase) -> None:
31
31
  super().__init__(arr)
32
- # Lazily built, cached opposite-format copy of `arr` -- see
33
- # vsparse._vcs_matmul._get_dual. Built at most once per view, the
34
- # first time a matmul needs it in the direction `arr` isn't
35
- # major-aligned for.
32
+ # Opposite-format copy of `arr`, cached by vsparse._vcs_matmul when
33
+ # regrouping the whole array fits one chunk's budget.
36
34
  self._dual_arr: _VCSBase | None = None
37
35
 
36
+
38
37
  def __matmul__(self, other: Any) -> Any:
39
38
  """``self @ other`` for a dense ``other`` -- see :mod:`vsparse._vcs_matmul`."""
40
39
  from vsparse._vcs_matmul import normalized_at_dense
@@ -1,93 +0,0 @@
1
- """Numba-accelerated numerical kernels on the VCS layout."""
2
-
3
- from __future__ import annotations
4
-
5
- import numba
6
- import numpy as np
7
-
8
- __all__ = ["major_matmat", "major_matvec", "minor_matmat", "minor_matvec"]
9
-
10
-
11
- @numba.njit(cache=True)
12
- def _major_matvec(major_ptr, values, value_ptr, indices, x, n_major, n_minor):
13
- """y = A @ x where A's major axis (columns for VCSC) has length n_major.
14
-
15
- x has length n_major, output y has length n_minor.
16
- """
17
- y = np.zeros(n_minor, dtype=values.dtype)
18
- for j in range(n_major):
19
- xj = x[j]
20
- if xj == 0:
21
- continue
22
- for u in range(major_ptr[j], major_ptr[j + 1]):
23
- val = values[u] * xj
24
- for k in range(value_ptr[u], value_ptr[u + 1]):
25
- y[indices[k]] += val
26
- return y
27
-
28
-
29
- @numba.njit(cache=True, parallel=True)
30
- def _minor_matvec(major_ptr, values, value_ptr, indices, x, n_major):
31
- """y = x @ A, i.e. contract over the minor axis. x has length n_minor.
32
-
33
- Output y has length n_major. Safe to parallelize over major slices since
34
- each output element is written by exactly one iteration.
35
- """
36
- y = np.zeros(n_major, dtype=values.dtype)
37
- for j in numba.prange(n_major): # ty: ignore[not-iterable]
38
- s = 0.0
39
- for u in range(major_ptr[j], major_ptr[j + 1]):
40
- acc = 0.0
41
- for k in range(value_ptr[u], value_ptr[u + 1]):
42
- acc += x[indices[k]]
43
- s += values[u] * acc
44
- y[j] = s
45
- return y
46
-
47
-
48
- @numba.njit(cache=True)
49
- def _major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor):
50
- """Y = A @ B where A's major axis has length n_major, B is (n_major, k)."""
51
- k = b.shape[1]
52
- y = np.zeros((n_minor, k), dtype=values.dtype)
53
- for j in range(n_major):
54
- for u in range(major_ptr[j], major_ptr[j + 1]):
55
- val = values[u]
56
- for idx in range(value_ptr[u], value_ptr[u + 1]):
57
- row = indices[idx]
58
- for c in range(k):
59
- y[row, c] += val * b[j, c]
60
- return y
61
-
62
-
63
- @numba.njit(cache=True, parallel=True)
64
- def _minor_matmat(major_ptr, values, value_ptr, indices, b, n_major):
65
- """Y = B @ A, i.e. B is (k, n_minor), contracting over the minor axis."""
66
- k = b.shape[0]
67
- y = np.zeros((k, n_major), dtype=values.dtype)
68
- for j in numba.prange(n_major): # ty: ignore[not-iterable]
69
- for u in range(major_ptr[j], major_ptr[j + 1]):
70
- val = values[u]
71
- for idx in range(value_ptr[u], value_ptr[u + 1]):
72
- col = indices[idx]
73
- for c in range(k):
74
- y[c, j] += val * b[c, col]
75
- return y
76
-
77
-
78
- def major_matvec(major_ptr, values, value_ptr, indices, x, n_major, n_minor):
79
- return _major_matvec(major_ptr, values, value_ptr, indices, np.asarray(x), n_major, n_minor)
80
-
81
-
82
- def minor_matvec(major_ptr, values, value_ptr, indices, x, n_major):
83
- return _minor_matvec(major_ptr, values, value_ptr, indices, np.asarray(x), n_major)
84
-
85
-
86
- def major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor):
87
- b = np.ascontiguousarray(b)
88
- return _major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor)
89
-
90
-
91
- def minor_matmat(major_ptr, values, value_ptr, indices, b, n_major):
92
- b = np.ascontiguousarray(b)
93
- return _minor_matmat(major_ptr, values, value_ptr, indices, b, n_major)
File without changes
File without changes
File without changes
File without changes