Skip to content
prasannamahatoPublic

About

StenPy is a GPU‑accelerated field pipeline that turns symbolic expressions into production‑ready HPC workflows. If you can write gradient(f) + laplacian(g), StenPy can execute it on multi‑gigabyte volumetric data — in‑memory or streaming from disk.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

56 Commits

Folders and files

Repository files navigation

StenPy

Stencil and tensor computing for PyTorch, driven by expression strings.

StenPy lets you describe a numerical computation as a short expression, such as a Laplacian, a gradient, a curl or a diffusion step. It then parses the expression, builds a compute graph, fuses the operators into a single Triton kernel on CUDA, and falls back to plain PyTorch everywhere else. It also covers differentiation through those expressions, fused GEMM helpers, out-of-core processing of HDF5 data, and optional multi-rank execution.

Status: version 0.1.0


Contents


Features

  • Expression-driven API. Write "laplacian(u) + gradient(u, dim=0)" instead of hand-rolling stencils.
  • Fast at small and medium sizes. About 5-6x lower per-evaluation time than torch.compile on grids below ~10^5 points, and parity at large sizes (see Performance).
  • Operator fusion. Chains of elementwise and stencil operators compile into a single Triton kernel on CUDA, avoiding full-size intermediate tensors.
  • Graceful CPU fallback. With no GPU or no Triton, StenPy uses vendor and PyTorch fallbacks, so the same code runs on a laptop.
  • Many operators. Stencils (laplacian, gradient, divergence, curl, jacobian, hessian, biharmonic), reductions, matmul and einsum, FFT and spectral derivatives, linear algebra, convolutions, and sorting and scan operators.
  • Five boundary modes. periodic, neumann, reflect, dirichlet, open.
  • Autograd support. Differentiate through compute, use fused adjoints (fused_vjp), checkpointed rollout for long time-stepping loops, and CUDA-graph-captured graphed_value_and_grad.
  • Memory-aware. A built-in memory manager enforces limits and hardware profiles, and streams data from disk when it does not fit.
  • HDF5 I/O. Load and save fields with spacing and origin metadata, optionally lazily.
  • Low-overhead relaunch. bind() resolves an expression once and returns a handle that is a single raw kernel launch per call.
  • Extensible. Register your own operators and operator specs.

Requirements

Requirement Notes
Python 3.8+ (the code uses from __future__ import annotations)
PyTorch Required
NumPy Required
SymPy Required (expressions are parsed with it)
Triton Optional, enables fused kernels on CUDA
CUDA GPU Optional, fused kernels and CUDA graphs need it
h5py Optional, enables HDF5 I/O and out-of-core processing
MPI Optional, used by distributed mode if present

Triton is detected automatically by _triton_compat.py. If it is missing or unsupported (CPU-only machines, some operating systems), StenPy substitutes inert placeholders and uses its torch fallbacks. Set OPS_DISABLE_TRITON=1 to force this.

There is no packaging metadata in the repository yet, so installation is currently "put the files on your PYTHONPATH":

pip install torch numpy sympy          # core
pip install triton                     # optional, GPU fusion
pip install h5py                       # optional, HDF5 / out-of-core

Project layout

stenpy.py is the only public entry point. Everything else is private and can only be loaded as part of import stenpy.

File Role
stenpy.py Public API: fields, compute, compute_many, bind, I/O, configuration, errors
_stenpy_engine.py Core runtime: expression parsing, compute graph, Field, Graph, Runtime, operator registry
_stenpy_operator.py Operator specifications (OperatorSpec, StencilSpec, ReductionSpec, MatmulSpec, ElementwiseSpec, ...) and the built-in operator table
_fused_compiler.py Fusion compiler that generates and launches Triton kernels
_memory_manager.py Memory limits, hardware profiles, out-of-core streaming, distributed helpers
_stenpy_ai.py Autograd: differentiable compute, fused_vjp, rollout, graphed_value_and_grad, GraphedCallable
_stenpy_gemm.py Fused GEMM helpers: linear, mm, wgrad, compile
_triton_compat.py Optional-Triton shim (HAS_TRITON, triton, tl, on_triton)
_stenpy_gate.py Guard that stops private modules being imported directly
stenpy_demo.py Interactive demo server and headless benchmark (MRI, CT, stock/PDE and Navier-Stokes scenarios)

The front-door gate

