Skip to content

API Reference

Formats

  • CSRMatrix(values, col_indices, row_ptrs, shape) — compressed sparse row
  • .to_dense() — materialize back to a dense torch.Tensor
  • .nnz, .shape, .dtype, .density
  • COOMatrix(values, row_indices, col_indices, shape) — coordinate format
  • .to_csr() / CSRMatrix.to_coo() — roundtrip conversions
  • BSRMatrix(blocks, block_col_indices, block_row_ptrs, shape, block_size=128) — block-sparse row, the NKI compute format
  • .from_dense(dense, block_size=128, threshold=0), .from_csr(csr, ...), .to_dense(), .to_csr()
  • The NKI kernels take block_size=128 only. Other block sizes run on the PyTorch path (correct, no NKI), or raise NotImplementedError under TRNSPARSE_REQUIRE_NKI=1.
  • from_dense(dense, threshold=0) — CSR from a dense tensor
  • from_scipy(sp_matrix), eye_sparse(n)

Ops

  • spmv(A, x, alpha=1.0, y=None, beta=0.0) — sparse matrix × dense vector
  • spmv_symmetric(A, x, alpha=1.0, uplo="upper") — symmetric A; only the uplo triangle is referenced, as in BLAS symv, so A may store one triangle or the full matrix (0.12.1). A matrix that stores only the opposite triangle still uses it, with a DeprecationWarning asking for the matching uplo.
  • spmm(A, B, alpha=1.0, C=None, beta=0.0) — sparse matrix × dense matrix (on NKI: A densified on the host, then a dense GEMM on the Tensor Engine)
  • bsr_spmm(A, B) — BSR × dense, one nc_matmul per stored block
  • screened_spmm(A, diag_integrals, B, threshold) — fused Schwarz-screened SpMM
  • block_sparse_attention_tiled(Q, K, V, mask_bsr, scale=None) — two-pass block-sparse attention with autograd; see Sparse attention. seq_len must be a multiple of mask_bsr.block_size (ValueError otherwise, since 0.11.0).
  • sparse_add(A, B, alpha=1.0, beta=1.0) — α A + β B
  • sparse_scale(A, alpha) — scalar multiply
  • sparse_transpose(A) — transpose of a CSR matrix
  • nnz_per_row(A)

Iterative solvers

cg_bsr, cg_bsr_fused / prepare_cg_bsr (FusedCGOperator), chebyshev_bsr, chebyshev_coeffs, richardson_bsr, power_iteration_bsr, power_iteration_bsr_fused, jacobi_preconditioner_bsr, bsr_diagonal. See Iterative solvers.

