Skip to main content

Serron

Mathematical Morphology module for PyTorch (CUDA and ROCm), providing differentiable operators and learnable network layers.

Install

One prebuilt wheel per platform covers every supported interpreter, on Linux (x86_64, aarch64) and Windows (x86_64, ARM64).

pip install serron

The kernels are built against PyTorch's stable C++ ABI, so a wheel loads on torch 2.13 and every later release (torch>=2.13) rather than only the minor it was compiled against. The wheel carries no CPython tag either, because the compiled libraries use no CPython API.

Wheels load on both CUDA and CPU-only torch builds; the CUDA kernels are only loaded when the installed torch has CUDA. The CUDA kernels work with a torch built against CUDA 12 or CUDA 13: they bind to the NVIDIA driver at runtime rather than linking a CUDA runtime, so the only requirement is a driver supporting CUDA 12.0 or newer (R525 / 525.60.13 on Linux, 528.33 on Windows).

On AMD GPUs (Linux x86_64), the wheel also carries a ROCm library, used when the installed torch is a ROCm 10 build. Kernel images are embedded for gfx90a, gfx942, gfx950, gfx1100 and gfx1201, plus a portable SPIR-V image that other architectures compile when the kernels load. The library links no HIP runtime; it uses the one torch already loaded. Set SERRON_ROCM_FORCE_SPIRV=1 to use the portable image even where a native one exists.

Backend Platforms Torch build Kernels
CUDA Linux (x86_64, aarch64), Windows (x86_64, ARM64) CUDA 12 or 13 native for compute capability 7.5 to 12.0, PTX for 12.0 and up
ROCm Linux (x86_64) ROCm 10 native for gfx90a, gfx942, gfx950, gfx1100, gfx1201; portable SPIR-V for the rest
CPU Linux, Windows any C++

Usage

Serron works on standard PyTorch tensors laid out as (N, C, H, W) and living on a CUDA, ROCm or CPU device (ROCm devices are also addressed as "cuda" in torch).

Functional operators

Stateless operators live in serron.functional and are re-exported at the top level. Each takes an input tensor, a structuring element, and an optional border mode:

import torch
import serron
from serron import BorderMode
from serron import structuring_element as se

x = torch.rand(1, 1, 256, 256, device="cuda")
kernel = se.disk(3, device="cuda")

eroded = serron.erosion(x, kernel)
dilated = serron.dilation(x, kernel)
opened = serron.opening(x, kernel)
closed = serron.closing(x, kernel)

# Derived operators
grad = serron.gradient(x, kernel)  # dilate(x) - erode(x)
white = serron.top_hat(x, kernel)  # x - open(x)
black = serron.black_hat(x, kernel)  # close(x) - x

# Control border handling
eroded_reflect = serron.erosion(x, kernel, border=BorderMode.REFLECT)

Available operators: erosion, dilation, opening, closing, gradient, top_hat, black_hat, reconstruction_by_dilation, reconstruction_by_erosion.

Geodesic reconstruction

reconstruction_by_dilation floods a marker outwards until it settles, held down by a mask at every step; reconstruction_by_erosion is its dual. Both iterate the compiled erode / dilate ops to a fixed point and default to BorderMode.CONSTANT, which is the geodesic reading of the image boundary.

marker = torch.zeros_like(x)
marker[..., 128, 128] = x[..., 128, 128]

with torch.no_grad():  # no backward pass yet
    flooded = serron.reconstruction_by_dilation(marker, x, se.cross(3, device="cuda"))

The loop runs on the device, but its convergence test reads one flag back to the host every check_every steps (16 by default). Raise it to trade a few wasted steps for fewer syncs.

Structuring elements

serron.structuring_element builds common SE shapes on the requested device:

from serron import structuring_element as se

se.square(5, device="cuda")  # (5, 5) full square
se.cross(5, device="cuda")  # (5, 5) plus shape
se.disk(3, device="cuda")  # (7, 7) disk, radius 3
se.diamond(3, device="cuda")  # (7, 7) diamond, radius 3
se.from_tensor(my_weights)  # wrap an arbitrary 2-D tensor as a grayscale SE

Border modes

BorderMode controls how out-of-bounds neighbors are handled:

Mode Behavior
BorderMode.REPLICATE Repeat the edge value (default)
BorderMode.REFLECT Mirror across the edge
BorderMode.CONSTANT Pad with a constant

Learnable layers

serron also exposes torch.nn.Module layers with a learnable structuring element, so morphology can be trained end-to-end inside a network. Each layer takes the number of channels and a kernel_size:

import torch
from serron import Erosion2d, Dilation2d, Opening2d, Closing2d
from serron import BorderMode

layer = Erosion2d(channels=3, kernel_size=5, border=BorderMode.REPLICATE).cuda()

x = torch.rand(8, 3, 64, 64, device="cuda")
y = layer(x)  # forward pass; layer.weight is a trainable (C, k, k) SE
y.sum().backward()  # gradients flow into layer.weight

Available layers: Erosion2d, Dilation2d, Opening2d, Closing2d.

Implementation

Every operator picks one of a few kernels at call time. The structuring element and the device's shared memory decide which one.