Every private module calls require_front_door(__name__) as its first statement. If you do import _stenpy_engine directly, you get an immediate, explanatory ImportError telling you to import stenpy instead. As the module itself notes, this is a guard rail rather than a vault, since Python cannot make a module truly unimportable.


Quick start

import numpy as np
import stenpy

stenpy.info()   # prints version, device, fusion status, memory limit

# Wrap data in a Field, with grid spacing metadata
u = stenpy.field(np.random.rand(256, 256), spacing=0.1)

# Evaluate an expression
lap = stenpy.compute(u, "laplacian(u)", fields={"u": u})
# or, equivalently
lap = stenpy.compute("laplacian(u)", fields={"u": u}, boundary="periodic")

arr = stenpy.to_numpy(lap)

compute accepts either compute("expr", fields={...}) or compute(field, "expr", ...).

A time-stepping example (heat equation, explicit Euler):

import torch, stenpy

dt, nu = 1e-4, 0.1
u = torch.rand(512, 512, device="cuda", dtype=torch.float64)

step = f"u + {dt}*{nu}*laplacian(u)"
for _ in range(1000):
    u = stenpy.compute(step, fields={"u": u}, dx=1 / 512, boundary="periodic")

Passing torch tensors in returns torch tensors out, and passing Field objects returns Field objects.


How it works

Module architecture

flowchart TD
    user([Your code]) -->|import stenpy| front[stenpy.py<br/>public API]
    front --> engine[_stenpy_engine.py<br/>parser, graph, Field, Runtime]
    front --> ops[_stenpy_operator.py<br/>operator specs]
    front --> mem[_memory_manager.py<br/>limits, profiles, out-of-core, MPI]
    front -. lazy .-> ai[_stenpy_ai.py<br/>autograd, rollout, CUDA graphs]
    front -. lazy .-> gemm[_stenpy_gemm.py<br/>linear, mm, wgrad, compile]
    engine --> fused[_fused_compiler.py<br/>Triton kernel generator]
    engine --> ops
    fused --> ops
    fused --> triton[_triton_compat.py<br/>optional Triton shim]
    gemm --> triton
    gate[[_stenpy_gate.py<br/>front-door guard]] -.-> engine
    gate -.-> ops
    gate -.-> mem
    gate -.-> ai
    gate -.-> fused
    gate -.-> gemm
Loading

Solid arrows are imports or calls, dotted lazy arrows are modules loaded on first use, and the dotted lines from the gate show every private module checking that import stenpy happened first.

What happens when you call compute

flowchart TD
    A["compute('laplacian(u)', fields=...)"] --> B{Any input<br/>requires grad?}
    B -- yes --> AD[Differentiable path<br/>_stenpy_ai]
    B -- no --> C[Fold scalars, validate boundary,<br/>look up compile cache]
    C --> D{Cache hit?}
    D -- yes --> G
    D -- no --> E[Parse expression with SymPy<br/>check names and fields]
    E --> F[Build compute graph<br/>CSE shared sub-expressions]
    F --> G{Fits in memory?}
    G -- no --> OOC[Stream in tiles<br/>from HDF5 to HDF5]
    G -- yes --> H{CUDA + Triton<br/>+ fusible?}
    H -- yes --> K[One fused Triton kernel]
    H -- no --> V[Vendor / PyTorch fallback]
    K --> R[Result: Field, LazyField or tensor]
    V --> R
    OOC --> R
Loading

How bind() decides to use the fast path

flowchart LR
    S[bind expr, fields] --> T{CUDA device<br/>with Triton?}
    T -- no --> SLOW
    T -- yes --> U{Expression eligible<br/>for single kernel?}
    U -- no --> SLOW
    U -- yes --> W[Verify on a small crop<br/>against general path]
    W --> X{Matches and<br/>finite?}
    X -- no --> SLOW[Fall back to compute per call<br/>fast = False, reason logged]
    X -- yes --> FAST[Raw kernel launch<br/>fast = True]
Loading

With strict=True, every route into the fallback raises UnsupportedOperationError instead.


Performance

StenPy is benchmarked against torch.compile on 3-D grids (N^3 points) with five PDE-style expressions, plus sweeps over operator and field counts. All numbers below come from all_points.csv (1,118 measured points); the three plots are in docs/.

