mlx-segment-ct 0.2.2__tar.gz → 0.3.0__tar.gz
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.
Potentially problematic release.
This version of mlx-segment-ct might be problematic. Click here for more details.
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/PKG-INFO +5 -2
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/README.md +4 -1
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/pyproject.toml +2 -2
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/__init__.py +1 -1
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/activations.py +5 -1
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/bundle_transforms.py +14 -5
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/checkpoint_sources.py +3 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/correction.py +3 -2
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/correction_inferer.py +10 -3
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/instance_norm.py +2 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/medmlx.py +17 -4
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_correction_weights.py +3 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_weights.py +3 -1
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/projections.py +2 -1
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/.gitignore +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/LICENSE +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/THIRD_PARTY_NOTICES.md +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/_types.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/interactive.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/labels.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_network.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_point.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_point_window.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_upsample.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_worker.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/py.typed +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/restoration.py +0 -0
- {mlx_segment_ct-0.2.2 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/streaming.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mlx-segment-ct
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Native MLX implementation of NV-Segment-CT (VISTA-3D)
|
|
5
5
|
Author: Joseph Sandoval, Alfredo Sandoval Jr.
|
|
6
6
|
License-Expression: Apache-2.0 AND BSD-3-Clause
|
|
@@ -60,7 +60,10 @@ from medmlx_core.runtime import import_mlx
|
|
|
60
60
|
from mlx_segment_ct import mlx_correction_weights, mlx_weights
|
|
61
61
|
|
|
62
62
|
mx = import_mlx()
|
|
63
|
-
checkpoint = Path(hf_hub_download(
|
|
63
|
+
checkpoint = Path(hf_hub_download(
|
|
64
|
+
"nvidia/NV-Segment-CT", "vista3d_pretrained_model/model.pt",
|
|
65
|
+
revision="afb51518689f71e6abb367ee6301b2cd0225c66a",
|
|
66
|
+
))
|
|
64
67
|
out = Path("weights")
|
|
65
68
|
out.mkdir(exist_ok=True)
|
|
66
69
|
mx.save_safetensors(
|
|
@@ -32,7 +32,10 @@ from medmlx_core.runtime import import_mlx
|
|
|
32
32
|
from mlx_segment_ct import mlx_correction_weights, mlx_weights
|
|
33
33
|
|
|
34
34
|
mx = import_mlx()
|
|
35
|
-
checkpoint = Path(hf_hub_download(
|
|
35
|
+
checkpoint = Path(hf_hub_download(
|
|
36
|
+
"nvidia/NV-Segment-CT", "vista3d_pretrained_model/model.pt",
|
|
37
|
+
revision="afb51518689f71e6abb367ee6301b2cd0225c66a",
|
|
38
|
+
))
|
|
36
39
|
out = Path("weights")
|
|
37
40
|
out.mkdir(exist_ok=True)
|
|
38
41
|
mx.save_safetensors(
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "mlx-segment-ct"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
description = "Native MLX implementation of NV-Segment-CT (VISTA-3D)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
classifiers = ["Operating System :: MacOS :: MacOS X"]
|
|
@@ -20,7 +20,7 @@ dependencies = [
|
|
|
20
20
|
]
|
|
21
21
|
|
|
22
22
|
[project.entry-points."medmlx.models"]
|
|
23
|
-
|
|
23
|
+
mlx-segment-ct = "mlx_segment_ct.medmlx:MODEL"
|
|
24
24
|
|
|
25
25
|
[project.optional-dependencies]
|
|
26
26
|
conversion = ["torch>=2.13,<3"]
|
|
@@ -25,7 +25,7 @@ if TYPE_CHECKING:
|
|
|
25
25
|
from mlx_segment_ct.mlx_worker import automatic_logits
|
|
26
26
|
from mlx_segment_ct.streaming import LabelReducer, bounded_labels, rolling_logits
|
|
27
27
|
|
|
28
|
-
__version__ = "0.
|
|
28
|
+
__version__ = "0.3.0"
|
|
29
29
|
|
|
30
30
|
_EXPORTS = {
|
|
31
31
|
"AutomaticModel": "mlx_segment_ct.mlx_network",
|
|
@@ -63,7 +63,11 @@ class Gelu:
|
|
|
63
63
|
)
|
|
64
64
|
|
|
65
65
|
def __call__(self, values: array) -> array:
|
|
66
|
-
"""
|
|
66
|
+
"""Evaluate erf-form GELU using the kernel's float32 approximation.
|
|
67
|
+
|
|
68
|
+
The result has the input shape; this polynomial implementation is not an
|
|
69
|
+
exact mathematical evaluation of the error function.
|
|
70
|
+
"""
|
|
67
71
|
return self.kernel(
|
|
68
72
|
inputs=[values],
|
|
69
73
|
template=[("SIZE", values.size)],
|
|
@@ -193,7 +193,10 @@ class RestorationGrid:
|
|
|
193
193
|
def load_volume(path: Path) -> tuple[HostArray, DoubleArray]:
|
|
194
194
|
"""``LoadImaged(image_only=True)`` and ``EnsureChannelFirstd`` via NibabelReader.
|
|
195
195
|
|
|
196
|
-
Returns the float32 (C, X, Y, Z) array and the float64 affine.
|
|
196
|
+
Returns the float32 (C, X, Y, Z) array and the float64 affine. Header
|
|
197
|
+
spatial units are not converted; downstream spacing assumes affine values
|
|
198
|
+
are in millimeters. The affine is checked for finiteness and invertibility,
|
|
199
|
+
but image voxel values are not checked for finiteness here.
|
|
197
200
|
"""
|
|
198
201
|
try:
|
|
199
202
|
image = nifti_api.load(str(path))
|
|
@@ -232,9 +235,10 @@ def preprocess(
|
|
|
232
235
|
NV-Segment-CT's fixed range (``"range"``) or NV-Segment-CTMR's percentiles.
|
|
233
236
|
|
|
234
237
|
``image`` is float32 ``(1, X, Y, Z)`` as ``load_volume`` returns it, and ``affine``
|
|
235
|
-
its voxel-to-world matrix (NIfTI RAS, millimeters).
|
|
236
|
-
[0, 1]
|
|
237
|
-
|
|
238
|
+
its voxel-to-world matrix (NIfTI RAS, assumed millimeters). Finite values are
|
|
239
|
+
scaled to [0, 1] in the usual nondegenerate case (see
|
|
240
|
+
``scale_intensity_percentiles`` for the equal-percentile case); NaNs can
|
|
241
|
+
survive preprocessing. The result is on the RAS-oriented 1.5 mm foreground crop.
|
|
238
242
|
|
|
239
243
|
Raises:
|
|
240
244
|
InvalidInputError: no voxel is above zero after resampling, or an ``extra``
|
|
@@ -348,7 +352,12 @@ def _fused_multiply_add(a: np.float32, b: np.float32, c: np.float32) -> np.float
|
|
|
348
352
|
|
|
349
353
|
|
|
350
354
|
def save_label_map(path: Path, labels: HostArray, affine: DoubleArray) -> None:
|
|
351
|
-
"""
|
|
355
|
+
"""Save float32 labels and the supplied affine in a new NIfTI-1 header.
|
|
356
|
+
|
|
357
|
+
The source header, including its unit code, is not copied. The sform uses
|
|
358
|
+
the supplied affine and qform uses NiBabel's shear-stripped representation;
|
|
359
|
+
both have code 1.
|
|
360
|
+
"""
|
|
352
361
|
data = np.asarray(labels)
|
|
353
362
|
data = data[0] if data.ndim == 4 and data.shape[0] == 1 else data
|
|
354
363
|
image = nifti_api.Nifti1Image(data.astype(np.float32, copy=False), affine)
|
|
@@ -30,6 +30,9 @@ def read_safetensors_checkpoint(checkpoint_path: Path, *, mx: CoreRuntime) -> di
|
|
|
30
30
|
matches the pinned names directly. The prefix is stripped only when every
|
|
31
31
|
key in the file shares it, so an unexpected layout surfaces as a checkpoint
|
|
32
32
|
key mismatch in ``convert_state_dict`` rather than being silently merged.
|
|
33
|
+
Values are materialized as contiguous NumPy arrays; NumPy's
|
|
34
|
+
``ascontiguousarray`` turns a zero-dimensional tensor into shape ``(1,)``.
|
|
35
|
+
This reader does not validate the graph inventory or checkpoint provenance.
|
|
33
36
|
"""
|
|
34
37
|
raw = mx.load(str(checkpoint_path))
|
|
35
38
|
if not isinstance(raw, dict):
|
|
@@ -12,8 +12,9 @@ def normalized_point_positions(points: HostArray, shape: tuple[int, ...]) -> Hos
|
|
|
12
12
|
|
|
13
13
|
``points`` holds voxel indices with the last axis ordered (x, y, z) on the image
|
|
14
14
|
whose spatial shape is ``shape``. Each coordinate gets +0.5 (the voxel center)
|
|
15
|
-
and is divided by that axis size
|
|
16
|
-
|
|
15
|
+
and is divided by that axis size. In-bounds integer voxel indices yield values
|
|
16
|
+
in (0, 1); this helper does not clip or validate coordinates. The result is
|
|
17
|
+
float32 with the shape of ``points``. Callers must supply positive axis sizes.
|
|
17
18
|
|
|
18
19
|
MONAI transforms clicks in float64 and casts only after normalization. MLX
|
|
19
20
|
does not support float64, so this geometry calculation stays on the host.
|
|
@@ -72,6 +72,8 @@ def point_based_window_inferer[ArrayT: ArrayValue](
|
|
|
72
72
|
Padding is constant zero, coverage is binary (overlaps sum, not average),
|
|
73
73
|
and untouched voxels keep previous logits, or NaN when no previous mask.
|
|
74
74
|
Only array data is returned; affine/meta restoration belongs to the caller.
|
|
75
|
+
The released ROIs have even dimensions. For an odd ROI dimension, a centered
|
|
76
|
+
interior window spans ``2 * (roi // 2)`` voxels, one fewer than the ROI.
|
|
75
77
|
|
|
76
78
|
Args:
|
|
77
79
|
inputs: image, ``(1, C, X, Y, Z)``.
|
|
@@ -79,14 +81,19 @@ def point_based_window_inferer[ArrayT: ArrayValue](
|
|
|
79
81
|
predictor: called once per window with the MLX patch and keyword arguments
|
|
80
82
|
``point_coords``, ``point_labels``, ``class_vector``, ``prompt_class``,
|
|
81
83
|
``patch_coords`` (the window slices), ``prev_mask`` and ``kwargs``.
|
|
84
|
+
Coordinates and previous logits passed to it use the padded grid.
|
|
82
85
|
point_coords: ``(1, N, 3)`` click positions in voxel units of ``inputs``.
|
|
83
86
|
point_labels: ``(1, N)`` click codes (see ``InteractivePrompt``).
|
|
87
|
+
class_vector: Optional automatic-branch class IDs, forwarded to the predictor.
|
|
88
|
+
prompt_class: Optional point-branch class IDs, forwarded to the predictor.
|
|
84
89
|
prev_mask: optional previous logits on the ``inputs`` grid.
|
|
85
90
|
point_start: index of the first click that gets its own windows; earlier
|
|
86
91
|
clicks are still passed to the predictor as context.
|
|
87
|
-
center_only: one window
|
|
88
|
-
windows per axis (27 per click): centered
|
|
89
|
-
|
|
92
|
+
center_only: one window per click, shifted at image edges; otherwise up to
|
|
93
|
+
three windows per axis (27 per click): centered and edge-inset windows.
|
|
94
|
+
margin: Edge inset used only when ``center_only`` is false.
|
|
95
|
+
mx: Array boundary for creating patches; defaults to the shared MLX runtime.
|
|
96
|
+
**kwargs: Extra predictor keyword arguments, forwarded unchanged.
|
|
90
97
|
|
|
91
98
|
Raises:
|
|
92
99
|
ValueError: more than one object, a non-5D input, or no window selected.
|
|
@@ -136,6 +136,8 @@ class InstanceNorm:
|
|
|
136
136
|
An optional float32 residual of the same shape is added after the affine,
|
|
137
137
|
before the activation (leaky ReLU uses slope 0.01). The two-pass moments
|
|
138
138
|
and each float32 rounding step are unchanged. Returns the input shape.
|
|
139
|
+
These shapes and dtypes are caller requirements, not independently
|
|
140
|
+
validated before the Metal kernels are dispatched.
|
|
139
141
|
"""
|
|
140
142
|
batch, channels = values.shape[:2]
|
|
141
143
|
size = prod(values.shape[2:])
|
|
@@ -41,7 +41,7 @@ if TYPE_CHECKING:
|
|
|
41
41
|
from mlx_segment_ct.restoration import ScoreRestorer
|
|
42
42
|
|
|
43
43
|
MODEL = {
|
|
44
|
-
"id": "
|
|
44
|
+
"id": "mlx-segment-ct",
|
|
45
45
|
"label": "NV-Segment-CT",
|
|
46
46
|
"task": "segmentation",
|
|
47
47
|
"run": "mlx_segment_ct.medmlx:run",
|
|
@@ -51,7 +51,7 @@ MODEL = {
|
|
|
51
51
|
),
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
MASK_FILENAME = "
|
|
54
|
+
MASK_FILENAME = "mlx_segment_ct_mask.nii.gz"
|
|
55
55
|
RESTORATIONS = ("scores", "bundle")
|
|
56
56
|
AUTOMATIC_WEIGHTS = "automatic.safetensors"
|
|
57
57
|
CORRECTION_WEIGHTS = "correction.safetensors"
|
|
@@ -64,7 +64,7 @@ _NETWORK_FAILURE = (
|
|
|
64
64
|
)
|
|
65
65
|
_WEIGHTS_HINT = (
|
|
66
66
|
"Convert NVIDIA's NV-Segment-CT (or NV-Segment-CTMR, with checkpoint='NV-Segment-CTMR') "
|
|
67
|
-
"
|
|
67
|
+
"vista3d_pretrained_model/model.pt with the conversion extra and save "
|
|
68
68
|
"mx.save_safetensors(<dir>/automatic.safetensors, "
|
|
69
69
|
"mlx_segment_ct.mlx_weights.convert_weights(model_pt, mx=mx)); point inference also "
|
|
70
70
|
"needs <dir>/correction.safetensors from mlx_correction_weights.convert_weights. Pass "
|
|
@@ -113,12 +113,25 @@ def run(
|
|
|
113
113
|
interpolates the scores trilinearly at each source voxel and decides its label
|
|
114
114
|
there, so boundaries follow the source resolution. ``"bundle"`` decides on the
|
|
115
115
|
1.5 mm grid and restores labels with nearest interpolation, as the NVIDIA bundle does.
|
|
116
|
+
Input affine values are assumed to be millimeters; NIfTI spatial-unit codes are
|
|
117
|
+
neither validated nor converted. Output NIfTI headers are newly constructed.
|
|
116
118
|
|
|
117
119
|
Weights are converted automatic.safetensors and, for points, correction.safetensors.
|
|
118
120
|
The result contains absolute output paths and JSON details. Masks preserve the
|
|
119
121
|
source shape and affine, with float32 global labels and 255 for uncovered voxels.
|
|
120
122
|
Existing outputs require ``overwrite=True``. Invalid requests, missing weights
|
|
121
123
|
and inference failures raise the corresponding medmlx-core error.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
image_path: Input CT or MRI NIfTI volume, according to the checkpoint.
|
|
127
|
+
weights_path: Directory containing converted ``automatic.safetensors``;
|
|
128
|
+
point inference also requires ``correction.safetensors``.
|
|
129
|
+
output_dir: Directory for the output mask; run details are returned.
|
|
130
|
+
segment_all: Request the checkpoint's all-classes set; cannot be combined
|
|
131
|
+
with class or point prompts. With no prompts, all classes are selected
|
|
132
|
+
even when this flag is false.
|
|
133
|
+
interactive: Require point-prompt mode; point inputs also select it when false.
|
|
134
|
+
overwrite: Replace an existing output mask when true; input aliases are refused.
|
|
122
135
|
"""
|
|
123
136
|
started = time.perf_counter()
|
|
124
137
|
for name, value in (
|
|
@@ -774,7 +787,7 @@ def validate_labels(labels: HostArray, class_ids: Sequence[int]) -> None:
|
|
|
774
787
|
def _publish(destination: Path, write: Callable[[Path], None]) -> None:
|
|
775
788
|
"""Write next to the destination, then replace it atomically."""
|
|
776
789
|
with NamedTemporaryFile(
|
|
777
|
-
dir=destination.parent, prefix=".
|
|
790
|
+
dir=destination.parent, prefix=".mlx-segment-", suffix=".nii.gz", delete=False
|
|
778
791
|
) as handle:
|
|
779
792
|
staged = Path(handle.name)
|
|
780
793
|
try:
|
|
@@ -17,6 +17,9 @@ from mlx_segment_ct.mlx_point import additional_shapes
|
|
|
17
17
|
def convert_state_dict(state_dict: object) -> dict[str, HostArray]:
|
|
18
18
|
"""Return only additional point tensors as contiguous source-layout FP32 arrays.
|
|
19
19
|
|
|
20
|
+
Unused tensors are ignored, and matching shapes and values do not establish
|
|
21
|
+
checkpoint identity or origin.
|
|
22
|
+
|
|
20
23
|
Raises:
|
|
21
24
|
InvalidInputError: a required point tensor is absent from ``state_dict``, or is
|
|
22
25
|
not finite float32 of the expected shape.
|
|
@@ -20,11 +20,13 @@ if TYPE_CHECKING:
|
|
|
20
20
|
def convert_state_dict[ArrayT: ArrayValue](
|
|
21
21
|
state_dict: object, *, mx: ArrayBoundary[ArrayT]
|
|
22
22
|
) -> dict[str, ArrayT]:
|
|
23
|
-
"""Select and validate the automatic graph; return FP32
|
|
23
|
+
"""Select and validate the automatic graph; return FP32 boundary arrays.
|
|
24
24
|
|
|
25
25
|
Keys and tensor layouts are unchanged. Point-head and point-decoder tensors
|
|
26
26
|
are excluded exactly as in the source converter: ``image_encoder.up_layers.`` is
|
|
27
27
|
the point decoder, while ``image_encoder.up_layers_auto.`` is kept.
|
|
28
|
+
``mx.array`` creates each result; the supplied boundary determines its array
|
|
29
|
+
backend. Tensor validation does not establish checkpoint identity or origin.
|
|
28
30
|
|
|
29
31
|
Raises:
|
|
30
32
|
InvalidInputError: the selected keys differ from the pinned graph, or a
|
|
@@ -69,7 +69,8 @@ class Projections:
|
|
|
69
69
|
With ``linear`` true, ``values`` is ``(rows, 48)`` (class MLP) and ``weight`` is
|
|
70
70
|
``(48, 48)``. Otherwise ``values`` is channel-first ``(1, 48, D, H, W)`` (the
|
|
71
71
|
encoder head, a 1x1x1 convolution) and ``weight`` is ``(48, 48, 1, 1, 1)``.
|
|
72
|
-
``bias`` is ``(48,)``. The result has the shape of ``values``.
|
|
72
|
+
``bias`` is ``(48,)``. The result has the shape of ``values``. Shapes
|
|
73
|
+
and dtypes are caller requirements and are not checked before dispatch.
|
|
73
74
|
"""
|
|
74
75
|
return self.kernel(
|
|
75
76
|
inputs=[values, weight, bias],
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|