Which path runs

Path Runs when Cost per output
Separable van Herk–Gil–Werman Flat SE and max(kH, kW) >= SERRON_SEPARABLE_MIN_K O(1) in the window length
Tiled 2-D Otherwise, when the halo tile and the SE fit in shared memory O(kH × kW)
Element-wise Otherwise; reads through global memory (CUDA only) O(kH × kW)

SERRON_SEPARABLE_MIN_K is the window length where the separable path takes over. It accepts any positive integer. The default differs per backend because it marks where the separable path starts beating the 2-D one, and that point is not the same on both: 11 on CUDA, 5 on CPU, where there is no tiled 2-D kernel to soften the kH × kW window.

Calibrating for your GPU

The default window length is a compromise: where the separable path starts winning differs per GPU, dtype and between the forward and the backward pass. serron ships measured values for the architectures someone has calibrated (compute capability 12.0 so far), so those start out right. For any other GPU, or to measure your own, serron.calibrate() times it on the GPU in front of you:

import serron

serron.calibrate()

The result applies to the running process and is saved under $SERRON_CACHE_DIR (default ~/.cache/serron), keyed by GPU, CUDA version and serron version. Later processes load it on their first CUDA op, so calibrate() only has to run once. Pass force=True to measure again, or dtypes=[...] to choose the element types. What applies, in order: SERRON_SEPARABLE_MIN_K, then what calibrate() saved on this machine, then the shipped values for the GPU's compute capability, then the built-in default of 11 (5 on CPU).

Tuning for shapes

calibrate() moves one threshold. To time every algorithm, warm them up ahead of time:

serron.autotune(shapes=[(8, 3, 512, 512), (16, 3, 1024, 1024)], ks=[7, 15, 31])

Each combination of shape, window length, dtype and structuring-element kind is timed forward and backward on scratch tensors, so none of your tensors are touched. A winner replaces the built-in choice only where it is at least 5% faster. A tuning also serves shapes within a factor of two in N*C*H*W, and inputs of up to 65536 elements (1x1x256x256) are left to the built-in choice because they are bound by launch latency. Results are saved with the calibration and loaded on the first CUDA op of a later process. Nothing is ever tuned while a CUDA graph is being captured.

SERRON_AUTOTUNE controls this:

Value Effect
unset Load saved results; never tune on its own
1 Also tune a problem the first time it is seen. That one call pays for it (about 0.2–0.6 s)
0 Ignore saved and shipped results and use the built-in choice

The separable path

Splitting a flat kH × kW window into a 1 × kW row pass and a kH × 1 column pass already drops the per-pixel work from kH × kW to kH + kW, and the Van Herk–Gil–Werman algorithm drops it further to a constant three operations per ouput, no matter the sequence length.

On CUDA both scans sit in shared memory. A chunk at least a warp wide gets a warp to itself and the lanes cooperate through shuffles; anything shorter gets a single thread. On CPU the lines go through at::parallel_for.

Backward

Backward needs to know where the winning sample was, not just what it was, so its scans carry a (value, offset) pair rather than a bare value. Combining two of those keeps the lower offset on a tie, which is the rule the direct kernel gets from its strict-improvement loop — reproducing it exactly is what makes the two paths agree on which tap receives the gradient. The window is one pair-combine as before, so the search is O(1) in the window length on both the row and the column pass.

It splits on the same condition: a separable row and column argreduce for a flat SE at or above the threshold, and a direct recompute of the winning tap otherwise. The direct recompute stages its window in shared memory the same way the forward's tiled path does.

Benchmarks

Per-operator throughput and the cross-library comparison live in benchmarks/README.md.

Erosion with a flat SE, 8x3x512x512 float32 on an H100 PCIe (with Intel Xeon Platinum 8480+), in milliseconds:

k serron PyTorch Kornia CuPy SciPy (CPU)
7 0.30 0.42 2.80 0.20 159
31 0.23 5.46 41.87 0.58 151
63 0.31 21.48 OOM 1.05 144
127 0.25 81.03 OOM 2.00 142

Building from source

Clone repo

git clone git@github.com:vhrabar/serron.git
cd serron

Choosing a torch build

torch is pulled from a specific wheel index via mutually-exclusive dependency groups, one per backend and end of the supported range: cu132 / cpu at the oldest torch the kernels target, cu132-newest / cpu-newest at the current release. Only dev is enabled by default, so a torch group is always chosen explicitly. cu134 (x86_64 and AMD64) and the rocm-<arch> groups (Linux x86_64, one per GPU architecture) follow the same rule. --no-default-groups keeps the command independent of whatever is enabled by default:

uv sync --no-default-groups --group dev --group cu132-newest # CUDA, newest torch
uv sync --no-default-groups --group dev --group cpu-newest # CPU-only, newest torch
uv sync --no-default-groups --group dev --group cu132      # CUDA, oldest supported torch
uv sync --no-default-groups --group dev --group cpu        # CPU-only, oldest supported torch

On Windows on ARM, the cu134-win-arm64 group pulls NVIDIA's +cu134 torch wheels from https://pypi.nvidia.com/nvtorch_oot/.