Short version: StenPy is far faster when a problem is small enough that launch overhead dominates, and statistically tied with torch.compile once the problem is large enough to be memory-bandwidth-bound. It also builds faster, and uses somewhat more VRAM at the largest sizes. On the end-to-end demo scenarios the engine stage is 1.8x to 3.5x faster than torch.compile and 17x to 27x faster than eager PyTorch.

Test setup

  • Expressions (stencil ops / elementary ops): diffusion (1 / 0), advection (3 / 5), burgers (4 / 7), vorticity_sq (6 / 8), ns_residual (18 / 39).
  • Size sweep: N increases step by step until free VRAM drops below 10 %. 10 repeats per point. Both backends use identical grids.
  • Operator-count sweep: fixed N = 512 (134,217,728 points), 0-100 operators, plus 0-5 distinct input fields.
  • Metric: per-evaluation time in ms (the ratio plots use the median).
  • Hardware, dtype and software versions are not recorded in the CSV. Add them here before publishing, for example: GPU model, driver / ROCm or CUDA version, PyTorch, Triton and StenPy versions, and precision. The out-of-memory message in the log is a HIP (ROCm) error, so the run appears to be on an AMD GPU.

Size scaling

Per-evaluation time vs grid size

StenPy / torch.compile time ratio vs grid size

Median speedup of StenPy over torch.compile (>1 means StenPy is faster), grouped by grid size:

Expression < 10^5 points 10^5 - 10^7 points >= 10^7 points Best single point Crossover to parity
diffusion 5.4x 1.5x 1.00x 5.7x ~11M points
advection 5.8x 1.1x 1.00x 6.3x ~2.4M points
burgers 5.6x 1.1x 1.00x 5.9x ~3.0M points
vorticity_sq 6.0x 1.1x 1.01x 6.7x ~4.4M points
ns_residual 5.3x 1.0x 1.00x 6.0x ~1.1M points

"Crossover" is the first size where StenPy's time reaches 97 % or more of torch.compile's. Below it StenPy is faster, above it the two are tied.

What the data says:

  • Small grids (up to ~10^5 points): about 5-6x faster. A StenPy evaluation costs roughly 3.4-3.9 microseconds regardless of expression, against roughly 20-23 microseconds for torch.compile. In this regime the time is almost entirely per-call overhead, which is what the single fused launch (and bind()) removes.
  • Mid-size grids (10^5 - 10^7 points): the advantage shrinks as real work starts to dominate. diffusion keeps its lead longest because it has only one stencil op.
  • Large grids (>= 10^7 points): parity. Geometric-mean time ratio over this range is 0.997 (diffusion), 0.999 (advection), 1.000 (burgers), 0.995 (vorticity_sq) and 0.993 (ns_residual). That is within about 1 % either way, and well within run-to-run noise on most points. Both backends are bandwidth-bound here, so there is nothing left for fusion to win.
  • Largest sizes reached: StenPy ran up to N = 1144 (diffusion) and N = 874-934 for the others before hitting the 10 % free-VRAM stop. torch.compile reached slightly larger grids in every case (N = 1184 for diffusion, where it ended in a true out-of-memory error, and N = 894-964 for the others).

Operator-count scaling at N = 512

Operator and field count scaling

Sweep StenPy / torch.compile time ratio Notes
Elementary ops (0-100) 0.988 - 0.997 Flat at ~1.77 ms for both. Differences are inside the error bars
Stencil ops (0-100) 0.954 - 1.001 Both rise from ~1.8 ms to ~9.6 ms by 25 ops, then plateau. StenPy is about 3-4 % faster beyond 25 ops
Mixed (stencil + 2 elementary per step) 0.938 - 1.007 Same shape as the stencil sweep, StenPy up to ~6 % faster on the plateau
Distinct input fields (0-5) 0.994 - 0.995 Both scale linearly, ~1.77 ms to ~5.4 ms

The plateau after ~25 stencil operators is a property of the benchmark, not of either compiler: the stencil taps repeat after 32 unique ones, so both compilers common-subexpression-eliminate the repeated loads and the cost stops growing. Read these sweeps as "fusion does not degrade as expressions get long", not as a claim about real 100-operator workloads.

Application benchmarks (demo scenarios)

End-to-end numbers from the four scenarios in stenpy_demo.py. "Whole frame" is the full per-frame cost. "Engine stage" is just the part StenPy replaces, and "shared stage" is work every backend performs identically (for example the filtered back-projection in CT), which is why whole-frame numbers move less than engine-stage numbers.

