serron 0.5.0__py3-none-win_amd64.whl

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.
bin/_C.dll ADDED
Binary file
bin/_C_cuda.dll ADDED
Binary file
serron/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ """
2
+ Serron: CUDA-accelerated mathematical morphology for PyTorch.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from importlib.metadata import PackageNotFoundError
8
+ from importlib.metadata import version as _version
9
+
10
+ from . import functional, structuring_element
11
+ from .enums import BorderMode, Operation
12
+ from .functional import (
13
+ black_hat,
14
+ closing,
15
+ dilation,
16
+ erosion,
17
+ gradient,
18
+ opening,
19
+ reconstruction_by_dilation,
20
+ reconstruction_by_erosion,
21
+ top_hat,
22
+ )
23
+ from .modules import Closing2d, Dilation2d, Erosion2d, Opening2d
24
+
25
+ try:
26
+ __version__ = _version("serron")
27
+ except PackageNotFoundError:
28
+ __version__ = "0.0.0+unknown"
29
+
30
+ __all__ = [
31
+ "BorderMode",
32
+ "Closing2d",
33
+ "Dilation2d",
34
+ "Erosion2d",
35
+ "Opening2d",
36
+ "Operation",
37
+ "__version__",
38
+ "black_hat",
39
+ "closing",
40
+ "dilation",
41
+ "erosion",
42
+ "functional",
43
+ "gradient",
44
+ "opening",
45
+ "reconstruction_by_dilation",
46
+ "reconstruction_by_erosion",
47
+ "structuring_element",
48
+ "top_hat",
49
+ ]
serron/_build_info.py ADDED
@@ -0,0 +1,11 @@
1
+ """
2
+ Build-time facts about the compiled extension, generated by CMake.
3
+ """
4
+
5
+ TORCH_TARGET_VERSION = "2.13"
6
+
7
+ TORCH_VERSION = "2.14.1"
8
+
9
+ WITH_CUDA = True
10
+
11
+ STABLE_ABI = True
serron/_cmake_ops.py ADDED
@@ -0,0 +1,142 @@
1
+ """
2
+ Op-namespace loader for the local CMake / PyPI build.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import glob
8
+ import importlib
9
+ import os
10
+ import sys
11
+ from typing import Protocol, cast
12
+
13
+ import torch
14
+
15
+ _NAMESPACE = "serron"
16
+
17
+
18
+ def _search_dirs() -> list[str]:
19
+ dirs = [os.path.dirname(__file__)]
20
+ pkg = sys.modules.get(_NAMESPACE)
21
+ if pkg is not None:
22
+ dirs.extend(getattr(pkg, "__path__", ()))
23
+ return list(dict.fromkeys(dirs))
24
+
25
+
26
+ def _find_library(stem: str) -> str | None:
27
+ for pkg_dir in _search_dirs():
28
+ for pattern in (f"{stem}.*so", f"{stem}.*pyd", f"{stem}.*dll"):
29
+ matches = glob.glob(os.path.join(pkg_dir, pattern))
30
+ if matches:
31
+ return matches[0]
32
+ return None
33
+
34
+
35
+ def _release(version: str) -> tuple[int, ...]:
36
+ """``(major, minor, micro)`` of ``version``, ignoring any local or pre-release suffix."""
37
+ head = version.split("+")[0]
38
+ parts: list[int] = []
39
+ for part in head.split(".")[:3]:
40
+ digits = "".join(c for c in part if c.isdigit())
41
+ if not digits:
42
+ break
43
+ parts.append(int(digits))
44
+ return tuple(parts)
45
+
46
+
47
+ class _BuildInfo(Protocol):
48
+ TORCH_TARGET_VERSION: str
49
+ TORCH_VERSION: str
50
+ STABLE_ABI: bool
51
+
52
+
53
+ def _build_info() -> _BuildInfo | None:
54
+ # Generated by CMake, so absent when running from a bare source tree.
55
+ try:
56
+ return cast("_BuildInfo", importlib.import_module(f"{__package__}._build_info"))
57
+ except ImportError:
58
+ return None
59
+
60
+
61
+ def _load(path: str) -> None:
62
+ info = _build_info()
63
+ built_for = info.TORCH_VERSION if info is not None else None
64
+ try:
65
+ torch.ops.load_library(path)
66
+ except OSError as exc:
67
+ raise ImportError(
68
+ f"Could not load the compiled Serron extension {os.path.basename(path)} "
69
+ f"(built against torch {built_for or 'unknown'}, installed torch is {torch.__version__}): {exc}"
70
+ ) from exc
71
+
72
+
73
+ def _check_torch_version() -> None:
74
+ """
75
+ Reject a torch too old for this build.
76
+
77
+ Built against the stable ABI, the extension loads on its target version and every later one, so the bound is
78
+ one-sided. Without it the extension is tied to the exact minor it was compiled against, because the torch C++
79
+ ABI changes between minor releases.
80
+ """
81
+ info = _build_info()
82
+ if info is None:
83
+ return
84
+
85
+ if not info.STABLE_ABI:
86
+ if _release(info.TORCH_VERSION)[:2] != _release(torch.__version__)[:2]:
87
+ raise ImportError(
88
+ f"Serron was built against torch {info.TORCH_VERSION}, but torch {torch.__version__} is "
89
+ f"installed, and this build does not target the stable ABI. The torch C++ ABI changes between "
90
+ f"minor releases: install a matching torch, or rebuild Serron against the installed one."
91
+ )
92
+ return
93
+
94
+ target = info.TORCH_TARGET_VERSION
95
+ if _release(torch.__version__) < _release(target):
96
+ raise ImportError(
97
+ f"Serron needs torch {target} or newer, but torch {torch.__version__} is installed. "
98
+ f"Upgrade torch, or rebuild Serron from source against the installed version."
99
+ )
100
+
101
+
102
+ def _load_c_extension() -> None:
103
+ _check_torch_version()
104
+
105
+ cpu_lib = _find_library("_C")
106
+ if cpu_lib is None:
107
+ raise ImportError(
108
+ f"Could not find the compiled Serron '_C' extension in {_search_dirs()}. Reinstall the package so the kernels are built."
109
+ )
110
+ _load(cpu_lib)
111
+
112
+ cuda_lib = _find_library("_C_cuda")
113
+ if cuda_lib is not None and torch.version.cuda is not None:
114
+ _load(cuda_lib)
115
+
116
+
117
+ # autocast per device type
118
+ _AUTOCAST_DTYPES = {"cuda": torch.float16, "cpu": torch.bfloat16}
119
+
120
+ # FWD -> takes path, BWD -> gets from fwd
121
+ _AUTOCAST_OPS = ("erode", "dilate")
122
+
123
+
124
+ def _register_autocast() -> None:
125
+ """
126
+ Make the operators participate in ``torch.autocast``.
127
+
128
+ The stable ABI has no equivalent of ``at::autocast``, so the ops are registered with the dispatcher instead.
129
+ """
130
+ for device_type, dtype in _AUTOCAST_DTYPES.items():
131
+ for op in _AUTOCAST_OPS:
132
+ torch.library.register_autocast(f"{_NAMESPACE}::{op}", device_type, dtype)
133
+
134
+
135
+ _load_c_extension()
136
+ _register_autocast()
137
+
138
+ ops = getattr(torch.ops, _NAMESPACE)
139
+
140
+
141
+ def add_op_namespace_prefix(op_name: str) -> str:
142
+ return f"{_NAMESPACE}::{op_name}"
serron/_flatness.py ADDED
@@ -0,0 +1,40 @@
1
+ """
2
+ Flatness of a structuring element, remembered per tensor.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import torch
8
+ from torch.utils.weak import WeakTensorKeyDictionary
9
+
10
+ # caching mapping
11
+ _cache: WeakTensorKeyDictionary = WeakTensorKeyDictionary()
12
+
13
+
14
+ def is_flat(kernel: torch.Tensor) -> bool:
15
+ """
16
+ Whether ``kernel`` is flat and staus is unknown
17
+
18
+ :param kernel: structuring-element tensor.
19
+ :returns: ``True`` when every entry is ``0``.
20
+ """
21
+ cached: tuple[int, bool] | None = _cache.get(kernel)
22
+ version: int = kernel._version
23
+ if cached is not None and cached[0] == version:
24
+ return cached[1]
25
+
26
+ flat = bool(kernel.eq(0).all().item())
27
+ _cache[kernel] = (version, flat)
28
+ return flat
29
+
30
+
31
+ def mark(kernel: torch.Tensor, flat: bool) -> torch.Tensor:
32
+ """
33
+ Record AKAOT answer for ``kernel``, so the first use does not measure it.
34
+
35
+ :param kernel: structuring-element tensor.
36
+ :param flat: whether every entry is ``0``.
37
+ :returns: ``kernel``, to allow use in a return statement.
38
+ """
39
+ _cache[kernel] = (kernel._version, flat)
40
+ return kernel
serron/autograd.py ADDED
@@ -0,0 +1,103 @@
1
+ """
2
+ Autograd wrapper around the compiled serron CUDA kernels.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import override
8
+
9
+ import torch
10
+
11
+ from . import _flatness
12
+ from ._cmake_ops import add_op_namespace_prefix, ops
13
+
14
+ __all__ = ["_DilateFunction", "_ErodeFunction", "add_op_namespace_prefix", "ops"]
15
+
16
+
17
+ def _match_dtype(input_: torch.Tensor, kernel: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
18
+ """
19
+ Cast ``input_`` and ``kernel`` to their common floating dtype.
20
+
21
+
22
+ :param input_: image tensor.
23
+ :param kernel: structuring-element tensor.
24
+ :returns: ``(input_, kernel)`` sharing ``torch.promote_types(input_.dtype, kernel.dtype)``.
25
+ """
26
+ compute_dtype = torch.promote_types(input_.dtype, kernel.dtype)
27
+ return input_.to(compute_dtype), kernel.to(compute_dtype)
28
+
29
+
30
+ class _ErodeFunction(torch.autograd.Function):
31
+ """Autograd binding for ``serron::erode`` / ``serron::erode_backward``."""
32
+
33
+ @staticmethod
34
+ @override
35
+ def forward( # pyrefly: ignore[bad-override]
36
+ ctx: torch.autograd.function.FunctionCtx, input_: torch.Tensor, kernel: torch.Tensor, border: int
37
+ ) -> torch.Tensor:
38
+ flat = _flatness.is_flat(kernel)
39
+ input_, kernel = _match_dtype(input_, kernel)
40
+ ctx.save_for_backward(input_, kernel)
41
+ ctx.border = border # type: ignore[attr-defined]
42
+ ctx.flat = flat # type: ignore[attr-defined]
43
+ result: torch.Tensor = ops.erode(input_, kernel, border, flat)
44
+ return result
45
+
46
+ @staticmethod
47
+ @override
48
+ def backward( # pyrefly: ignore[bad-override]
49
+ ctx: torch.autograd.function.FunctionCtx, grad_output: torch.Tensor
50
+ ) -> tuple[torch.Tensor | None, torch.Tensor | None, None]:
51
+ needs_input, needs_kernel = ctx.needs_input_grad[:2] # type: ignore[attr-defined]
52
+ if not (needs_input or needs_kernel):
53
+ return None, None, None
54
+
55
+ input_, kernel = ctx.saved_tensors # type: ignore[attr-defined]
56
+ grad_output = grad_output.to(input_.dtype).contiguous()
57
+ grad_input, grad_kernel = ops.erode_backward(
58
+ grad_output,
59
+ input_,
60
+ kernel,
61
+ ctx.border, # type: ignore[attr-defined]
62
+ ctx.flat, # type: ignore[attr-defined]
63
+ needs_kernel,
64
+ )
65
+ return (grad_input if needs_input else None), (grad_kernel if needs_kernel else None), None
66
+
67
+
68
+ class _DilateFunction(torch.autograd.Function):
69
+ """Autograd binding for ``serron::dilate`` / ``serron::dilate_backward``."""
70
+
71
+ @staticmethod
72
+ @override
73
+ def forward( # pyrefly: ignore[bad-override]
74
+ ctx: torch.autograd.function.FunctionCtx, input_: torch.Tensor, kernel: torch.Tensor, border: int
75
+ ) -> torch.Tensor:
76
+ flat = _flatness.is_flat(kernel)
77
+ input_, kernel = _match_dtype(input_, kernel)
78
+ ctx.save_for_backward(input_, kernel)
79
+ ctx.border = border # type: ignore[attr-defined]
80
+ ctx.flat = flat # type: ignore[attr-defined]
81
+ result: torch.Tensor = ops.dilate(input_, kernel, border, flat)
82
+ return result
83
+
84
+ @staticmethod
85
+ @override
86
+ def backward( # pyrefly: ignore[bad-override]
87
+ ctx: torch.autograd.function.FunctionCtx, grad_output: torch.Tensor
88
+ ) -> tuple[torch.Tensor | None, torch.Tensor | None, None]:
89
+ needs_input, needs_kernel = ctx.needs_input_grad[:2] # type: ignore[attr-defined]
90
+ if not (needs_input or needs_kernel):
91
+ return None, None, None
92
+
93
+ input_, kernel = ctx.saved_tensors # type: ignore[attr-defined]
94
+ grad_output = grad_output.to(input_.dtype).contiguous()
95
+ grad_input, grad_kernel = ops.dilate_backward(
96
+ grad_output,
97
+ input_,
98
+ kernel,
99
+ ctx.border, # type: ignore[attr-defined]
100
+ ctx.flat, # type: ignore[attr-defined]
101
+ needs_kernel,
102
+ )
103
+ return (grad_input if needs_input else None), (grad_kernel if needs_kernel else None), None
serron/enums.py ADDED
@@ -0,0 +1,39 @@
1
+ """
2
+ Enumerations shared across the morphology ops and layers.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from enum import Enum
8
+
9
+
10
+ class Operation(Enum):
11
+ """
12
+ Morphological operations
13
+ """
14
+
15
+ ERODE = "erode"
16
+ DILATE = "dilate"
17
+ OPEN = "open"
18
+ CLOSE = "close"
19
+ GRADIENT = "gradient"
20
+ TOP_HAT = "top_hat"
21
+ BLACK_HAT = "black_hat"
22
+
23
+
24
+ class BorderMode(Enum):
25
+ """
26
+ OuB neighborhood border mode.
27
+ """
28
+
29
+ REFLECT = "reflect"
30
+ REPLICATE = "replicate"
31
+ CONSTANT = "constant"
32
+
33
+
34
+ BORDER_TO_INT: dict[BorderMode, int] = {
35
+ BorderMode.REFLECT: 0,
36
+ BorderMode.REPLICATE: 1,
37
+ BorderMode.CONSTANT: 2,
38
+ }
39
+ """Encoding of :class:`BorderMode` the compiled ops take as their ``border`` argument."""
serron/functional.py ADDED
@@ -0,0 +1,281 @@
1
+ """
2
+ Stateless morphological operations backed by the CUDA kernels.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import torch
8
+
9
+ from . import _flatness
10
+ from ._cmake_ops import ops
11
+ from .autograd import _DilateFunction, _ErodeFunction
12
+ from .enums import BORDER_TO_INT, BorderMode
13
+
14
+
15
+ def erosion(input_: torch.Tensor, kernel: torch.Tensor, *, border: BorderMode = BorderMode.REPLICATE) -> torch.Tensor:
16
+ """
17
+ Grayscale erosion (sliding minimum) of ``input`` by ``kernel``
18
+ :param input_: input tensor
19
+ :param kernel: kernel tensor
20
+ :param border: border mode
21
+ :return: eroded tensor
22
+ """
23
+ result: torch.Tensor = _ErodeFunction.apply(input_, kernel, BORDER_TO_INT[border])
24
+ return result
25
+
26
+
27
+ def dilation(input_: torch.Tensor, kernel: torch.Tensor, *, border: BorderMode = BorderMode.REPLICATE) -> torch.Tensor:
28
+ """
29
+ Grayscale dilation (sliding maximum) of ``input`` by ``kernel``
30
+ :param input_: input tensor
31
+ :param kernel: kernel tensor
32
+ :param border: border mode
33
+ :return: dilated tensor
34
+ """
35
+ result: torch.Tensor = _DilateFunction.apply(input_, kernel, BORDER_TO_INT[border])
36
+ return result
37
+
38
+
39
+ def opening(input_: torch.Tensor, kernel: torch.Tensor, *, border: BorderMode = BorderMode.REPLICATE) -> torch.Tensor:
40
+ """
41
+ Opening: erosion followed by dilation.
42
+ :param input_: input tensor
43
+ :param kernel: kernel tensor
44
+ :param border: border mode
45
+ :return: top-hat tensor
46
+ """
47
+ return dilation(erosion(input_, kernel, border=border), kernel, border=border)
48
+
49
+
50
+ def closing(input_: torch.Tensor, kernel: torch.Tensor, *, border: BorderMode = BorderMode.REPLICATE) -> torch.Tensor:
51
+ """
52
+ "Closing: dilation followed by erosion.
53
+ :param input_: input tensor
54
+ :param kernel: kernel tensor
55
+ :param border: border mode
56
+ :return: top-hat tensor
57
+ """
58
+ return erosion(dilation(input_, kernel, border=border), kernel, border=border)
59
+
60
+
61
+ def gradient(input_: torch.Tensor, kernel: torch.Tensor, *, border: BorderMode = BorderMode.REPLICATE) -> torch.Tensor:
62
+ """
63
+ Morphological gradient: ``dilate(input) - erode(input)``.
64
+ :param input_: input tensor
65
+ :param kernel: kernel tensor
66
+ :param border: border mode
67
+ :return: top-hat tensor
68
+ """
69
+ return dilation(input_, kernel, border=border) - erosion(input_, kernel, border=border)
70
+
71
+
72
+ def top_hat(input_: torch.Tensor, kernel: torch.Tensor, *, border: BorderMode = BorderMode.REPLICATE) -> torch.Tensor:
73
+ """
74
+ White top-hat: ``input - open(input)``
75
+ :param input_: input tensor
76
+ :param kernel: kernel tensor
77
+ :param border: border mode
78
+ :return: top-hat tensor
79
+ """
80
+ return input_ - opening(input_, kernel, border=border)
81
+
82
+
83
+ def black_hat(input_: torch.Tensor, kernel: torch.Tensor, *, border: BorderMode = BorderMode.REPLICATE) -> torch.Tensor:
84
+ """
85
+ Black top-hat: ``close(input) - input``
86
+ :param input_: input tensor
87
+ :param kernel: kernel tensor
88
+ :param border: border mode
89
+ :return: top-hat tensor
90
+ """
91
+ return closing(input_, kernel, border=border) - input_
92
+
93
+
94
+ _DEFAULT_CHECK_EVERY = 16
95
+
96
+
97
+ def _align_inputs(
98
+ marker: torch.Tensor, mask: torch.Tensor, kernel: torch.Tensor, name: str
99
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, bool]:
100
+ """
101
+ Check the three tensors a reconstruction runs on and bring them to one dtype.
102
+
103
+ :param marker: propagation seed, shape ``(N, C, H, W)``.
104
+ :param mask: tensor constraining the propagation, same shape as ``marker``.
105
+ :param kernel: structuring element, ``(kH, kW)`` or ``(C, kH, kW)``.
106
+ :param name: qualified caller name used to prefix diagnostics.
107
+ :return: ``(marker, mask, kernel)`` sharing a dtype, plus whether ``kernel`` is flat.
108
+ :raises ValueError: if the shapes or devices disagree.
109
+ :raises RuntimeError: if autograd is live and one of the inputs wants a gradient.
110
+ """
111
+ if marker.shape != mask.shape:
112
+ raise ValueError(f"{name}: marker and mask must share a shape, got {tuple(marker.shape)} and {tuple(mask.shape)}")
113
+ if marker.device != mask.device or marker.device != kernel.device:
114
+ raise ValueError(
115
+ f"{name}: marker, mask and kernel must be on one device, got {marker.device}, {mask.device} and {kernel.device}"
116
+ )
117
+ if torch.is_grad_enabled() and (marker.requires_grad or mask.requires_grad or kernel.requires_grad):
118
+ raise RuntimeError(f"{name}: reconstruction has no backward pass yet; run it under torch.no_grad() or detach its inputs")
119
+
120
+ compute_dtype = torch.promote_types(torch.promote_types(marker.dtype, mask.dtype), kernel.dtype)
121
+ # Read flatness off the caller's kernel, so a cast does not throw away a cached answer.
122
+ flat = _flatness.is_flat(kernel)
123
+ return marker.to(compute_dtype), mask.to(compute_dtype), _flatness.mark(kernel.to(compute_dtype), flat), flat
124
+
125
+
126
+ def _require_nonnegative_anchor(kernel: torch.Tensor, name: str) -> None:
127
+ """
128
+ Reject a structuring element that would let a geodesic step move the wrong way.
129
+
130
+ :param kernel: structuring element, ``(kH, kW)`` or ``(C, kH, kW)``.
131
+ :param name: qualified caller name used to prefix diagnostics.
132
+ :raises ValueError: if any channel's anchor tap is negative or NaN.
133
+ """
134
+ anchor_h, anchor_w = kernel.shape[-2] // 2, kernel.shape[-1] // 2
135
+ anchor = kernel[..., anchor_h, anchor_w]
136
+ if not bool((anchor >= 0).all().item()):
137
+ raise ValueError(
138
+ f"{name}: the structuring element's anchor tap kernel[..., {anchor_h}, {anchor_w}] must be >= 0, "
139
+ f"otherwise the geodesic iteration is not monotone and need not converge"
140
+ )
141
+
142
+
143
+ def _reconstruct(
144
+ marker: torch.Tensor,
145
+ mask: torch.Tensor,
146
+ kernel: torch.Tensor,
147
+ border: BorderMode,
148
+ *,
149
+ dilate: bool,
150
+ max_iter: int | None,
151
+ check_every: int,
152
+ name: str,
153
+ ) -> torch.Tensor:
154
+ """
155
+ Iterate a geodesic step to its fixed point.
156
+
157
+ :param marker: propagation seed, shape ``(N, C, H, W)``.
158
+ :param mask: tensor constraining the propagation, same shape as ``marker``.
159
+ :param kernel: structuring element, ``(kH, kW)`` or ``(C, kH, kW)``.
160
+ :param border: boundary mode for out-of-image reads.
161
+ :param dilate: ``True`` to reconstruct by dilation, ``False`` by erosion.
162
+ :param max_iter: iteration budget, or ``None`` to run until the fixed point.
163
+ :param check_every: how many steps to run between convergence tests.
164
+ :param name: qualified caller name used to prefix diagnostics.
165
+ :return: the reconstruction, same shape as ``marker`` and dtype promoted across the inputs.
166
+ :raises ValueError: if the inputs disagree, or ``max_iter`` / ``check_every`` are out of range.
167
+ :raises RuntimeError: if ``max_iter`` runs out before the fixed point.
168
+ """
169
+ if check_every < 1:
170
+ raise ValueError(f"{name}: check_every must be >= 1, got {check_every}")
171
+ if max_iter is not None and max_iter < 1:
172
+ raise ValueError(f"{name}: max_iter must be >= 1 or None, got {max_iter}")
173
+
174
+ marker, mask, kernel, flat = _align_inputs(marker, mask, kernel, name)
175
+ if not flat:
176
+ _require_nonnegative_anchor(kernel, name)
177
+
178
+ border_int = BORDER_TO_INT[border]
179
+ step = ops.dilate if dilate else ops.erode
180
+ clip = torch.minimum if dilate else torch.maximum
181
+
182
+ with torch.no_grad():
183
+ current = clip(marker, mask)
184
+ snapshot = current
185
+ iterations = 0
186
+ while max_iter is None or iterations < max_iter:
187
+ current = clip(step(current, kernel, border_int, flat), mask)
188
+ iterations += 1
189
+ if iterations % check_every == 0:
190
+ if torch.equal(current, snapshot):
191
+ return current
192
+ snapshot = current
193
+
194
+ if torch.equal(current, snapshot):
195
+ return current
196
+
197
+ raise RuntimeError(
198
+ f"{name}: no fixed point after {max_iter} iterations; raise max_iter, or pass finite inputs "
199
+ f"(a NaN never compares equal, so the convergence test can never fire)"
200
+ )
201
+
202
+
203
+ def reconstruction_by_dilation(
204
+ marker: torch.Tensor,
205
+ mask: torch.Tensor,
206
+ kernel: torch.Tensor,
207
+ *,
208
+ border: BorderMode = BorderMode.CONSTANT,
209
+ max_iter: int | None = None,
210
+ check_every: int = _DEFAULT_CHECK_EVERY,
211
+ ) -> torch.Tensor:
212
+ """
213
+ Geodesic reconstruction by dilation: the fixed point of ``min(dilation(y), mask)`` from ``y = marker``.
214
+
215
+ Values propagate out of ``marker`` along the structuring element, held down by ``mask`` at every
216
+ step, so a seeded peak floods only as far as ``mask`` allows. ``marker`` is clipped to
217
+ ``min(marker, mask)`` first, which is the precondition the definition asks for.
218
+
219
+ This operation is not differentiable yet and raises if handed an input that wants a gradient.
220
+
221
+ :param marker: propagation seed, shape ``(N, C, H, W)``.
222
+ :param mask: upper bound on the propagation, same shape as ``marker``.
223
+ :param kernel: structuring element, ``(kH, kW)`` or ``(C, kH, kW)``, anchor tap >= 0.
224
+ :param border: boundary mode for out-of-image reads.
225
+ :param max_iter: iteration budget, or ``None`` to run until the fixed point.
226
+ :param check_every: how many steps to run between convergence tests; larger trades a few wasted
227
+ steps for fewer device-to-host reads.
228
+ :return: the reconstruction, same shape as ``marker`` and dtype promoted across the inputs.
229
+ :raises ValueError: if the inputs disagree, or ``max_iter`` / ``check_every`` are out of range.
230
+ :raises RuntimeError: if an input wants a gradient, or ``max_iter`` runs out before the fixed point.
231
+ """
232
+ return _reconstruct(
233
+ marker,
234
+ mask,
235
+ kernel,
236
+ border,
237
+ dilate=True,
238
+ max_iter=max_iter,
239
+ check_every=check_every,
240
+ name="serron.reconstruction_by_dilation",
241
+ )
242
+
243
+
244
+ def reconstruction_by_erosion(
245
+ marker: torch.Tensor,
246
+ mask: torch.Tensor,
247
+ kernel: torch.Tensor,
248
+ *,
249
+ border: BorderMode = BorderMode.CONSTANT,
250
+ max_iter: int | None = None,
251
+ check_every: int = _DEFAULT_CHECK_EVERY,
252
+ ) -> torch.Tensor:
253
+ """
254
+ Geodesic reconstruction by erosion: the fixed point of ``max(erosion(y), mask)`` from ``y = marker``.
255
+
256
+ The dual of :func:`reconstruction_by_dilation`: ``marker`` sits above ``mask``, is clipped to
257
+ ``max(marker, mask)`` first, and the iteration descends until it settles.
258
+
259
+ This operation is not differentiable yet and raises if handed an input that wants a gradient.
260
+
261
+ :param marker: propagation seed, shape ``(N, C, H, W)``.
262
+ :param mask: lower bound on the propagation, same shape as ``marker``.
263
+ :param kernel: structuring element, ``(kH, kW)`` or ``(C, kH, kW)``, anchor tap >= 0.
264
+ :param border: boundary mode for out-of-image reads.
265
+ :param max_iter: iteration budget, or ``None`` to run until the fixed point.
266
+ :param check_every: how many steps to run between convergence tests; larger trades a few wasted
267
+ steps for fewer device-to-host reads.
268
+ :return: the reconstruction, same shape as ``marker`` and dtype promoted across the inputs.
269
+ :raises ValueError: if the inputs disagree, or ``max_iter`` / ``check_every`` are out of range.
270
+ :raises RuntimeError: if an input wants a gradient, or ``max_iter`` runs out before the fixed point.
271
+ """
272
+ return _reconstruct(
273
+ marker,
274
+ mask,
275
+ kernel,
276
+ border,
277
+ dilate=False,
278
+ max_iter=max_iter,
279
+ check_every=check_every,
280
+ name="serron.reconstruction_by_erosion",
281
+ )
serron/modules.py ADDED
@@ -0,0 +1,73 @@
1
+ """
2
+ Learnable morphology layers (``torch.nn.Module``).
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import override
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+ from . import functional as F
13
+ from .enums import BorderMode
14
+
15
+
16
+ class _MorphologyNd(nn.Module):
17
+ """Shared base: owns the learnable SE parameter."""
18
+
19
+ def __init__(
20
+ self,
21
+ channels: int,
22
+ kernel_size: int,
23
+ *,
24
+ border: BorderMode = BorderMode.REPLICATE,
25
+ dtype: torch.dtype = torch.float32,
26
+ device: torch.device | str | None = None,
27
+ ) -> None:
28
+ super().__init__()
29
+ self.channels = channels
30
+ self.kernel_size = kernel_size
31
+ self.border = border
32
+ self.weight = nn.Parameter(torch.empty(channels, kernel_size, kernel_size, dtype=dtype, device=device))
33
+ self.reset_parameters()
34
+
35
+ def reset_parameters(self) -> None:
36
+ with torch.no_grad():
37
+ self.weight.zero_()
38
+
39
+ @override
40
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
41
+ raise NotImplementedError
42
+
43
+
44
+ class Erosion2d(_MorphologyNd):
45
+ """Learnable 2-D erosion layer."""
46
+
47
+ @override
48
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
49
+ return F.erosion(x, self.weight, border=self.border)
50
+
51
+
52
+ class Dilation2d(_MorphologyNd):
53
+ """Learnable 2-D dilation layer."""
54
+
55
+ @override
56
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
57
+ return F.dilation(x, self.weight, border=self.border)
58
+
59
+
60
+ class Opening2d(_MorphologyNd):
61
+ """Learnable 2-D opening layer."""
62
+
63
+ @override
64
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
65
+ return F.opening(x, self.weight, border=self.border)
66
+
67
+
68
+ class Closing2d(_MorphologyNd):
69
+ """Learnable 2-D closing layer."""
70
+
71
+ @override
72
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
73
+ return F.closing(x, self.weight, border=self.border)
serron/py.typed ADDED
File without changes
@@ -0,0 +1,116 @@
1
+ """
2
+ Structuring-element builders.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import torch
8
+
9
+ from . import _flatness
10
+
11
+ _OFF = float("-inf")
12
+
13
+
14
+ def _checked_dtype(dtype: torch.dtype) -> torch.dtype:
15
+ """
16
+ Reject a dtype the morphology kernels cannot dispatch on.
17
+
18
+ :param dtype: requested element type.
19
+ :return: ``dtype`` unchanged.
20
+ :raises ValueError: if ``dtype`` is not a floating type.
21
+ """
22
+ if not dtype.is_floating_point:
23
+ raise ValueError(f"structuring elements must use a floating dtype, got {dtype}")
24
+ return dtype
25
+
26
+
27
+ def _flat(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
28
+ """
29
+ Turn a boolean membership ``mask`` into a flat additive SE (0 / -inf).
30
+ :param mask: input mask
31
+ :param dtype: element type of the result
32
+ :return: flat additive SE
33
+ """
34
+ # Marked not-flat without inspecting the mask: a shape that happens to fill its whole
35
+ # box is still correct on the 2-D path, only slower.
36
+ return _flatness.mark(torch.where(mask, 0.0, _OFF).to(dtype), False)
37
+
38
+
39
+ def _centered_coords(size: int, device: torch.device | str | None) -> torch.Tensor:
40
+ """
41
+ 1-D coordinate axis centered on 0
42
+ :param size: size of the cord axis
43
+ :param device: torch device
44
+ :return: cord axis of size ``sieze`` centered on 0
45
+ """
46
+ return torch.arange(size, device=device) - (size - 1) // 2
47
+
48
+
49
+ def square(size: int, *, dtype: torch.dtype = torch.float32, device: torch.device | str | None = None) -> torch.Tensor:
50
+ """
51
+ Square SE of shape ``(size, size)``.
52
+ :param size: SE size
53
+ :param dtype: element type; match the input's to keep an operation in that precision
54
+ :param device: device to create the SE on
55
+ :return: SE tensor
56
+ """
57
+ if size < 1:
58
+ raise ValueError(f"size must be >= 1, got {size}")
59
+ return _flatness.mark(torch.zeros(size, size, dtype=_checked_dtype(dtype), device=device), True)
60
+
61
+
62
+ def cross(size: int, *, dtype: torch.dtype = torch.float32, device: torch.device | str | None = None) -> torch.Tensor:
63
+ """
64
+ Cross-shaped SE of shape ``(size, size)``.
65
+ :param size: SE size (should be odd for a symmetric cross)
66
+ :param dtype: element type; match the input's to keep an operation in that precision
67
+ :param device: device to create the SE on
68
+ :return: SE tensor
69
+ """
70
+ if size < 1:
71
+ raise ValueError(f"size must be >= 1, got {size}")
72
+ coords = _centered_coords(size, device)
73
+ dy, dx = torch.meshgrid(coords, coords, indexing="ij")
74
+ return _flat((dy == 0) | (dx == 0), _checked_dtype(dtype))
75
+
76
+
77
+ def disk(radius: int, *, dtype: torch.dtype = torch.float32, device: torch.device | str | None = None) -> torch.Tensor:
78
+ """
79
+ Disk-shaped SE of shape ``(2*radius+1, 2*radius+1)``.
80
+ :param radius: SE radius
81
+ :param dtype: element type; match the input's to keep an operation in that precision
82
+ :param device: device to create the SE on
83
+ :return: SE tensor
84
+ """
85
+ if radius < 0:
86
+ raise ValueError(f"radius must be >= 0, got {radius}")
87
+ coords = _centered_coords(2 * radius + 1, device)
88
+ dy, dx = torch.meshgrid(coords, coords, indexing="ij")
89
+ return _flat(dx * dx + dy * dy <= radius * radius, _checked_dtype(dtype))
90
+
91
+
92
+ def diamond(radius: int, *, dtype: torch.dtype = torch.float32, device: torch.device | str | None = None) -> torch.Tensor:
93
+ """
94
+ Diamond SE of shape ``(2*radius+1, 2*radius+1)``.
95
+ :param radius: SE radius
96
+ :param dtype: element type; match the input's to keep an operation in that precision
97
+ :param device: device to create the SE on
98
+ :return: SE tensor
99
+ """
100
+ if radius < 0:
101
+ raise ValueError(f"radius must be >= 0, got {radius}")
102
+ coords = _centered_coords(2 * radius + 1, device)
103
+ dy, dx = torch.meshgrid(coords, coords, indexing="ij")
104
+ return _flat(dx.abs() + dy.abs() <= radius, _checked_dtype(dtype))
105
+
106
+
107
+ def from_tensor(weights: torch.Tensor, *, dtype: torch.dtype = torch.float32) -> torch.Tensor:
108
+ """
109
+ Wrap an arbitrary 2-D tensor as a grayscale SE.
110
+ :param weights: 2-D tensor of weights
111
+ :param dtype: element type; match the input's to keep an operation in that precision
112
+ :return: SE tensor
113
+ """
114
+ if weights.dim() != 2:
115
+ raise ValueError(f"expected a 2-D (kh, kw) tensor, got shape {tuple(weights.shape)}")
116
+ return weights.to(_checked_dtype(dtype))
@@ -0,0 +1,268 @@
1
+ Metadata-Version: 2.4
2
+ Name: serron
3
+ Version: 0.5.0
4
+ Summary: Mathematical Morphology module for PyTorch (CUDA), providing differentiable operators and learnable network layers.
5
+ Keywords: cuda,gpu,pytorch,morphology,mathematical-morphology,image-processing,computer-vision,erosion,dilation,differentiable,deep-learning
6
+ Author-Email: Vedran Hrabar <vedran.hrabar@outlook.com>
7
+ License-Expression: MIT AND BSD-3-Clause
8
+ License-File: LICENSE
9
+ License-File: THIRD_PARTY_NOTICES
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: GPU
12
+ Classifier: Environment :: GPU :: NVIDIA CUDA
13
+ Classifier: Environment :: GPU :: NVIDIA CUDA :: 12
14
+ Classifier: Environment :: GPU :: NVIDIA CUDA :: 13
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Operating System :: Microsoft :: Windows
19
+ Classifier: Programming Language :: C++
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Programming Language :: Python :: Implementation :: CPython
26
+ Classifier: Topic :: Scientific/Engineering
27
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
28
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
29
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
30
+ Classifier: Topic :: Software Development :: Libraries
31
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
+ Classifier: Typing :: Typed
33
+ Project-URL: Homepage, https://github.com/vhrabar/serron
34
+ Project-URL: Source, https://github.com/vhrabar/serron
35
+ Project-URL: Documentation, https://github.com/vhrabar/serron/wiki
36
+ Project-URL: Changelog, https://github.com/vhrabar/serron/blob/main/CHANGELOG.md
37
+ Project-URL: Bug Tracker, https://github.com/vhrabar/serron/issues
38
+ Requires-Python: >=3.12
39
+ Requires-Dist: torch>=2.13
40
+ Description-Content-Type: text/markdown
41
+
42
+ # Serron
43
+
44
+ Mathematical Morphology module for PyTorch (CUDA), providing differentiable operators and learnable network layers.
45
+
46
+ ## Install
47
+
48
+ One prebuilt wheel per platform covers every supported interpreter, on Linux (x86_64,
49
+ aarch64) and Windows (x86_64).
50
+
51
+ ```bash
52
+ pip install serron
53
+ ```
54
+
55
+ The kernels are built against PyTorch's stable C++ ABI, so a wheel loads on torch 2.13 and
56
+ every later release (`torch>=2.13`) rather than only the minor it was compiled against. The
57
+ wheel carries no CPython tag either, because the compiled libraries use no CPython API.
58
+
59
+ Wheels load on both CUDA and CPU-only torch builds; the CUDA kernels are only loaded when
60
+ the installed torch has CUDA. The CUDA kernels work with a torch built against CUDA 12 or
61
+ CUDA 13: they bind to the NVIDIA driver at runtime rather than linking a CUDA runtime, so the
62
+ only requirement is a driver supporting CUDA 12.0 or newer (R525 / 525.60.13 on Linux,
63
+ 528.33 on Windows).
64
+
65
+ ## Usage
66
+
67
+ Serron works on standard PyTorch tensors laid out as `(N, C, H, W)` and living on a CUDA
68
+ or CPU device.
69
+
70
+ ### Functional operators
71
+
72
+ Stateless operators live in `serron.functional` and are re-exported at the top level.
73
+ Each takes an input tensor, a structuring element, and an optional `border` mode:
74
+
75
+ ```python
76
+ import torch
77
+ import serron
78
+ from serron import BorderMode
79
+ from serron import structuring_element as se
80
+
81
+ x = torch.rand(1, 1, 256, 256, device="cuda")
82
+ kernel = se.disk(3, device="cuda")
83
+
84
+ eroded = serron.erosion(x, kernel)
85
+ dilated = serron.dilation(x, kernel)
86
+ opened = serron.opening(x, kernel)
87
+ closed = serron.closing(x, kernel)
88
+
89
+ # Derived operators
90
+ grad = serron.gradient(x, kernel) # dilate(x) - erode(x)
91
+ white = serron.top_hat(x, kernel) # x - open(x)
92
+ black = serron.black_hat(x, kernel) # close(x) - x
93
+
94
+ # Control border handling
95
+ eroded_reflect = serron.erosion(x, kernel, border=BorderMode.REFLECT)
96
+ ```
97
+
98
+ Available operators: `erosion`, `dilation`, `opening`, `closing`, `gradient`,
99
+ `top_hat`, `black_hat`, `reconstruction_by_dilation`, `reconstruction_by_erosion`.
100
+
101
+ ### Geodesic reconstruction
102
+
103
+ `reconstruction_by_dilation` floods a marker outwards until it settles, held down by a
104
+ mask at every step; `reconstruction_by_erosion` is its dual. Both iterate the compiled
105
+ `erode` / `dilate` ops to a fixed point and default to `BorderMode.CONSTANT`, which is the
106
+ geodesic reading of the image boundary.
107
+
108
+ ```python
109
+ marker = torch.zeros_like(x)
110
+ marker[..., 128, 128] = x[..., 128, 128]
111
+
112
+ with torch.no_grad(): # no backward pass yet
113
+ flooded = serron.reconstruction_by_dilation(marker, x, se.cross(3, device="cuda"))
114
+ ```
115
+
116
+ The loop runs on the device, but its convergence test reads one flag back to the host every
117
+ `check_every` steps (16 by default). Raise it to trade a few wasted steps for fewer syncs.
118
+
119
+ ### Structuring elements
120
+
121
+ `serron.structuring_element` builds common SE shapes on the requested device:
122
+
123
+ ```python
124
+ from serron import structuring_element as se
125
+
126
+ se.square(5, device="cuda") # (5, 5) full square
127
+ se.cross(5, device="cuda") # (5, 5) plus shape
128
+ se.disk(3, device="cuda") # (7, 7) disk, radius 3
129
+ se.diamond(3, device="cuda") # (7, 7) diamond, radius 3
130
+ se.from_tensor(my_weights) # wrap an arbitrary 2-D tensor as a grayscale SE
131
+ ```
132
+
133
+ ### Border modes
134
+
135
+ `BorderMode` controls how out-of-bounds neighbors are handled:
136
+
137
+ | Mode | Behavior |
138
+ |------------------------|---------------------------------|
139
+ | `BorderMode.REPLICATE` | Repeat the edge value (default) |
140
+ | `BorderMode.REFLECT` | Mirror across the edge |
141
+ | `BorderMode.CONSTANT` | Pad with a constant |
142
+
143
+ ### Learnable layers
144
+
145
+ `serron` also exposes `torch.nn.Module` layers with a learnable structuring element,
146
+ so morphology can be trained end-to-end inside a network. Each layer takes the number
147
+ of `channels` and a `kernel_size`:
148
+
149
+ ```python
150
+ import torch
151
+ from serron import Erosion2d, Dilation2d, Opening2d, Closing2d
152
+ from serron import BorderMode
153
+
154
+ layer = Erosion2d(channels=3, kernel_size=5, border=BorderMode.REPLICATE).cuda()
155
+
156
+ x = torch.rand(8, 3, 64, 64, device="cuda")
157
+ y = layer(x) # forward pass; layer.weight is a trainable (C, k, k) SE
158
+ y.sum().backward() # gradients flow into layer.weight
159
+ ```
160
+
161
+ Available layers: `Erosion2d`, `Dilation2d`, `Opening2d`, `Closing2d`.
162
+
163
+ ## Implementation
164
+
165
+ Every operator picks one of a few kernels at call time. The structuring element and the
166
+ device's shared memory decide which one.
167
+
168
+ ### Which path runs
169
+
170
+
171
+
172
+ | Path | Runs when | Cost per output |
173
+ |-------------------------------|---------------------------------------------------------------|---------------------------|
174
+ | Separable van Herk–Gil–Werman | Flat SE and `max(kH, kW) >= SERRON_SEPARABLE_MIN_K` | O(1) in the window length |
175
+ | Tiled 2-D | Otherwise, when the halo tile and the SE fit in shared memory | O(kH × kW) |
176
+ | Element-wise | Otherwise; reads through global memory (CUDA only) | O(kH × kW) |
177
+
178
+ `SERRON_SEPARABLE_MIN_K` is the window length where the separable path takes over. It
179
+ accepts any positive integer. The default differs per backend because it marks where the
180
+ separable path starts beating the 2-D one, and that point is not the same on both: `11` on
181
+ CUDA, `5` on CPU, where there is no tiled 2-D kernel to soften the `kH × kW` window.
182
+
183
+ ### The separable path
184
+
185
+ Splitting a flat `kH × kW` window into a `1 × kW` row pass and a `kH × 1` column pass
186
+ already drops the per-pixel work from `kH × kW` to `kH + kW`, and the Van Herk–Gil–Werman algorithm
187
+ drops it further to a constant three operations per ouput, no matter the sequence length.
188
+
189
+ On CUDA both scans sit in shared memory. A chunk at least a warp wide gets a warp to
190
+ itself and the lanes cooperate through shuffles; anything shorter gets a single thread.
191
+ On CPU the lines go through `at::parallel_for`.
192
+
193
+ ### Backward
194
+
195
+ Backward needs to know *where* the winning sample was, not just what it was, so its scans
196
+ carry a `(value, offset)` pair rather than a bare value. Combining two of those keeps the
197
+ lower offset on a tie, which is the rule the direct kernel gets from its strict-improvement
198
+ loop — reproducing it exactly is what makes the two paths agree on which tap receives the
199
+ gradient. The window is one pair-combine as before, so the search is O(1) in the window
200
+ length on both the row and the column pass.
201
+
202
+ It splits on the same condition: a separable row and column argreduce for a flat SE at or
203
+ above the threshold, and a direct recompute of the winning tap otherwise. The direct
204
+ recompute stages its window in shared memory the same way the forward's tiled path does.
205
+
206
+
207
+ ## Benchmarks
208
+
209
+ Per-operator throughput and the cross-library comparison live in
210
+ [`benchmarks/README.md`](https://github.com/vhrabar/serron/blob/main/benchmarks/README.md).
211
+
212
+ Erosion with a flat SE, `8x3x512x512` float32 on an H100 PCIe (with Intel Xeon Platinum 8480+), in milliseconds:
213
+
214
+ | k | serron | PyTorch | Kornia | CuPy | SciPy (CPU) |
215
+ |----:|---------:|--------:|-------:|-----:|------------:|
216
+ | 7 | 0.30 | 0.42 | 2.80 | 0.20 | 159 |
217
+ | 31 | **0.23** | 5.46 | 41.87 | 0.58 | 151 |
218
+ | 63 | **0.31** | 21.48 | OOM | 1.05 | 144 |
219
+ | 127 | **0.25** | 81.03 | OOM | 2.00 | 142 |
220
+
221
+
222
+
223
+ ## Building from source
224
+
225
+ ### Clone repo
226
+ ```bash
227
+ git clone git@github.com:vhrabar/serron.git
228
+ cd serron
229
+ ```
230
+
231
+ ### Choosing a torch build
232
+
233
+ `torch` is pulled from a specific wheel index via mutually-exclusive dependency groups,
234
+ one per backend and end of the supported range: `cu132` / `cpu` at the oldest torch the
235
+ kernels target, `cu132-newest` / `cpu-newest` at the current release. `cu132-newest` is
236
+ enabled by default, so plain `uv sync` gives the CUDA 13.2 build against the newest torch.
237
+ Because the groups conflict, selecting another one means turning the default off, which
238
+ `--no-default-groups` does in one step:
239
+
240
+ ```bash
241
+ uv sync # CUDA, newest torch
242
+ uv sync --no-default-groups --group dev --group cpu-newest # CPU-only, newest torch
243
+ uv sync --no-default-groups --group dev --group cu132 # CUDA, oldest supported torch
244
+ uv sync --no-default-groups --group dev --group cpu # CPU-only, oldest supported torch
245
+ ```
246
+
247
+ ### Building the wheel
248
+
249
+ Building the CUDA extension from source needs the CUDA 13.X toolkit (`nvcc`):
250
+
251
+ ```bash
252
+ uv sync --no-install-workspace
253
+ uv build --package serron --wheel --no-build-isolation
254
+ ```
255
+
256
+ On a GPU-less machine, sync the CPU torch build instead; the extension then builds
257
+ C++ only (no `nvcc` required):
258
+
259
+ ```bash
260
+ uv sync --no-install-workspace --no-default-groups --group dev --group cpu-newest
261
+ uv build --package serron --wheel --no-build-isolation
262
+ ```
263
+
264
+ ## License
265
+
266
+ MIT
267
+
268
+ Copyright © 2026 Vedran Hrabar.
@@ -0,0 +1,17 @@
1
+ bin/_C.dll,sha256=75RwnI5dso4-SGrVoS5KLRyJfYsgG7E3joRJKfAA30w,182784
2
+ bin/_C_cuda.dll,sha256=-QOwiei0oEAPZMgyPOVro-D7eMPeRWBMzwQ5bNVWM5Q,18928640
3
+ serron/__init__.py,sha256=WLtQQ0kzIBEBHYLpxn44czC-VdmWSmNl1OqsJvVTHNY,1014
4
+ serron/_build_info.py,sha256=8lrncTaFWdB3HW9ACvLRK5Om69XzIhEg-OQHIlwTW0A,180
5
+ serron/_cmake_ops.py,sha256=p23q5tU4VFmhh1rO27NFwLz9ZQ9VTx3OpjrgIfpqZMk,4352
6
+ serron/_flatness.py,sha256=hXahHsoUPFejmBg5Ix6q6NnAv2WGOLqYub3PCOK-5fk,1101
7
+ serron/autograd.py,sha256=MOG6ttr1wbhi91oMJ87HbvIhduBTimDbs9B4NqIg9Gk,3967
8
+ serron/enums.py,sha256=6ZZr_liNDTAthVLCNq_GKI8zRN9V9MSkElZRm8Zgwho,728
9
+ serron/functional.py,sha256=-fJrFSZg0t0OYVegRj-LuXSWinqI2ZHYwgtv50wDxa0,11479
10
+ serron/modules.py,sha256=TXFsm0EUUe2P5fxsYRvazW8bIKwu7yGUZ7f4nFUrMdw,1866
11
+ serron/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ serron/structuring_element.py,sha256=_0qAtr_RJmo5zrufggGUBzZGKXoKUbqL1kg5IoPw6iM,4338
13
+ serron-0.5.0.dist-info/METADATA,sha256=gHUBt9G3XNdZ_0QbblL_6ruPbsXRKs2QN3SW06sRHKk,10966
14
+ serron-0.5.0.dist-info/WHEEL,sha256=H2-vNj0Uj93L_UlwWLAHSbPwt0nxqZmlgAGZZjm-2qY,102
15
+ serron-0.5.0.dist-info/licenses/LICENSE,sha256=CdBSCY_sy1PsGSUM6wibbfVE3QNvVYJbC-f_7n9d-QU,1091
16
+ serron-0.5.0.dist-info/licenses/THIRD_PARTY_NOTICES,sha256=02QPuFH-rh7SVzO14_w_WDh5V07pLo6ZC-ZPb7e-aC4,4527
17
+ serron-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: scikit-build-core 1.1.1
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vedran Hrabar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,110 @@
1
+ THIRD-PARTY NOTICES
2
+
3
+ This project contains code derived from third-party software. The original
4
+ license terms are reproduced below as required by those licenses.
5
+
6
+ ================================================================================
7
+ PyTorch
8
+ https://github.com/pytorch/pytorch
9
+
10
+ License: BSD-3-Clause
11
+ ================================================================================
12
+
13
+ Used in (paths relative to packages/serron/):
14
+
15
+ csrc/cuda/utils/driver.h, csrc/cuda/utils/driver.cpp
16
+ runtime binding to the CUDA driver API (from c10/cuda/driver_api.h/.cpp)
17
+ csrc/compat/atomic.cuh
18
+ BFloat16 atomic add by compare-and-swap (from AtomicFPOp in
19
+ torch/headeronly/cuda/Atomic.h)
20
+ csrc/compat/acc_type.h
21
+ accumulate-type trait and its table (from ATen/AccumulateType.h)
22
+
23
+ The compiled extension also includes code from PyTorch's header-only
24
+ torch/headeronly headers (Half, BFloat16), which are inlined into it at build
25
+ time.
26
+
27
+ From PyTorch:
28
+
29
+ Copyright (c) 2016- Facebook, Inc (Adam Paszke)
30
+ Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
31
+ Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
32
+ Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
33
+ Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
34
+ Copyright (c) 2011-2013 NYU (Clement Farabet)
35
+ Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
36
+ Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
37
+ Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
38
+
39
+ From Caffe2:
40
+
41
+ Copyright (c) 2016-present, Facebook Inc. All rights reserved.
42
+
43
+ All contributions by Facebook:
44
+ Copyright (c) 2016 Facebook Inc.
45
+
46
+ All contributions by Google:
47
+ Copyright (c) 2015 Google Inc.
48
+ All rights reserved.
49
+
50
+ All contributions by Yangqing Jia:
51
+ Copyright (c) 2015 Yangqing Jia
52
+ All rights reserved.
53
+
54
+ All contributions by Kakao Brain:
55
+ Copyright 2019-2020 Kakao Brain
56
+
57
+ All contributions by Cruise LLC:
58
+ Copyright (c) 2022 Cruise LLC.
59
+ All rights reserved.
60
+
61
+ All contributions by Tri Dao:
62
+ Copyright (c) 2024 Tri Dao.
63
+ All rights reserved.
64
+
65
+ All contributions by Arm:
66
+ Copyright (c) 2021, 2023-2025 Arm Limited and/or its affiliates
67
+
68
+ All contributions from Caffe:
69
+ Copyright(c) 2013, 2014, 2015, the respective contributors
70
+ All rights reserved.
71
+
72
+ All other contributions:
73
+ Copyright(c) 2015, 2016 the respective contributors
74
+ All rights reserved.
75
+
76
+ Caffe2 uses a copyright model similar to Caffe: each contributor holds
77
+ copyright over their contributions to Caffe2. The project versioning records
78
+ all such contribution and copyright details. If a contributor wants to further
79
+ mark their specific copyright on a particular contribution, they should
80
+ indicate their copyright solely in the commit message of the change when it is
81
+ committed.
82
+
83
+ All rights reserved.
84
+
85
+ Redistribution and use in source and binary forms, with or without
86
+ modification, are permitted provided that the following conditions are met:
87
+
88
+ 1. Redistributions of source code must retain the above copyright
89
+ notice, this list of conditions and the following disclaimer.
90
+
91
+ 2. Redistributions in binary form must reproduce the above copyright
92
+ notice, this list of conditions and the following disclaimer in the
93
+ documentation and/or other materials provided with the distribution.
94
+
95
+ 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
96
+ and IDIAP Research Institute nor the names of its contributors may be
97
+ used to endorse or promote products derived from this software without
98
+ specific prior written permission.
99
+
100
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
101
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
102
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
103
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
104
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
105
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
106
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
107
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
108
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
109
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
110
+ POSSIBILITY OF SUCH DAMAGE.