uv sync --no-default-groups --group dev --group cu134-win-arm64 # Windows on ARM, CUDA 13.4

On Linux x86_64, AMD GPUs use rocm-<arch code> groups: rocm-gfx90a, rocm-gfx942, rocm-gfx950, rocm-gfx1036, rocm-gfx1100, rocm-gfx1201.

Building the wheel

Building the CUDA extension from source needs the CUDA 13.X toolkit (nvcc):

uv sync --no-install-workspace
uv build --package serron --wheel --no-build-isolation

The ROCm library is built next to it whenever hipcc is found, the same way the CUDA one needs nvcc: from SERRON_ROCM_ROOT, ROCM_PATH or HIP_PATH, else on PATH. Pass -DSERRON_ROCM=OFF to skip it. No GPU is needed to build. Use ROCm 10.0's hipcc (the rocm-sdk-core==10.0.* pip package works): the compiler must not be newer than the ROCm runtime that loads the portable image, and torch's ROCm 10 wheels bring 10.0. SERRON_ROCM_ARCHS sets the native architecture list:

CMAKE_ARGS="-DSERRON_ROCM_ARCHS=gfx942;gfx1100" uv build --package serron --wheel --no-build-isolation
scripts/check_rocm_linkage.sh dist/serron-*.whl

On a GPU-less machine, sync the CPU torch build instead; the extension then builds C++ only (no nvcc or hipcc required):

uv sync --no-install-workspace --no-default-groups --group dev --group cpu-newest
uv build --package serron --wheel --no-build-isolation

License

MIT

Copyright © 2026 Vedran Hrabar.

Metadata

Release files for serron 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for serron 0.6.0
File Size Uploaded Provenance Actions
serron-0.6.0.tar.gz 84.4 kB With provenance Details for serron-0.6.0.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for serron 0.6.0
File Actions
serron-0.6.0-py3-none-win_arm64.whl Python 3 none Windows ARM64 Details for serron-0.6.0-py3-none-win_arm64.whl
serron-0.6.0-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for serron-0.6.0-py3-none-win_amd64.whl
serron-0.6.0-py3-none-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl Python 3 none Linux glibc 2.28+ x86-64, Linux glibc 2.24+ x86-64 Details for serron-0.6.0-py3-none-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
serron-0.6.0-py3-none-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl Python 3 none Linux glibc 2.24+ ARM64, Linux glibc 2.28+ ARM64 Details for serron-0.6.0-py3-none-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl

Total release size: 18.4 MB

Release files / serron-0.6.0.tar.gz

Download URL serron-0.6.0.tar.gz
Size 84.4 kB
Tags Source
SHA-256 checksum
How to use checksums
36f98440a96af99d9c8e64776419688b8741a8bf6b28e8d0affb0dc4ccd2dac5
BLAKE2b-256 checksum
How to use checksums
7cd271a9b2a119a767f85c93f4b1104d24e3cb0a6109a22a76c3b55542f36616
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / serron-0.6.0-py3-none-win_arm64.whl

Download URL serron-0.6.0-py3-none-win_arm64.whl
Size 2.4 MB
Tags Python 3 Windows ARM64
SHA-256 checksum
How to use checksums
365f9186e9b20869b2070242385e0b5a9e845e470df21c34151164cbdc6504ec
BLAKE2b-256 checksum
How to use checksums
6b0d774f0aac394def9876b82202916169e5436e41b0a6e1565a1441ef1a25e1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / serron-0.6.0-py3-none-win_amd64.whl

Download URL serron-0.6.0-py3-none-win_amd64.whl
Size 5.0 MB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
58b5b8e2d13cf4124f90835ef52847e70b230aad3706cab85cd1d9b273d486b1
BLAKE2b-256 checksum
How to use checksums
340ddaa239ba15eb0be95128e3addc2027c80d2fb6900874c80cd3be5d6f86dc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / serron-0.6.0-py3-none-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl

Download URL serron-0.6.0-py3-none-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Size 5.8 MB
Tags Linux glibc 2.24+ x86-64 Linux glibc 2.28+ x86-64 Python 3
SHA-256 checksum
How to use checksums
c96a02d56c9945d05c5e4bdd42e5812b01c3e39fa4f2bd7122349b1f0a993833
BLAKE2b-256 checksum
How to use checksums
0027a3f5de9c4760f9c1edc286942e87b405efd9cd44c54a6816bf87c6d8b5b7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / serron-0.6.0-py3-none-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl

Download URL serron-0.6.0-py3-none-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl
Size 5.1 MB
Tags Linux glibc 2.24+ ARM64 Linux glibc 2.28+ ARM64 Python 3
SHA-256 checksum
How to use checksums
645eb144201308adfc811fad93c28016092af0bda74a04e01437d4103d97f3c0
BLAKE2b-256 checksum
How to use checksums
eabcff842a4d4fe3566270aba4b17a05835d283d6838611eff0eea1f87e68bd6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for serron 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 5 files in this release have been uploaded with provenance metadata.

Select from 5 files

Attestation for serron-0.6.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page