Scenario Backend Whole frame Engine stage Extra GPU mem
MRI (8 coils) (shared 0.434 ms) PyTorch eager 8.649 ms 8.208 ms 48.0 MB
torch.compile 1.336 ms 0.893 ms 10.4 MB
StenPy 0.927 ms 0.491 ms 12.4 MB
CT scan (shared 32.691 ms) PyTorch eager 43.341 ms 10.547 ms 18.0 MB
torch.compile 33.649 ms 0.972 ms 10.0 MB
StenPy 33.156 ms 0.462 ms 10.1 MB
Finance: live stock (shared 0 ms) PyTorch eager 20.823 ms 20.702 ms 0.0 MB
torch.compile 2.828 ms 2.828 ms 0.0 MB
StenPy 0.798 ms 0.798 ms 0.0 MB
Navier-Stokes (shared 3.290 ms) PyTorch eager 28.321 ms 25.014 ms 11.0 MB
torch.compile 5.742 ms 2.473 ms 7.0 MB
StenPy 4.170 ms 0.929 ms 13.1 MB

Speedup of StenPy (higher is better):

Scenario Whole frame vs eager Whole frame vs torch.compile Engine stage vs eager Engine stage vs torch.compile
MRI (8 coils) 9.3x 1.44x 16.7x 1.82x
CT scan 1.31x 1.01x 22.8x 2.10x
Finance: live stock 26.1x 3.54x 26.1x 3.54x
Navier-Stokes 6.8x 1.38x 26.9x 2.66x
xychart-beta
    title "Whole-frame time by backend (ms, lower is better)"
    x-axis ["MRI", "Finance", "Navier-Stokes"]
    y-axis "ms" 0 --> 30
    bar [8.649, 20.823, 28.321]
    bar [1.336, 2.828, 5.742]
    bar [0.927, 0.798, 4.170]
Loading

Bars in each group are PyTorch eager, torch.compile and StenPy, in that order. CT is left out of the chart because its 32 ms shared stage dominates every bar and hides the comparison, but its row in the tables above is real.

Reading these results:

  • The engine stage is where StenPy wins, at 1.8x to 3.5x over torch.compile and 17x to 27x over eager PyTorch. These are small, latency-bound kernels, the same regime where the size-scaling data shows the biggest gains.
  • The whole-frame gain depends on how much of the frame is the engine. Finance is 100 % engine, so it shows the full 3.5x. CT is dominated by a 32.7 ms shared stage, so a 2.1x faster engine moves the whole frame by only about 1 %.
  • Extra GPU memory is comparable, from 0 MB to 13 MB. StenPy uses slightly more than torch.compile in MRI (12.4 vs 10.4 MB) and Navier-Stokes (13.1 vs 7.0 MB), and about the same in CT.
  • Hardware, dtype and software versions for these runs aren't recorded either. Add them next to the size-scaling setup.

Build time and memory

StenPy torch.compile
Median build time per configuration (build_s) 0.81 s 1.24 s
Mean build time 1.5 s 5.5 s
Worst-case build time 7.5 s 110 s
VRAM in use, ns_residual at ~668M points 14.6 GB 13.5 GB
  • Build time is lower and, more importantly, much less spiky. The 110 s worst case for torch.compile is a single outlier, so treat the mean with care and prefer the median.
  • StenPy uses about 8 % more device memory than torch.compile at the largest ns_residual size. This is also why its sweeps stop slightly earlier under the 10 %-free-VRAM rule.

Caveats

  • Results are from one machine and one run. Treat differences under about 2 % at large sizes as noise.
  • Ratios at large N are close to 1.0 by construction (both are memory-bound), so the headline win is latency at small and medium sizes, not bandwidth at large sizes.
  • Typical workloads that benefit most are many small evaluations in a loop (time stepping, solver inner loops, per-slice processing, PDE residuals inside training), especially combined with bind().
  • Reproduce or extend the numbers from the raw data in all_points.csv.

Core API

Fields and conversion

Function Purpose
field(data, *, spacing, origin, device, copy) Wrap an array, tensor or Field. Returns a Field (or the LazyField unchanged)
from_numpy(array, ...) Same as field, but requires a numpy.ndarray
to_numpy(obj) / to_torch(obj) Convert a field, tensor or array back out
Field In-memory grid data plus spacing and origin metadata
LazyField Handle to an HDF5 dataset that stays on disk until needed