Graph segment sum and gather (segment_sum, gather, #139)

The graph block of a message-passing interatomic potential (the MLIP exemplar, trnsci/trnsci#170), with MACE's scatter_sum semantics.

  • segment_sum(m, idx, num_segments, *, plan=None) — out[i] = Σ m[e] over the edges with idx[e] == i; rows with no edge are 0. m is [E, ...], idx is [E] int64 / int32, sorted or not. Backward: gather.
  • gather(h, idx, *, plan=None) — out[e] = h[idx[e]]. Backward: segment_sum.
  • segment_plan(idx, num_segments, *, padding=None) → SegmentPlan — sorts the edges by segment once on the host (stable, int64) and builds the kernel's tile layout. Build one per neighbour list (senders and receivers each) and pass it as plan=; .to(device) stages its tables.
  • padding: an [E] bool mask of the edges that pad E to a compile bucket. Padded edges take no slots, and every sum the plan computes skips them: segment_sum ignores m there, and so does the backward of gather. gather and the backward of segment_sum still fill padded rows (with h[idx[e]] / grad[idx[e]]). The sums are bitwise those of the plan over the real edges alone, wherever the padding points, on every backend. Without a mask, padding edges are ordinary edges: give them zero messages and spread them over segments 0, 1, 2, …, since piling them on one segment raises the slot count of every tile (#141).

Backends: pytorch is the reference (index_add_ / index_select; deterministic on the CPU). On NKI, the trnsparse::segment_sum_tiles and trnsparse::gather_rows ops (each registered as the other's backward) reduce each 128-row tile on the TensorEngine: a 0/1 incidence tile times 128 gathered message rows per nc_matmul, fp32 PSUM accumulation, in an order fixed by the plan. Results are bitwise identical run to run and at LNC=1 and LNC=2. No index is computed on the device or passes through fp32, and there is no flattened E·F / N·F index (aws-neuron-sdk#1466, #1467,

1468). One launch addresses operands up to 2^34 bytes (8000 atoms at

F = 5120 is 9.4e9 bytes, verified on trn2, #141); a wider call splits the feature axis, one launch per chunk over the same plan, bitwise equal to one launch. Size alone no longer sends an fp32 call to device aten, whose index_add_ / index_select fail at these sizes. fp64 follows the suite policy (host torch under auto). See the trnsparse.segment module docstring for the summation order and limits.

Kernel-matrix products (kernel_matmul, #93)

K(X, Y) @ V without forming K, for stationary kernels of the distance: "rbf", "matern12", "matern32", "matern52" (trnsparse.KERNELS). The operator of matrix-free Gaussian-process regression and kernel ridge regression.

  • kernel_matmul(X, Y, V, kernel="rbf", lengthscale=1.0, outputscale=1.0, noise=0.0) — Y=None gives (K(X, X) + noise I) @ V. lengthscale is a float or a (d,) tensor (per-dimension lengthscales). V is (m,) or (m, R).
  • KernelOperator(X, kernel, lengthscale, outputscale, noise, device=None) — prepares X once (centred, rescaled, fp32 on the device) for repeated applications: op(V), op.cross(Y, W) = K(Y, X) @ W, op.diag(), op.rows(idx) (rows of K for pivoted-Cholesky preconditioners).
  • kernel_matmul_reference(...) — dense float64 torch.cdist reference.

NKI path: one launch per application, or one per row block of X when the product exceeds 6e10 kernel entries n * m (#100): the Neuron runtime stops a launch after 30 s, and a single launch at n = 2^20 takes 40-80 s on Trn2. The rate is flat in R, so the budget counts entries only: about 2.2 s per launch at LNC=2, 4.5 s at LNC=1. The product runs in the fewest launches the budget allows, as equal blocks of a multiple of 1024 rows (19 blocks of 55296 rows at n = m = 2^20), the last one zero-padded to the same shape, so every block reuses one compile and one cached handle. Rows are independent, so the blocked result is bit-identical to a single launch.

Multi-core (#102): with several visible logical cores (NEURON_RT_VISIBLE_CORES=0-3 on trn2.3xlarge at LNC=2) a row-blocked product spreads its blocks round-robin over the cores. The block count is rounded up to a multiple of the core count (20 blocks of 53248 rows on 4 cores at n = m = 2^20), so every core gets the same number. Each core gets its own copy of Y, V and the parameters, staged through the host once per product, before any kernel is queued. All launches are issued from the calling thread and run asynchronously, and the blocks are gathered in row order on the operands' device. The result is bit-identical to one core. TRNSPARSE_KMV_CORES is auto (the default: every visible core when n * m exceeds the block budget, one core below it), all, or a number of cores (1 turns it off). TRNSPARSE_KMV_THREADS=1 issues each core's blocks from its own worker thread instead, after the first block of every core has been launched (and the handle traced) on the calling thread.

Per 128 x 512 tile the squared distances are one TensorEngine matmul on augmented coordinates [x, |x|^2, 1] . [-2y, 1, |y|^2] into PSUM, the kernel function runs on ScalarE reading PSUM (exp(a D + log s) for RBF), and the product with V accumulates on the TensorEngine. Lengthscale, outputscale and noise are a tensor argument, so new hyperparameters do not recompile. Output rows are split over both physical cores (LNC=2); results are bit-identical at LNC=1 and LNC=2 by construction (same Y-tile order). d <= 126.

Precision: fp32, with inputs centred on the host. The distance expansion cancels for near-coincident points (relative error about u (|x|^2 + |y|^2) / |x - y|^2); the smooth kernels see that at first order, Matern-1/2 (a cusp at 0) as sqrt(u |x|^2) / l. float64 follows the suite policy: auto computes in torch float64, explicit nki casts with a warning, TRNSPARSE_REQUIRE_NKI raises. Env: TRNSPARSE_KMV_GROUP (Y tiles per loop body, 1 to 32; default kmv_group(m): about sqrt(m / 128), from 4 to 32 (32 from m = 131072), which also minimises the fp32 summation error), TRNSPARSE_KMV_BLOCK_WORK (kernel entries per launch, default 6e10), TRNSPARSE_NKI_EAGER_HANDLE=0 (custom op instead of the cached wrap_nki handle).

Screening

  • schwarz_bounds(shell_pair_integrals) — Cauchy-Schwarz bounds $Q_{pq} = \sqrt{(pq|pq)}$
  • screen_quartets(Q, threshold) — keep only quartets with $Q_{pq}Q_{rs} > \text{threshold}$
  • density_screen(Q, P, threshold) — density-weighted screening
  • sparsity_stats(Q, threshold=1e-10) — shell, pair and quartet counts and the sparsity fraction

Dispatch

  • set_backend("auto" | "pytorch" | "nki") — select compute backend
  • get_backend() — current backend
  • HAS_NKI — module-level flag set at import time

On Neuron hardware the NKI backend runs on one of two torch-neuronx lineages, detected on the first kernel launch (force with TRNSCI_NKI_DISPATCH=native|xla|cpu):

  • Native (TorchNeuron, Trn2/Trn3) — each kernel is a custom op on device="neuron": torch.ops.trnsparse.spmm_dense, bsr_spmm, screened_spmm, attn_stats, attn_out, attn_bwd_dq, attn_bwd_dkdv, and the composite bsr_attn / bsr_attn_bwd. Backwards are attached with torch.library.register_autograd; spmm also traces under torch.compile(backend="neuron", fullgraph=True). The ops are registered only once this path is selected.
  • XLA (Trn1) — kernels run on the torch_xla device, as before.

Placement on the native path: sparse structure (CSR row_ptrs / col_indices / values, BSR block_row_ptrs / block_col_indices) stays on the host; dense operands and BSR blocks may be on neuron; results are on the dense operand's device. See Installation.

Multi-core (trnsparse.multicore, native path)

A Trn2 chip at LNC=2 has four logical NeuronCores, which TorchNeuron exposes as neuron:0 … neuron:3 (NEURON_RT_VISIBLE_CORES=0-3). Each static kernel already splits its work across the two physical cores of one logical core; these classes split it across logical cores.

  • logical_cores(n=None): the visible logical cores as devices.
  • partition_block_rows(row_ptrs, n_parts): block rows split into groups balanced by stored blocks (the same greedy as the in-kernel split).
  • ShardedBSR(A, devices=None, pretransposed=True): A split by block rows, with each core's blocks resident on that core.
  • .replicate(B) copies B to every core.
  • .spmm(B_replicas) returns one output per core, issuing one kernel launch per core without waiting.
  • .gather(outs) assembles C on the host.
  • pretransposed=True runs the pre-transposed kernel (no in-kernel transpose, fewer DMAs, and B tiles shared by groups of up to 8 block rows). Gradients reach each core's B replica and block copy.
  • ShardedAttention(mask, devices=None): a single-head block-sparse attention forward, split by query block rows. Use .shard_rows(Q), .replicate_kv(K, V), .forward(Qts, KVs) and .gather(outs). It is forward only. For several heads, put whole heads on different cores and call block_sparse_attention_tiled there; that path has autograd.

TorchNeuron does not copy tensors between logical cores. A neuron:0 tensor's .to("neuron:1") comes back still on core 0, and copy_ across cores raises. So per-core operands are built on the host and copied once, and results return through the host. The kernel ops run on the logical core of their operands, and operands on two different cores are an error.