Skip to main content

Crate strided_kernel

Crate strided_kernel 

Source
Expand description

§strided-kernel

Concrete dtype-erased ordinary arithmetic and indexing dispatch, with the checked typed APIs re-exported from strided-basic. Runtime-DAG fusion is provided by the separate strided-fused crate. The two concrete owners do not depend on one another.

§Scope

  • Unary/Binary/N-ary map kernels (map_into, zip_map*_into)
  • Reductions (reduce, reduce_axis)
  • Prepared plans: compile validates the layout once and returns a handle whose execute reuses that work.
    • Copy and update: CopyPlan, UpdatePlan
    • Structural: SlicePlan, ReversePlan, PadPlan, ConcatenatePlan
    • Gather family: GatherSpec / GatherPlan, ScatterSpec / ScatterPlan, DynamicSlicePlan, DynamicUpdateSlicePlan. ScatterPlan::execute takes an element type of the sealed ScatterScalar set and wraps integer overflow, like ErasedScatterPlan; execute_with_combine takes any combine
  • Dtype-erased replays of the plans above: ErasedCopyPlan, ErasedUpdatePlan, ErasedConcatenatePlan, ErasedSlicePlan, ErasedReversePlan, ErasedPadPlan, ErasedGatherPlan, ErasedScatterPlan, ErasedDynamicSlicePlan, ErasedDynamicUpdateSlicePlan. Each resolves the runtime dtype, plus the family’s runtime operation where it has one, once per call and then runs a loop monomorphized for both
  • Single-axis and full erased reductions: ErasedReducePlan (full and axis reductions), cumulative scans (ErasedScanPlan), argmax / argmin (ErasedArgReducePlan) and fused layer_norm / rms_norm (ErasedNormPlan); their tie, NaN and rounding contracts are in the rustdoc
  • Batched outer product (batched_outer_product_into, plan_lazy_outer_product / LazyOuterProductLayout)
  • Runtime-selected one-shot entries for callers that have no plan to reuse: erased_map_into, erased_zip_into, erased_broadcast_mul_into_uninit, erased_select_into_uninit, erased_clamp_into_uninit, erased_compare_into_uninit
  • Utility ops (copy_into, add_acc, dot, sum, symmetrize_into)
  • Optional parallel execution through threadteam::Exec placement tokens (parallel feature)

fused_elementwise_into and the runtime-DAG types stay re-exported from strided-fused, so those names keep resolving for code written against the 0.4 line. The calls are not source compatible: 0.4 took three arguments, and the current release line requires a threadteam::Exec placement token as the fourth (strided-fused/src/fused.rs:1855), so a 0.4 call site fails to compile. New code imports them from strided-fused; the re-exports survive in 0.14 and may be removed in a future breaking release.

§Quick Example

use strided_kernel::{map_into, Exec, StridedArray};

let src = StridedArray::<f64>::from_fn_row_major(&[2, 3], |idx| (idx[0] * 3 + idx[1]) as f64);
let mut dst = StridedArray::<f64>::row_major(&[2, 3]);
map_into(&mut dst.view_mut(), &src.view(), |x| 2.0 * x, Exec::serial()).unwrap();
assert_eq!(dst.get(&[1, 2]), 10.0);

§Map and Reduce Operations

use strided_kernel::{Exec, StridedArray, map_into, zip_map2_into, reduce};

let a = StridedArray::<f64>::from_fn_row_major(&[4, 5], |idx| idx[0] as f64);
let b = StridedArray::<f64>::from_fn_row_major(&[4, 5], |idx| idx[1] as f64);
let mut out = StridedArray::<f64>::row_major(&[4, 5]);

// Unary map: dest[i] = f(src[i])
map_into(&mut out.view_mut(), &a.view(), |x| x * 2.0, Exec::serial()).unwrap();

// Binary zip map: dest[i] = f(a[i], b[i])
zip_map2_into(&mut out.view_mut(), &a.view(), &b.view(), |x, y| x + y, Exec::serial()).unwrap();

// Full reduction
let total = reduce(&a.view(), |x| x, |a, b| a + b, 0.0, Exec::serial()).unwrap();

§Built-in Erased Reduction Order