Fields must be real floating point (float16, float32 or float64). Integer and complex data are rejected with UnsupportedDTypeError. Spacing must be finite and positive, and empty or 0-d data is rejected.

Computing

compute(*args, fields=None, dx=None, boundary="periodic", device=None,
        chunk_size=None, chunk_dim=0, out=None, runtime=None)
Argument Meaning
fields Mapping from names used in the expression to arrays, tensors or Fields
dx Grid spacing. Taken from the primary Field if omitted
boundary One of the boundary modes
device "auto", "cpu", "cuda" or "cuda:N"
chunk_size, chunk_dim Process in chunks along a dimension
out Path to write the result to, for out-of-core runs
runtime Use a specific Runtime instead of the default one

Scalars in fields are folded into the expression as literals by default (STENPY_FOLD_SCALARS=0 disables this).

compute_many(exprs, *, fields, dx, boundary) evaluates several expressions that share inputs, ideally in one fused multi-output kernel, and returns a list of results. It falls back to evaluating them one at a time when fusion is not possible.

bind(expr, fields, dx, boundary, device, check, strict) resolves everything once and returns a Bound handle for repeated launches:

b = stenpy.bind("u + 0.01*laplacian(u)", {"u": u_tensor}, dx=0.01)
b()                    # relaunch, returns the (static) output tensor
b.replay()             # cheapest possible launch, no return
b(u=other_tensor)      # swap in another same-shape/dtype tensor by name
b.out                  # preallocated output, overwritten on each call
b.fast                 # True if the raw-launch path is active

bind needs a CUDA device with Triton. Otherwise it falls back to compute() per call (b.fast is False) and logs a warning, or raises UnsupportedOperationError if you pass strict=True. With check=True it verifies the fast path against the general path on a small crop of the data before trusting it.

Introspection

Function Returns
info(verbose=True) Prints and returns the capabilities summary
capabilities() Dict covering precision, CUDA, operator counts, fusion, out-of-core, distributed and memory state
memory_info(device) Current memory state
list_operators() Sorted names of executable operators
get_runtime() / reset_runtime() Access or reset the default Runtime
clear_compile_cache() Drop cached compiled expressions
version() / __version__ Version string

Operators

The built-in operator specifications are:

Family Operators
Stencil laplacian, gradient, gradient_nd, divergence, curl, jacobian, hessian, biharmonic
Reduction sum, mean, min_max, norm_l2, variance
Matrix matmul, linear, einsum
Spectral fft, ifft, spectral_gradient, spectral_laplacian
Linear algebra solve, inverse, eigenvalues, svd
Convolution conv_1d, conv_2d, conv_3d
Sorting and scans argmax, topk, sort, cumsum, cumprod
Utility select, scalar

Operators take keyword arguments inside the expression, for example gradient(u, dim=0). Elementwise functions such as relu also work in expressions, as in the demo's relu(V + ...).

Use stenpy.list_operators() to see exactly what is executable in your installation.

Which operators fuse into a single kernel is a property of each spec (Fusibility: elementwise, stencil, reduction, fp64). Fusion is CUDA and Triton only. On CPU, StenPy uses the vendor and fallback implementations.


Boundary conditions

Pass boundary= to compute, compute_many, bind or fused_vjp:

periodic (default), neumann, reflect, dirichlet, open

An unsupported value raises InvalidInputError.


Precision and memory

stenpy.set_precision("fp32")          # fp16 / fp32 / fp64
stenpy.get_precision()

stenpy.set_memory_limit("8GB")        # None, bytes, float, or string
stenpy.get_memory_limit()

stenpy.set_hardware_profile("...")    # preset name, or a HardwareProfile object
  • Precision. By default StenPy follows the floating-point dtype of the inputs (STENPY_FOLLOW_INPUT_DTYPE). If native fp32 execution fails for an expression, it logs a warning, remembers the expression, and recomputes in fp64 before casting back.
  • Memory limit. Lets you cap how much memory a computation may use. Computations that do not fit raise OutOfMemoryError or are streamed out-of-core, where supported.
  • Hardware profile. Tunes adaptive thresholds. A profile is detected automatically, or can be set by name or via the HardwareProfile class.

Out-of-core and HDF5

