mlx-segment-ct 0.2.1__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.

Files changed (28) hide show
  1. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/PKG-INFO +9 -9
  2. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/README.md +7 -7
  3. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/pyproject.toml +4 -4
  4. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/__init__.py +1 -1
  5. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/activations.py +5 -1
  6. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/bundle_transforms.py +14 -5
  7. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/checkpoint_sources.py +3 -0
  8. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/correction.py +3 -2
  9. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/correction_inferer.py +10 -3
  10. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/instance_norm.py +41 -7
  11. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/medmlx.py +17 -4
  12. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_correction_weights.py +3 -0
  13. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_network.py +17 -9
  14. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_weights.py +3 -1
  15. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/projections.py +2 -1
  16. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/.gitignore +0 -0
  17. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/LICENSE +0 -0
  18. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/THIRD_PARTY_NOTICES.md +0 -0
  19. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/_types.py +0 -0
  20. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/interactive.py +0 -0
  21. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/labels.py +0 -0
  22. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_point.py +0 -0
  23. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_point_window.py +0 -0
  24. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_upsample.py +0 -0
  25. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/mlx_worker.py +0 -0
  26. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/py.typed +0 -0
  27. {mlx_segment_ct-0.2.1 → mlx_segment_ct-0.3.0}/src/mlx_segment_ct/restoration.py +0 -0
  28. {mlx_segment_ct-0.2.1 → 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.2.1
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
@@ -8,7 +8,7 @@ License-File: LICENSE
8
8
  License-File: THIRD_PARTY_NOTICES.md
9
9
  Classifier: Operating System :: MacOS :: MacOS X
10
10
  Requires-Python: <3.15,>=3.13
11
- Requires-Dist: medmlx-core==0.2.3
11
+ Requires-Dist: medmlx-core==0.2.4
12
12
  Requires-Dist: nibabel<6,>=5.3
13
13
  Requires-Dist: numpy<3,>=2.0
14
14
  Requires-Dist: scipy<2,>=1.14
@@ -30,7 +30,7 @@ Description-Content-Type: text/markdown
30
30
 
31
31
  Segment CT anatomy automatically or with anatomy names and clicks, using NVIDIA VISTA-3D in native MLX.
32
32
 
33
- [Docs](docs/technical.md) · [MedMLX](https://github.com/MedMLX)
33
+ [Docs](https://github.com/MedMLX/mlx-segment-ct/blob/main/docs/technical.md) · [MedMLX](https://github.com/MedMLX)
34
34
 
35
35
  ![Automatic CT segmentation with selected organs and pelvic bones in 3D.](https://raw.githubusercontent.com/MedMLX/mlx-segment-ct/main/docs/showcase.png)
36
36
 
@@ -47,10 +47,7 @@ Segment CT anatomy automatically or with anatomy names and clicks, using NVIDIA
47
47
  ```bash
48
48
  uv venv --python 3.13
49
49
  source .venv/bin/activate
50
- repo="https://github.com/MedMLX/mlx-segment-ct"
51
- uv pip install \
52
- "mlx-segment-ct[conversion] @ git+$repo" \
53
- huggingface-hub
50
+ uv pip install "mlx-segment-ct[conversion]" huggingface-hub
54
51
  ```
55
52
 
56
53
  Download and convert the checkpoint once, then run:
@@ -63,7 +60,10 @@ from medmlx_core.runtime import import_mlx
63
60
  from mlx_segment_ct import mlx_correction_weights, mlx_weights
64
61
 
65
62
  mx = import_mlx()
66
- checkpoint = Path(hf_hub_download("nvidia/NV-Segment-CT", "vista3d_pretrained_model/model.pt"))
63
+ checkpoint = Path(hf_hub_download(
64
+ "nvidia/NV-Segment-CT", "vista3d_pretrained_model/model.pt",
65
+ revision="afb51518689f71e6abb367ee6301b2cd0225c66a",
66
+ ))
67
67
  out = Path("weights")
68
68
  out.mkdir(exist_ok=True)
69
69
  mx.save_safetensors(
@@ -94,6 +94,6 @@ Docs cover click prompts, interactive correction and the NV-Segment-CTMR checkpo
94
94
 
95
95
  ## License
96
96
 
97
- [Apache-2.0](LICENSE). See [third-party notices](THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
97
+ [Apache-2.0](https://github.com/MedMLX/mlx-segment-ct/blob/main/LICENSE). See [third-party notices](https://github.com/MedMLX/mlx-segment-ct/blob/main/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
98
98
 
99
99
  For research and education. Outputs require human review.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Segment CT anatomy automatically or with anatomy names and clicks, using NVIDIA VISTA-3D in native MLX.
4
4
 
5
- [Docs](docs/technical.md) · [MedMLX](https://github.com/MedMLX)
5
+ [Docs](https://github.com/MedMLX/mlx-segment-ct/blob/main/docs/technical.md) · [MedMLX](https://github.com/MedMLX)
6
6
 
7
7
  ![Automatic CT segmentation with selected organs and pelvic bones in 3D.](https://raw.githubusercontent.com/MedMLX/mlx-segment-ct/main/docs/showcase.png)
8
8
 
@@ -19,10 +19,7 @@ Segment CT anatomy automatically or with anatomy names and clicks, using NVIDIA
19
19
  ```bash
20
20
  uv venv --python 3.13
21
21
  source .venv/bin/activate
22
- repo="https://github.com/MedMLX/mlx-segment-ct"
23
- uv pip install \
24
- "mlx-segment-ct[conversion] @ git+$repo" \
25
- huggingface-hub
22
+ uv pip install "mlx-segment-ct[conversion]" huggingface-hub
26
23
  ```
27
24
 
28
25
  Download and convert the checkpoint once, then run:
@@ -35,7 +32,10 @@ from medmlx_core.runtime import import_mlx
35
32
  from mlx_segment_ct import mlx_correction_weights, mlx_weights
36
33
 
37
34
  mx = import_mlx()
38
- checkpoint = Path(hf_hub_download("nvidia/NV-Segment-CT", "vista3d_pretrained_model/model.pt"))
35
+ checkpoint = Path(hf_hub_download(
36
+ "nvidia/NV-Segment-CT", "vista3d_pretrained_model/model.pt",
37
+ revision="afb51518689f71e6abb367ee6301b2cd0225c66a",
38
+ ))
39
39
  out = Path("weights")
40
40
  out.mkdir(exist_ok=True)
41
41
  mx.save_safetensors(
@@ -66,6 +66,6 @@ Docs cover click prompts, interactive correction and the NV-Segment-CTMR checkpo
66
66
 
67
67
  ## License
68
68
 
69
- [Apache-2.0](LICENSE). See [third-party notices](THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
69
+ [Apache-2.0](https://github.com/MedMLX/mlx-segment-ct/blob/main/LICENSE). See [third-party notices](https://github.com/MedMLX/mlx-segment-ct/blob/main/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
70
70
 
71
71
  For research and education. Outputs require human review.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "mlx-segment-ct"
7
- version = "0.2.1"
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"]
@@ -13,14 +13,14 @@ license = "Apache-2.0 AND BSD-3-Clause"
13
13
  license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
14
14
  authors = [{ name = "Joseph Sandoval" }, { name = "Alfredo Sandoval Jr." }]
15
15
  dependencies = [
16
- "medmlx-core==0.2.3",
16
+ "medmlx-core==0.2.4",
17
17
  "nibabel>=5.3,<6",
18
18
  "numpy>=2.0,<3",
19
19
  "scipy>=1.14,<2",
20
20
  ]
21
21
 
22
22
  [project.entry-points."medmlx.models"]
23
- nv-segment-ct = "mlx_segment_ct.medmlx:MODEL"
23
+ mlx-segment-ct = "mlx_segment_ct.medmlx:MODEL"
24
24
 
25
25
  [project.optional-dependencies]
26
26
  conversion = ["torch>=2.13,<3"]
@@ -73,7 +73,7 @@ ban-relative-imports = "all"
73
73
  constraint-dependencies = ["setuptools>=84.1.0", "filelock>=4.2.1", "Pillow>=13,<14"]
74
74
 
75
75
  [tool.uv.sources]
76
- medmlx-core = { git = "https://github.com/MedMLX/medmlx.git", rev = "e765f0a94aa31e8dfcdc599e4a4206eaca84f8b0", subdirectory = "packages/core" }
76
+ medmlx-core = { git = "https://github.com/MedMLX/medmlx.git", rev = "f98e0924f50228e2b9509474947b9672054b3217", subdirectory = "packages/core" }
77
77
 
78
78
  [tool.hatch.build.targets.sdist]
79
79
  only-include = [
@@ -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.2.1"
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
- """Exact (erf-based) GELU of a float32 array; the result has the same shape."""
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). The result image is scaled to
236
- [0, 1] (see ``scale_intensity_percentiles`` for the equal-percentile case) on the
237
- RAS-oriented 1.5 mm foreground crop.
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
- """``SaveImaged(resample=False, output_dtype=float32)`` with NibabelWriter."""
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, giving values in (0, 1). The result is float32
16
- with the shape of ``points``.
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 centered on each click; otherwise up to three
88
- windows per axis (27 per click): centered, and with the click ``margin``
89
- voxels inside either edge.
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.
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  import struct
6
6
  from itertools import count
7
7
  from math import prod
8
- from typing import TYPE_CHECKING, cast
8
+ from typing import TYPE_CHECKING, Literal, cast
9
9
 
10
10
  from medmlx_core.typing import MetalKernel
11
11
 
@@ -80,14 +80,19 @@ _SOURCES = {
80
80
  """,
81
81
  ),
82
82
  "affine": (
83
- ["X", "SCALE", "BIAS"],
83
+ ["X", "SCALE", "BIAS", "RESIDUAL"],
84
84
  ["Y"],
85
85
  """
86
86
  uint i = thread_position_in_grid.x;
87
87
  if (i >= GROUPS * N) return;
88
88
  uint g = i / N;
89
89
  // Torch's vectorized affine rounds the multiplication before addition.
90
- Y[i] = X[i] * SCALE[g] + BIAS[g];
90
+ float value = X[i] * SCALE[g] + BIAS[g];
91
+ // Keep residual addition after the rounded affine, before activation.
92
+ if (ADD_RESIDUAL) value = value + RESIDUAL[i];
93
+ if (ACTIVATION == 1) value = isnan(value) ? value : max(value, 0.0f);
94
+ if (ACTIVATION == 2) value = value >= 0.0f ? value : 0.01f * value;
95
+ Y[i] = value;
91
96
  """,
92
97
  ),
93
98
  }
@@ -116,11 +121,23 @@ class InstanceNorm:
116
121
  for name, (inputs, outputs, source) in _SOURCES.items()
117
122
  }
118
123
 
119
- def __call__(self, values: array, weight: array, bias: array) -> array:
124
+ def __call__(
125
+ self,
126
+ values: array,
127
+ weight: array,
128
+ bias: array,
129
+ *,
130
+ activation: Literal["none", "relu", "leaky_relu"] = "none",
131
+ residual: array | None = None,
132
+ ) -> array:
120
133
  """Normalize each (sample, channel) over its spatial voxels, then scale and shift.
121
134
 
122
135
  ``values`` is float32 ``(B, C, D, H, W)``; ``weight`` and ``bias`` are ``(C,)``.
123
- Returns float32 with the shape of ``values``.
136
+ An optional float32 residual of the same shape is added after the affine,
137
+ before the activation (leaky ReLU uses slope 0.01). The two-pass moments
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.
124
141
  """
125
142
  batch, channels = values.shape[:2]
126
143
  size = prod(values.shape[2:])
@@ -131,9 +148,20 @@ class InstanceNorm:
131
148
  def run(
132
149
  name: str, inputs: list[array], shape: tuple[int, ...], *, variance: bool = False
133
150
  ) -> list[array]:
151
+ template: list[tuple[str, int | bool]] = [
152
+ *constants.items(),
153
+ ("VARIANCE", variance),
154
+ ]
155
+ if name == "affine":
156
+ template.extend(
157
+ [
158
+ ("ACTIVATION", ("none", "relu", "leaky_relu").index(activation)),
159
+ ("ADD_RESIDUAL", residual is not None),
160
+ ]
161
+ )
134
162
  return self.kernels[name](
135
163
  inputs=inputs,
136
- template=[*constants.items(), ("VARIANCE", variance)],
164
+ template=template,
137
165
  grid=(groups * tiles if name == "sum" else prod(shape), 1, 1),
138
166
  threadgroup=(256, 1, 1),
139
167
  output_shapes=[shape] * len(_SOURCES[name][1]),
@@ -146,4 +174,10 @@ class InstanceNorm:
146
174
  mean = run("mean", [totals], (groups,))[0]
147
175
  totals = run("sum", [values, mean], (groups, tiles, 2), variance=True)[0]
148
176
  scale, offset = run("coeff", [totals, mean, weight, bias, self.eps], (groups,))
149
- return run("affine", [values, scale, offset], tuple(values.shape))[0]
177
+ # The disabled residual slot uses an already contiguous small coefficient
178
+ # buffer, avoiding a second contiguous copy when values is a strided view.
179
+ return run(
180
+ "affine",
181
+ [values, scale, offset, scale if residual is None else residual],
182
+ tuple(values.shape),
183
+ )[0]
@@ -41,7 +41,7 @@ if TYPE_CHECKING:
41
41
  from mlx_segment_ct.restoration import ScoreRestorer
42
42
 
43
43
  MODEL = {
44
- "id": "nv-segment-ct",
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 = "nv_segment_ct_mask.nii.gz"
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
- "models/model.pt with the conversion extra and save "
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=".nv-segment-", suffix=".nii.gz", delete=False
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.
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  from collections.abc import Mapping, Sequence
6
6
  from math import prod
7
- from typing import TYPE_CHECKING, cast
7
+ from typing import TYPE_CHECKING, Literal, cast
8
8
 
9
9
  from mlx_segment_ct._types import ArrayValue, CoreRuntime
10
10
 
@@ -88,21 +88,29 @@ class FeatureModel:
88
88
  )
89
89
 
90
90
  def residual(self, x: array, prefix: str) -> array:
91
- y = self.conv(self.mx.maximum(self.norm(x, f"{prefix}.norm1"), 0), f"{prefix}.conv1")
92
- y = self.conv(self.mx.maximum(self.norm(y, f"{prefix}.norm2"), 0), f"{prefix}.conv2")
91
+ y = self.conv(self.norm(x, f"{prefix}.norm1", activation="relu"), f"{prefix}.conv1")
92
+ y = self.conv(self.norm(y, f"{prefix}.norm2", activation="relu"), f"{prefix}.conv2")
93
93
  return x + y
94
94
 
95
95
  def image_mapping(self, x: array, prefix: str) -> array:
96
- y = self.norm(self.conv(x, f"{prefix}.conv1.conv"), None)
97
- y = self.mx.where(y >= 0, y, 0.01 * y)
98
- y = self.norm(self.conv(y, f"{prefix}.conv2.conv"), None) + x
99
- return self.mx.where(y >= 0, y, 0.01 * y)
96
+ y = self.norm(self.conv(x, f"{prefix}.conv1.conv"), None, activation="leaky_relu")
97
+ return self.norm(
98
+ self.conv(y, f"{prefix}.conv2.conv"), None, activation="leaky_relu", residual=x
99
+ )
100
100
 
101
- def norm(self, x: array, prefix: str | None) -> array:
101
+ def norm(
102
+ self,
103
+ x: array,
104
+ prefix: str | None,
105
+ *,
106
+ activation: Literal["none", "relu", "leaky_relu"] = "none",
107
+ residual: array | None = None,
108
+ ) -> array:
109
+ """Normalize NCDHW values and fuse the caller's ordered affine epilogue."""
102
110
  channels = x.shape[1]
103
111
  weight = self.weights[f"{prefix}.weight"] if prefix else self.mx.ones((channels,))
104
112
  bias = self.weights[f"{prefix}.bias"] if prefix else self.mx.zeros((channels,))
105
- return self.instance_norm(x, weight, bias)
113
+ return self.instance_norm(x, weight, bias, activation=activation, residual=residual)
106
114
 
107
115
  def conv(self, x: array, prefix: str, *, padding: int = 1, stride: int = 1) -> array:
108
116
  return self.operators.conv(
@@ -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 MLX arrays.
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