The built-in erased Sum, Product, and SumSquares reductions have a narrower, explicit determinism contract than the generic closure-based reduce API:

  • Compact full reductions traverse consecutive physical storage from the logical origin. Other full reductions use the stable fused/block traversal. Axis reductions enumerate reduced coordinates in declared axis order, with the first reduced axis varying fastest.
  • Serial compact f32/f64 full reductions use four SIMD accumulators when the simd feature is enabled. Other dtype/feature combinations use a fixed eight-lane scalar accumulator. Accumulator lanes are merged in stable order. Generic closure reductions retain their existing association.
  • SumSquares accepts f32 and f64. Each value is multiplied by itself and rounded in that dtype before the result enters the Sum accumulator. The multiply and add are not contracted into FMA, so overflow and underflow are classified before accumulation. The kernel does not materialize a squared tensor.
  • i32 and i64 use wrapping sum/product. Floating and complex reductions use same-dtype arithmetic without widening, compensation, conjugation, or fast-math. Reassociation can change roundoff, signed zero, NaN details, and the point at which an intermediate overflows or underflows. Consequently, floating product may differ in finite/zero/infinite/NaN classification from a strict left fold.
  • Exec::serial() and a token of budget one use the same serial algorithm. A fixed budget has deterministic partition and merge order for a fixed executable, target, input, and layout; task completion order does not affect the result. Different budgets may produce different floating or complex roundoff.
  • Empty sum, product, and sum-of-squares return zero, one, and zero respectively. No tolerance or correctness gate is relaxed for the optimized association.

§High-Level Operations

use strided_kernel::{Exec, StridedArray, copy_into, add_acc, dot, symmetrize_into};

let a = StridedArray::<f64>::from_fn_row_major(&[4, 4], |idx| (idx[0] * 10 + idx[1]) as f64);
let mut out = StridedArray::<f64>::row_major(&[4, 4]);

// Copy
copy_into(&mut out.view_mut(), &a.view(), Exec::serial()).unwrap();

// Accumulating element-wise add: dest[i] += src[i]
add_acc(&mut out.view_mut(), &a.view(), Exec::serial()).unwrap();

// Dot product
let d = dot(&a.view(), &a.view()).unwrap();

// Symmetrize: dest = (src + src^T) / 2
symmetrize_into(&mut out.view_mut(), &a.view(), Exec::serial()).unwrap();

§Cache Optimization

The library automatically optimizes iteration order for cache efficiency:

  1. Dimension Fusion: Contiguous dimensions are fused to reduce loop overhead
  2. Dimension Reordering: Dimensions are sorted by stride magnitude for optimal memory access
  3. Tiled Iteration: Operations are blocked to fit in L1 cache (32KB)
  4. Contiguous Fast Paths: Contiguous arrays bypass blocking for direct iteration

§Parallel Feature

[dependencies]
# 0.16 carries the `*_acc` / `*_into` names and the sealed `ScatterScalar` bound (0.15.0 is the published line until it is released).
strided-kernel = { version = "0.16", features = ["parallel"] }

Every operation that can fan out takes a threadteam::Exec placement token as its last argument; Exec, Pool and PoolBuilder are re-exported from the crate root. The caller owns a pool, mints a token for a budget of its slots, and passes it by value. Exec::serial() runs inline on the calling thread.

use strided_kernel::{map_into, Exec, Pool, StridedArray};

let source = StridedArray::<f64>::from_fn_col_major(&[4], |index| index[0] as f64);
let mut destination = StridedArray::<f64>::col_major(&[4]);
let pool = Pool::builder().threads(2).build().unwrap();

map_into(
    &mut destination.view_mut(),
    &source.view(),
    |value| value + 1.0,
    Exec::new(&pool, 2).unwrap(),
)
.unwrap();
assert_eq!(destination.into_data(), vec![1.0, 2.0, 3.0, 4.0]);

The token carries the budget and the pool, so no thread-local placement state exists and nested operations split the budget they were given. simd is enabled by default; parallel lets pooled tokens run on a private threadteam pool, and without it every token runs inline. Features select implementation capabilities, not operation families.

§Benchmarks

Run all benchmarks (single-threaded + multi-threaded, Rust + Julia):

bash strided-kernel/benches/run_all.sh        # default thread counts: 1 2 4
bash strided-kernel/benches/run_all.sh 1 2 4 8  # custom thread counts