Requires h5py.

# Load (lazily if the array would not fit in memory)
f = stenpy.load("big.h5", dataset="field")             # lazy=None -> auto
f = stenpy.load("big.h5", lazy=True)                   # always a LazyField

# Stream a computation from disk to disk
stenpy.compute("laplacian(u)", fields={"u": f}, out="result.h5", chunk_size=64)

# Save with metadata
stenpy.save(field_obj, "out.h5", dataset="field", compression="gzip")

Datasets are expected to be real floating point. spacing and origin are read from the file (either as top-level datasets or as dataset attributes) when present, and default to 1.0 and 0.0 otherwise. If a file holds several datasets, pass dataset= explicitly.

Current limits of the out-of-core path: one on-disk input, one output, local (non-global) operators only. Global operators (such as reductions or FFTs) are not streamed. The STENPY_OOC_* variables tune tiling and chaining.


Autograd and differentiable simulation

If any input requires gradients, compute automatically switches to a differentiable path, so it works inside normal PyTorch autograd code. The differentiable path supports the boundary modes above but not streaming or custom runtimes (wrap those in torch.no_grad()).

u = torch.rand(128, 128, device="cuda", dtype=torch.float64, requires_grad=True)
loss = stenpy.compute("laplacian(u)", fields={"u": u}).pow(2).sum()
loss.backward()

Additional tools, loaded lazily from _stenpy_ai:

Function Purpose
fused_vjp(expr, fields, cotangent, *, dx, boundary, wrt) Fused vector-Jacobian product. Returns (output, {name: grad}), computing the forward expression and the adjoint expressions together via compute_many
rollout(step_fn, state, n_steps, params=(), segment=None, graph=None) Run step_fn for n_steps with segmented checkpointing, so memory scales roughly with sqrt(n_steps) instead of n_steps
graphed_value_and_grad(loss_fn, n_diff=1, warmup=2, clone_output=True) Returns a callable giving (loss, *grads), replayed through a captured CUDA graph after warmup
GraphedCallable The CUDA-graph replay wrapper used by the above

rollout is intended for differentiating through long time-stepping loops, for example fitting a PDE parameter. Field names beginning with the internal cotangent prefix are reserved.


Fused GEMM helpers

Available as stenpy.linear, stenpy.mm, stenpy.wgrad and stenpy.compile:

y = stenpy.linear(x, W, bias, activation="gelu")        # activation(x @ W.T + bias)
y = stenpy.mm(a, b, bias=bias, activation="relu")       # activation(op(a) @ op(b) + bias)
dW = stenpy.wgrad(x, dy, out=grad_buffer, bias=True)    # dW = dy^T @ x, accumulated in-GEMM
f = stenpy.compile(my_fn)                               # replay one captured CUDA graph per shape
  • Supported activations: relu, silu, gelu, tanh, sigmoid (or none).
  • 2-D operands use the fused path. Higher-rank operands use torch.matmul.
  • Dtypes: float16, bfloat16, float32, float64; tf32=True opts into TF32.
  • compile expects CUDA tensors passed positionally. Other inputs run the function eagerly.

Custom operators

from stenpy import StencilSpec, register_operator, register_spec, list_operators

stenpy.register_operator("my_op", my_callable, spec=my_spec, overwrite=False)
  • register_spec(spec) validates and registers an OperatorSpec (or subclass).
  • register_operator(name, func, *, spec=None, vendor=False, overwrite=False, **metadata) registers an executable implementation. Pass vendor=True to also register it as the vendor/fallback implementation. A name clash raises InvalidInputError unless overwrite=True.
  • Spec types: StencilSpec, ReductionSpec, MatmulSpec, ElementwiseSpec, BinaryElementwiseSpec.

Distributed execution

stenpy.dist_init(backend=None, dims=None)
stenpy.dist_rank(), stenpy.dist_size(), stenpy.is_distributed()
stenpy.decompose_field(...)

capabilities()["distributed"] reports the current state, including whether MPI is available. Only decomposition along axis 0 is validated.


Error handling

All public-layer errors derive from StenPyError, and most also derive from the matching built-in exception, so both styles of except work.