Or individually:

# Single-threaded Rust
cargo bench --bench rust_compare --manifest-path strided-kernel/Cargo.toml

# Single-threaded Julia
JULIA_NUM_THREADS=1 julia --project=strided-kernel/benches strided-kernel/benches/julia_compare.jl

# Multi-threaded Rust (N threads)
# The multi-threaded harnesses read STRIDED_KERNEL_BENCH_THREADS, build a pool of
# exactly that width and assert the effective budget; the workspace has no Rayon
# dependency, so RAYON_NUM_THREADS does nothing here.
STRIDED_KERNEL_BENCH_THREADS=N cargo bench --features parallel --bench threaded_compare --manifest-path strided-kernel/Cargo.toml

# Multi-threaded comparison script
bash strided-kernel/benches/run_threaded.sh 1 2 4

# Scaling benchmarks (sum + permute, 1/2/4 threads)
bash strided-kernel/benches/run_scaling.sh
bash strided-kernel/benches/run_scaling.sh 1 2 4 8  # custom thread counts

# Rank-25 tensor permutation (quantum circuit simulation workload)
cargo bench --bench rank25_permute --manifest-path strided-kernel/Cargo.toml

# Rank-25 Julia comparison
JULIA_NUM_THREADS=1 julia --project=strided-kernel/benches strided-kernel/benches/julia_rank25_compare.jl

# Mul kernel comparison against PyTorch CPU at 1T and 4T.
# Requires uv; the script uses uv run --with torch --with numpy so PyTorch
# is installed only in the benchmark environment.
# The PyTorch runner uses torch.mul(..., out=...) to avoid allocator/autograd overhead.
# Noncompact batched outer product includes both compact output and a
# torchlike_output case whose non-contiguous output strides match torch.einsum.
uv --version
STRIDED_KERNEL_MUL_BENCH_PROFILE=full bash strided-kernel/benches/run_mul_pytorch_compare.sh 1 4

Published benchmark programs and current measured results live in strided-rs-benchmark-suite.

§Algorithm Comparison: Julia Strided.jl vs Rust strided-rs

Both implementations share the same core algorithm ported from Strided.jl:

  1. Dimension fusion — merge contiguous dimensions to reduce loop depth
  2. Importance-weighted ordering — bit-pack stride orders with output array weighted 2× to determine optimal iteration order
  3. L1 cache blocking — iteratively halve block sizes until the working set fits in 32 KB
  4. Reversed loop nesting — innermost loop operates on the highest-importance dimension (smallest stride) for optimal cache access

The key architectural differences are:

FeatureJuliaRust
Kernel generation@generated unrolls loops per (rank, num_arrays) at compile timeHandwritten 1D/2D/3D/4D specializations + generic N-D fallback
Inner-loop SIMDExplicit @simd pragma on innermost loopStride-specialized inner loops: slice-based when stride=1, raw pointer otherwise; LLVM auto-vectorizes them at the SIMD level pulp selects at run time
ThreadingRecursive dimension-splitting via Threads.@spawnRecursive dimension-splitting via threadteam::Exec::fork, one child token per half; order-before-fuse pipeline enables layout-agnostic parallelization

Note: Strided.jl threading bug for non-column-major views. Julia’s pipeline fuses before ordering (fuse → order → block), so _mapreduce_fuse! only detects column-major contiguity. Permuted views (e.g. PermutedDimsArray(A, (2,1))) with row-major strides are never fused, causing _mapreduce_threaded! to fall through to the single-threaded kernel. strided-rs fixes this by simply reordering the pipeline to order → fuse → block: ordering first puts smallest-stride dimensions adjacent, and a single fusion pass then catches contiguity regardless of memory layout. See docs/strided_jl_threading_bug.md for a minimal reproduction and root cause analysis. Dtype-erased arithmetic and indexing kernels, with shared typed primitives. Runtime-DAG fusion is provided separately by strided-fused.

Modules§

auxiliary
Auxiliary routines ported from StridedViews.jl/src/auxiliary.jl
execution
Execution contract for operation-family implementations.
injectivity
Output-layout injectivity validation.
view
Julia-like dynamic-rank strided view types.

Structs§

Adjoint
Adjoint operation: f(x) = adjoint(x) = conj(transpose(x)) For scalar numbers, this is conj.
Classed
An element function together with the KernelClass it is charged as.
ConcatenatePlan
A compiled multi-input concatenate traversal.
Conj
Complex conjugate operation: f(x) = conj(x)
CopyPlan
A compiled copy traversal for one (dims, dst_strides, src_strides) layout pair.
DynamicSlicePlan
A compiled fixed-window dynamic-slice traversal.
DynamicUpdateSlicePlan
A compiled dynamic-update-slice traversal.
ErasedArgReducePlan
Dtype-erased argmax / argmin along one axis.
ErasedConcatenatePlan
Dtype-erased concatenate wrapper.
ErasedCopyPlan
Dtype-erased wrapper around CopyPlan.
ErasedDynamicSlicePlan
Dtype-erased fixed-window dynamic-slice wrapper.
ErasedDynamicUpdateSlicePlan
Dtype-erased dynamic-update-slice wrapper.
ErasedFusedPlan
Dtype-erased wrapper around FusedPlan.
ErasedGatherPlan
Dtype-erased gather wrapper.
ErasedNormPlan
Dtype-erased fused layer_norm / rms_norm along one axis.
ErasedPadPlan
Dtype-erased pad wrapper.
ErasedRawStridedMut
Borrowed dtype-erased raw strided output layout.
ErasedRawStridedPtr
Pointer-backed dtype-erased input used by one-shot write entry points.
ErasedRawStridedRef
Borrowed dtype-erased raw strided input layout.
ErasedRawStridedUninitMut
Borrowed dtype-erased raw strided output whose reachable elements may be uninitialized.
ErasedReducePlan
Dtype-erased reduction wrapper.
ErasedReversePlan
Dtype-erased reverse wrapper.
ErasedScanPlan
Dtype-erased cumulative scan (cumsum / cumprod) along one axis.
ErasedScatterPlan
Dtype-erased additive scatter wrapper.
ErasedSlicePlan
Dtype-erased static-slice wrapper.
ErasedUpdatePlan
Dtype-erased wrapper around UpdatePlan.
Exec
budget slots of a Pool, or the calling thread alone.
FusedInst
One SSA instruction in a FusedPlan.
FusedPlan
Topologically ordered fused elementwise SSA DAG.
GatherPlan
A compiled gather traversal for one value layout, index layout, and output layout.
GatherSpec
Gather configuration shared by generic and erased replay.
Identity
Identity operation: f(x) = x
LazyOuterProductLayout
Storage layout for a lazily ordered outer product.
NormSpec
Kind, eps and optional affine parameters of an ErasedNormPlan.
PadPlan
A compiled pad traversal.
Pool
A fixed set of worker threads that Exec tokens place work on.
PoolBuilder
Configuration of a Pool.
RawStridedMut
Borrowed raw strided output layout.
RawStridedRef
Borrowed raw strided input layout.
ReversePlan
A compiled reverse traversal over selected axes.
RunIndex
Rows grouped by destination: CSR offsets plus a stable row permutation.
RunSumPlan
dest[r, ..] (=|+=) Σ_{j in ptr[r]..ptr[r+1]} src[perm[j], ..].
ScanOptions
Direction and inclusivity of an ErasedScanPlan.
ScatterPlan
A compiled additive scatter traversal.
ScatterSpec
Scatter configuration shared by generic and erased replay.
SlicePlan
A compiled static-slice traversal.
StridedArray
Owned strided multidimensional array.
StridedView
Dynamic-rank immutable strided view with lazy element operations.
StridedViewMut
Dynamic-rank mutable strided view.
Transpose
Transpose operation: f(x) = transpose(x) For scalar numbers, this is identity. For matrix elements, this would transpose each element.
UpdatePlan
A compiled read-modify-write traversal for one (dims, dst_strides, src_strides) layout pair.

Enums§

ArgReduceOp
Runtime operation of an ErasedArgReducePlan.
CompareOp
Runtime comparison selected once before entering the element loop.
ErasedMapOp
Runtime unary operation for erased_map_into.
ErasedZipOp
Runtime binary operation for erased_zip_into.
FusedOp
Runtime scalar operation for a fused elementwise plan.
KernelDType
Dtypes supported by dtype-erased kernel entry points.
NormKind
Normalization computed by an ErasedNormPlan.
ReduceOp
Runtime reduction operation for dtype-erased full reductions.
ScanOp
Runtime operation of an ErasedScanPlan.
StridedError
Errors that can occur during strided array operations.
UpdateOp
Runtime unary operation applied to the source of an ErasedUpdatePlan.

Constants§

BLOCK_MEMORY_SIZE
Block memory size for cache-optimized iteration (L1 cache target).
CACHE_LINE_SIZE
Cache line size in bytes.
INLINE_RANK
Maximum rank whose metadata is stored inline without a heap allocation.
OPERAND_CAP
Number of operand slots: destination plus up to four inputs.
RAW_FUSED_RANK_LIMIT
Rank up to which a fused loop nest is stored inline.

Traits§

ComposableElementOp
Trait for element operations that support type-level composition.
Compose
Helper trait for composing two ElementOp types.
ElementOp
Trait for element-wise operations applied to strided views.
ElementOpApply
Trait for types that support element operations (conj, transpose, adjoint).
FusedScalar
Scalar types supported by fused_elementwise_into.
GatherIndex
Index scalar types accepted by GatherPlan.
KernelStorageElement
A scalar type that can safely witness storage for an erased kernel view.
MapFn
An element function that carries its KernelClass.
MaybeSimdOps
Trait for types that may have SIMD-accelerated sum/dot operations.
ScatterScalar
Element types accepted by ScatterPlan::execute.

Functions§

add_acc
Accumulating element-wise addition: dest[i] += src[i].
axpby_accum
Update caller-owned contiguous storage: y = alpha * x + beta * y.
axpy_acc
Accumulating AXPY: dest[i] = alpha * src[i] + dest[i].
axpy_conj_raw
dest = alpha * conj(src) + dest over borrowed raw strided layouts.
axpy_raw
dest = alpha * src + dest over borrowed raw strided layouts.
batched_outer_product_into
Compute dest[lhs_free..., rhs_free..., batch...] = lhs[lhs_free..., batch...] * rhs[rhs_free..., batch...].
batched_outer_product_into_uninit
Compute a batched outer product into a fully overwritten uninitialized output.
broadcast_mul_into
Broadcasted element-wise multiplication: dest[i] = a[i] * b[i].
broadcast_mul_into_uninit
Broadcast and multiply into a fully overwritten uninitialized output.
col_major_strides
Compute column-major strides (Julia default: first index varies fastest).
compare_into
Compare two ordered views elementwise into a Boolean destination.
compare_into_uninit
Compare two views into a fully overwritten uninitialized Boolean output.
copy_conj_into
Overwriting copy with complex conjugation: dest[i] = conj(src[i]).
copy_into
Copy elements from source to destination: dest[i] = src[i].
copy_into_col_major
Copy elements from src to dst, optimized for col-major destination.
copy_into_uninit
Copy initialized values into a potentially uninitialized destination.
copy_scale_conj_raw
dest = scale * conj(src) over borrowed raw strided layouts.
copy_scale_into
Overwriting copy with scaling: dest[i] = scale * src[i].
copy_scale_raw
dest = scale * src over borrowed raw strided layouts.
copy_transpose_scale_into
Copy with transpose and scaling: dest[j,i] = scale * src[i,j].
dot
Dot product: sum(OpA::apply(a[i]) * OpB::apply(b[i])).
embed_diagonal_into_uninit
Embed a dense column-major input on a diagonal in a new axis.
embed_diagonal_view_into_uninit
Embed a strided input on a diagonal in a new axis of caller-owned contiguous storage.
erased_broadcast_mul_into_uninit
Broadcast two same-dtype operands onto the destination axes and multiply them into uninitialized storage.
erased_clamp_into_uninit
Clamp elementwise into uninitialized storage: dest[i] = minimum(hi[i], maximum(lo[i], x[i])).
erased_compare_into_uninit
Compare two same-dtype operands elementwise into uninitialized bool storage.
erased_map_into
Apply one runtime-selected unary operation without compiling a plan.
erased_map_into_uninit
Apply one runtime-selected unary operation into uninitialized storage.
erased_select_into_uninit
Select elementwise between two same-dtype operands by a bool predicate, writing uninitialized storage: dest[i] = if pred[i] { on_true[i] } else { on_false[i] }.
erased_zip_into
Apply one runtime-selected binary operation without compiling a plan.
erased_zip_into_uninit
Apply one runtime-selected binary operation into uninitialized storage.
fma_acc
Accumulating fused multiply-add: dest[i] += OpA::apply(a[i]) * OpB::apply(b[i]).
fused_elementwise_into
Evaluate a runtime-DAG elementwise plan into one or more destinations.
is_injective_layout
Decide whether distinct logical positions map to distinct offsets.
map_into
Apply a function element-wise from source to destination.
map_into_uninit_with_kernel
Apply an element-wise function into a potentially uninitialized destination, handing a vectorized kernel the flat runs it can take.
map_update_into
Update in place: dest[i] = f(OpD(dest[i])).
mul_acc
Accumulating element-wise multiplication: dest[i] *= src[i].
mul_into
Element-wise multiplication: dest[i] = a[i] * b[i].
mul_into_uninit
Multiply two views into a fully overwritten uninitialized output.
nan_propagating_maximum
NaN-propagating elementwise maximum for real floats.
nan_propagating_minimum
NaN-propagating elementwise minimum for real floats.
plan_lazy_outer_product
Plan an outer-product output whose memory order follows the inputs’ physical stride order instead of the logical output order.
reduce
Full reduction with map function: reduce(init, op, map.(src)).
reduce_axis
Reduce along a single axis, returning a new StridedArray.
reduce_axis_into
Reduce along a single axis into caller-owned storage.
replay_copy_raw
dest = src, replaying the axes of the two views exactly as given.
replay_copy_raw_uninit
replay_copy_raw into a potentially uninitialized destination.
replay_map_raw
f(&mut dest[i], src[i]) for every element, replaying the axes of the two views exactly as given.
replay_map_raw_fused
f(&mut dest[i], src[i]) after fusing the two layouts inside the call.
replay_map_raw_serial
replay_map_raw on the calling thread, for callbacks and elements that are not Send + Sync: f(&mut dest[i], src[i]) for every element, with f an FnMut.
replay_map_raw_uninit
dest[i] = f(src[i]) into a potentially uninitialized destination.
replay_map_raw_uninit_fused
replay_map_raw_fused into a potentially uninitialized destination.
robust_complex_divide_f32
Divide two Complex<f32> values by widening to Complex<f64> (Julia’s Complex{Float32} route), so the f32 squares cannot overflow.
robust_complex_divide_f64
Divide two Complex<f64> values without the |z|² overflow/underflow of the textbook formula.
row_major_strides
Compute row-major strides (C default: last index varies fastest).
sum
Sum all elements: sum(src).
symmetrize_conj_into
Conjugate-symmetrize a square matrix: dest = (src + conj(src^T)) / 2.
symmetrize_into
Symmetrize a square matrix: dest = (src + src^T) / 2.
triangular_mask_into_uninit
Copy dense column-major matrices, replacing the masked triangle with fill.
triangular_mask_view_into_uninit
Mask a triangular region of a strided input into caller-owned contiguous storage.
zip_map2_into
Binary element-wise operation: dest[i] = f(a[i], b[i]).
zip_map3_into
Ternary element-wise operation: dest[i] = f(a[i], b[i], c[i]).
zip_map4_into
Quaternary element-wise operation: dest[i] = f(a[i], b[i], c[i], e[i]).
zip_reduce
Two-input mapped reduction: reduce(init, op, map.(a[i], b[i])).
zip_update2_into
Update in place from one input: dest[i] = f(OpD(dest[i]), OpA(a[i])).
zip_update3_into
Update in place from two inputs: dest[i] = f(OpD(dest[i]), OpA(a[i]), OpB(b[i])).

Type Aliases§

AxisVec
Axis metadata with inline storage for up to INLINE_RANK dimensions.
InlineVec
Inline vector of at most strided_view::INLINE_RANK elements.
OperandVec
Inline vector of at most OPERAND_CAP operands (strides, offsets, …).
Result
Result type for strided array operations.
StrideVec
Stride metadata with inline storage for up to INLINE_RANK dimensions.