Exception Also a Raised when
InvalidInputError ValueError Bad argument, shape, boundary, device or spacing
MalformedExpressionError InvalidInputError Expression cannot be parsed or uses unknown names
UnsupportedOperationError ValueError The operator or feature is unavailable
UnsupportedDTypeError TypeError Non-float or unsupported dtype
UnsupportedEnvironmentError RuntimeError No CUDA, no h5py, and so on
OutOfMemoryError MemoryError Does not fit in the configured or available memory
FileFormatError OSError HDF5 file unreadable or no usable dataset

Backend exceptions that look like real bugs are deliberately not wrapped. They propagate unchanged.


Environment variables

Common ones are listed here. The code reads more of them for tuning and debugging, so search the sources for STENPY_ for the full list.

Variable Effect
OPS_DISABLE_TRITON 1/true/yes disables Triton and forces the torch fallback
STENPY_DIRECT 0 disables the single-kernel direct-launch path
STENPY_STRICT_FUSION 1 makes fusion failures errors instead of silent fallbacks
STENPY_FOLD_SCALARS 0 stops scalar inputs being inlined into expressions
STENPY_FOLLOW_INPUT_DTYPE Controls whether compute precision follows the input dtype
STENPY_NATIVE_PRECISION Controls native fp32 execution
STENPY_MULTI_OUTPUT 0 disables fused multi-output kernels in compute_many
STENPY_COMPILE_CACHE Compile-cache control
STENPY_TUNE_CACHE, STENPY_AUTOTUNE Autotuning behaviour and cache location
STENPY_CUDA_GRAPH, STENPY_ROLLOUT_GRAPH 0 disables CUDA-graph replay
STENPY_GRAPH_MAX_MB Size threshold for graph capture (default 12)
STENPY_GEMM GEMM path control
STENPY_OOC_* Out-of-core tiling and chaining
STENPY_DEBUG_COMPILE_DIR Dump generated kernels for inspection

Python logging uses the stenpy logger, so logging.getLogger("stenpy").setLevel(logging.DEBUG) shows fallback decisions and fast-path rejections.


Interactive demo

stenpy_demo.py is a self-contained demo and benchmark. It serves a small web UI and compares StenPy against PyTorch baselines on four scenarios:

Scenario What it shows
mri Multi-coil MRI simulation and reconstruction
ct Radon transform and filtered back-projection
stock Option pricing / volatility PDE on market return data
ns Navier-Stokes vorticity simulation
python stenpy_demo.py --scenario mri --device auto --port 8000
python stenpy_demo.py --scenario ns --ns-n 512 --headless --frames 200   # no server
python stenpy_demo.py --doctor                                           # diagnose environment / network

Useful options:

Flag Purpose
--scenario {mri,ct,stock,ns} Which scenario to run
--device auto, cpu, cuda
--n, --slices, --pde-n, --ns-n Problem sizes
--market-csv, --tickers Real market data for the stock scenario
--lazy Use lazy HDF5-style loading
--headless, --frames Run without the web server
--host, --port, --open Server binding and auto-open in a browser
--public, --public-url, --tunnel-name, --no-tunnel Expose through a cloudflared tunnel
--admin-key Admin key for the served app
--stenpy-path Add a directory to sys.path to locate StenPy
--doctor Run environment diagnostics

The demo binds to 127.0.0.1 by default. Only use --public or a non-local --host when you intend to expose it, and set an admin key if you do.


Design notes

  • One door in. stenpy.py re-exports everything public. Autograd (_stenpy_ai) and GEMM (_stenpy_gemm) modules are imported lazily on first attribute access, which keeps import stenpy light.
  • Compile once, launch many times. Expressions are parsed and compiled once and cached. bind() removes even the cache lookup and argument validation from the hot path.
  • Fast paths are verified. Direct single-kernel launches are checked against the general path on a small crop, and rejected (with a logged reason) if they disagree or produce non-finite output from finite input.
  • Fallbacks are explicit. Wherever StenPy declines a fast path, the reason is logged. STENPY_STRICT_FUSION=1 and bind(strict=True) turn silent fallbacks into errors, which is useful in benchmarking and CI.
  • Known limits. Fused kernels need CUDA and Triton. Out-of-core is limited to one on-disk input, one output and local operators. Distributed decomposition is validated on axis 0 only.

About

StenPy is a GPU‑accelerated field pipeline that turns symbolic expressions into production‑ready HPC workflows. If you can write gradient(f) + laplacian(g), StenPy can execute it on multi‑gigabyte volumetric data — in‑memory or streaming from disk.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages