lesiondiffusion-mlx 0.2.3__tar.gz → 0.2.5__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 lesiondiffusion-mlx might be problematic. Click here for more details.

Files changed (24) hide show
  1. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/PKG-INFO +6 -4
  2. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/README.md +2 -2
  3. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/THIRD_PARTY_NOTICES.md +5 -3
  4. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/pyproject.toml +7 -7
  5. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/__init__.py +2 -1
  6. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_nax_conv.py +1 -0
  7. lesiondiffusion_mlx-0.2.5/src/lesiondiffusion_mlx/_nifti.py +111 -0
  8. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_reference.py +1 -0
  9. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_schedules.py +1 -0
  10. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_source_half.py +2 -0
  11. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_typing.py +32 -43
  12. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/medmlx.py +13 -0
  13. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_model.py +14 -5
  14. lesiondiffusion_mlx-0.2.3/src/lesiondiffusion_mlx/_group_norm.py +0 -217
  15. lesiondiffusion_mlx-0.2.3/src/lesiondiffusion_mlx/_nifti.py +0 -73
  16. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/.gitignore +0 -0
  17. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/LICENSE +0 -0
  18. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_arrays.py +0 -0
  19. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_attention.py +0 -0
  20. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_spatial.py +0 -0
  21. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_pipeline.py +0 -0
  22. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_sampling.py +0 -0
  23. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/py.typed +0 -0
  24. {lesiondiffusion_mlx-0.2.3 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/reference.json +0 -0
@@ -1,8 +1,10 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lesiondiffusion-mlx
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: Native MLX implementation of LesionDiffusion
5
- Project-URL: Homepage, https://huggingface.co/MedMLX/lesiondiffusion-mlx
5
+ Project-URL: Homepage, https://medmlx.org
6
+ Project-URL: Repository, https://github.com/MedMLX/lesiondiffusion-mlx
7
+ Project-URL: Weights, https://huggingface.co/MedMLX/lesiondiffusion-mlx
6
8
  Author: Joseph Sandoval, Alfredo Sandoval Jr.
7
9
  License-Expression: Apache-2.0 AND MIT AND BSD-3-Clause
8
10
  License-File: LICENSE
@@ -47,7 +49,7 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
47
49
  ```bash
48
50
  uv venv --python 3.13
49
51
  source .venv/bin/activate
50
- uv pip install "lesiondiffusion-mlx>=0.2.3"
52
+ uv pip install "lesiondiffusion-mlx>=0.2.5"
51
53
  ```
52
54
 
53
55
  ```python
@@ -69,7 +71,7 @@ Weights download from `MedMLX/lesiondiffusion-mlx` on first use. A local native
69
71
  folder can also be passed as `weights_path`; it needs `model.safetensors` and
70
72
  `tokenizer.json`. Conversion receipts are not required.
71
73
 
72
- Version 0.2.3 accepts `lesion_mask_path` instead of `bbox_size_mm` to inpaint a supplied lesion shape. Inputs must support the documented crop sizes. Outputs use a RAS 1 mm grid; voxels outside the lesion can change. Synthetic output is not ground truth.
74
+ Use `lesion_mask_path` instead of `bbox_size_mm` to inpaint a supplied lesion shape. Inputs must support the documented crop sizes. Outputs use a RAS 1 mm grid; voxels outside the lesion can change. Synthetic output is not ground truth.
73
75
 
74
76
  ## License
75
77
 
@@ -15,7 +15,7 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
15
15
  ```bash
16
16
  uv venv --python 3.13
17
17
  source .venv/bin/activate
18
- uv pip install "lesiondiffusion-mlx>=0.2.3"
18
+ uv pip install "lesiondiffusion-mlx>=0.2.5"
19
19
  ```
20
20
 
21
21
  ```python
@@ -37,7 +37,7 @@ Weights download from `MedMLX/lesiondiffusion-mlx` on first use. A local native
37
37
  folder can also be passed as `weights_path`; it needs `model.safetensors` and
38
38
  `tokenizer.json`. Conversion receipts are not required.
39
39
 
40
- Version 0.2.3 accepts `lesion_mask_path` instead of `bbox_size_mm` to inpaint a supplied lesion shape. Inputs must support the documented crop sizes. Outputs use a RAS 1 mm grid; voxels outside the lesion can change. Synthetic output is not ground truth.
40
+ Use `lesion_mask_path` instead of `bbox_size_mm` to inpaint a supplied lesion shape. Inputs must support the documented crop sizes. Outputs use a RAS 1 mm grid; voxels outside the lesion can change. Synthetic output is not ground truth.
41
41
 
42
42
  ## License
43
43
 
@@ -142,6 +142,8 @@ POSSIBILITY OF SUCH DAMAGE.
142
142
 
143
143
  ## Showcase image
144
144
 
145
- The CT images are from [AMOS22](https://doi.org/10.5281/zenodo.7262581),
146
- Ji, Yuanfeng et al., licensed [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
147
- The showcase uses cropped views with model-derived overlays or maps.
145
+ The showcase uses cropped CT views from [AMOS22](https://doi.org/10.5281/zenodo.7262581)
146
+ by Yuanfeng Ji et al., with model-derived overlays or maps. The Zenodo record lists
147
+ CC BY 4.0, while the dataset archive's metadata lists CC BY-SA 4.0. The showcase
148
+ is shared under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)
149
+ pending clarification; the repository's Apache-2.0 license does not relicense it.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "lesiondiffusion-mlx"
7
- version = "0.2.3"
7
+ version = "0.2.5"
8
8
  description = "Native MLX implementation of LesionDiffusion"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.13,<3.15"
@@ -22,7 +22,9 @@ dependencies = [
22
22
  ]
23
23
 
24
24
  [project.urls]
25
- Homepage = "https://huggingface.co/MedMLX/lesiondiffusion-mlx"
25
+ Homepage = "https://medmlx.org"
26
+ Repository = "https://github.com/MedMLX/lesiondiffusion-mlx"
27
+ Weights = "https://huggingface.co/MedMLX/lesiondiffusion-mlx"
26
28
 
27
29
  [project.entry-points."medmlx.models"]
28
30
  lesiondiffusion = "lesiondiffusion_mlx.medmlx:MODEL"
@@ -59,14 +61,14 @@ line-length = 100
59
61
  target-version = "py313"
60
62
 
61
63
  [tool.ruff.lint]
62
- extend-select = ["TID251", "TID252", "ANN401"]
64
+ extend-select = ["TID251", "TID252"]
63
65
  select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
64
66
 
65
67
  [tool.pyright]
66
68
  include = ["scripts","src","tests","typings"]
67
- extraPaths = ["src"]
69
+ extraPaths = ["src", "scripts"]
68
70
  pythonVersion = "3.13"
69
- typeCheckingMode = "strict"
71
+ typeCheckingMode = "standard"
70
72
  enableTypeIgnoreComments = false
71
73
  reportUnnecessaryTypeIgnoreComment = "error"
72
74
 
@@ -74,8 +76,6 @@ reportUnnecessaryTypeIgnoreComment = "error"
74
76
  ban-relative-imports = "all"
75
77
 
76
78
  [tool.ruff.lint.flake8-tidy-imports.banned-api]
77
- "typing.Any" = {msg = "Use a precise type and parse untyped values at the boundary."}
78
- "typing_extensions.Any" = {msg = "Use a precise type and parse untyped values at the boundary."}
79
79
 
80
80
  [tool.hatch.build.targets.sdist]
81
81
  only-include = [
@@ -32,7 +32,7 @@ if TYPE_CHECKING:
32
32
  )
33
33
  from lesiondiffusion_mlx.mlx_sampling import DdimSampler as DdimSampler
34
34
 
35
- __version__ = "0.2.3"
35
+ __version__ = "0.2.5"
36
36
 
37
37
  __all__ = [
38
38
  "LINET_CONFIG",
@@ -48,6 +48,7 @@ __all__ = [
48
48
 
49
49
 
50
50
  def __getattr__(name: str) -> object:
51
+ """Load a public export from its module on first access."""
51
52
  if name not in __all__:
52
53
  raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
53
54
  module = (
@@ -392,6 +392,7 @@ def pack_upsample_weight(weight: Array, mx: Mlx) -> Array:
392
392
  # parity p reads padded source offset p + t. Plain FP32 additions, not an
393
393
  # einsum, whose matmul could run in TF32 under MLX_ENABLE_TF32.
394
394
  def fold(taps: Array) -> Array:
395
+ """Fold one upsampling tap into packed convolution weights."""
395
396
  k0, k1, k2 = taps[0], taps[1], taps[2]
396
397
  return mx.stack([mx.stack([k0, k1 + k2]), mx.stack([k0 + k1, k2])])
397
398
 
@@ -0,0 +1,111 @@
1
+ """The NIfTI surface used here, verified against NiBabel's image/header APIs."""
2
+
3
+ from os import PathLike
4
+ from typing import Literal, Protocol, cast
5
+
6
+ import nibabel
7
+ import numpy as np
8
+ from nibabel.filebasedimages import ImageFileError as ImageFileError
9
+
10
+ from lesiondiffusion_mlx._arrays import HostArray
11
+
12
+ type PathArg = str | PathLike[str]
13
+ type SpatialAffine = np.ndarray[tuple[int, ...], np.dtype[np.float64]]
14
+
15
+
16
+ class ArrayBuffer(Protocol):
17
+ def __array__(
18
+ self, dtype: np.dtype[np.generic] | None = None, copy: bool | None = None
19
+ ) -> HostArray:
20
+ """Convert the image data buffer to a host array."""
21
+ ...
22
+
23
+
24
+ class NiftiHeader(Protocol):
25
+ def get_zooms(self) -> tuple[float, ...]:
26
+ """Return voxel spacing from the header."""
27
+ ...
28
+ def get_xyzt_units(self) -> tuple[str, str]:
29
+ """Return spatial and temporal unit names."""
30
+ ...
31
+ def set_xyzt_units(self, xyz: str, t: str) -> None:
32
+ """Set spatial and temporal unit names."""
33
+ ...
34
+ def set_data_dtype(self, dtype: type[np.generic]) -> None:
35
+ """Set the stored image dtype."""
36
+ ...
37
+
38
+
39
+ class HeaderFactory(Protocol):
40
+ def from_header(self, header: NiftiHeader) -> NiftiHeader:
41
+ """Construct a NIfTI header from an existing header."""
42
+ ...
43
+
44
+
45
+ class NiftiImage(Protocol):
46
+ shape: tuple[int, ...]
47
+ affine: SpatialAffine
48
+ dataobj: ArrayBuffer | HostArray
49
+ header: NiftiHeader
50
+
51
+ def get_qform(self, *, coded: Literal[True]) -> tuple[SpatialAffine | None, int]:
52
+ """Return the qform affine and its code."""
53
+ ...
54
+ def get_sform(self, *, coded: Literal[True]) -> tuple[SpatialAffine | None, int]:
55
+ """Return the sform affine and its code."""
56
+ ...
57
+ def set_qform(self, affine: HostArray, code: int) -> None:
58
+ """Set the qform affine and code."""
59
+ ...
60
+ def set_sform(self, affine: HostArray, code: int) -> None:
61
+ """Set the sform affine and code."""
62
+ ...
63
+
64
+
65
+ class ImageFactory(Protocol):
66
+ def __call__(
67
+ self, dataobj: HostArray, affine: HostArray, header: NiftiHeader | None = None
68
+ ) -> NiftiImage:
69
+ """Construct a NIfTI image from data, affine, and header."""
70
+ ...
71
+
72
+
73
+ class OrientationFunctions(Protocol):
74
+ """The subset of ``nibabel.orientations`` used to resample to RAS 1 mm."""
75
+
76
+ def axcodes2ornt(self, axcodes: tuple[str, str, str]) -> HostArray:
77
+ """Convert axis codes to an orientation transform."""
78
+ ...
79
+ def ornt_transform(self, start_ornt: HostArray, end_ornt: HostArray) -> HostArray:
80
+ """Compute the transform between two orientations."""
81
+ ...
82
+ def apply_orientation(self, data: HostArray, ornt: HostArray) -> HostArray:
83
+ """Apply an orientation transform to image data."""
84
+ ...
85
+ def inv_ornt_aff(self, ornt: HostArray, shape: tuple[int, ...]) -> SpatialAffine:
86
+ """Return the inverse voxel affine for an orientation and shape."""
87
+ ...
88
+
89
+
90
+ class Nibabel(Protocol):
91
+ Nifti1Header: HeaderFactory
92
+ Nifti1Image: ImageFactory
93
+ orientations: OrientationFunctions
94
+
95
+ def load(self, filename: PathArg) -> NiftiImage:
96
+ """Load an image from a path."""
97
+ ...
98
+ def save(self, image: NiftiImage, filename: PathArg) -> None:
99
+ """Write a NIfTI image to a path."""
100
+ ...
101
+ def aff2axcodes(self, affine: HostArray) -> tuple[str | None, ...]:
102
+ """Derive axis codes from an affine."""
103
+ ...
104
+ def io_orientation(self, affine: HostArray) -> HostArray:
105
+ """Derive voxel-axis orientation from an affine."""
106
+ ...
107
+
108
+
109
+ # This adapter is used only for .nii/.nii.gz inputs and NIfTI output; the wider
110
+ # NiBabel loader supports unrelated image classes outside the runner contract.
111
+ nib = cast(Nibabel, nibabel)
@@ -25,6 +25,7 @@ class SourceReference(TypedDict):
25
25
 
26
26
 
27
27
  def _string(value: object) -> str:
28
+ """Require a string for a reference metadata field."""
28
29
  if not isinstance(value, str):
29
30
  raise ValueError("reference.json source names, revisions and labels must be strings")
30
31
  return value
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
 
6
6
  def _is_runtime_integer(value: object) -> bool:
7
+ """Recognize integer inputs while excluding booleans."""
7
8
  return isinstance(value, int) and not isinstance(value, bool)
8
9
 
9
10
 
@@ -342,9 +342,11 @@ def _norm_affine_kernels(mx: Mlx) -> tuple[MetalKernel, MetalKernel]:
342
342
 
343
343
  @lru_cache(maxsize=1)
344
344
  def _kernels(mx: Mlx) -> tuple[MetalKernel, MetalKernel, MetalKernel, MetalKernel, MetalKernel]:
345
+ """Build or reuse the source-order half-precision Metal kernels."""
345
346
  def kernel(
346
347
  name: str, inputs: list[str], output: str, source: str, header: str = ""
347
348
  ) -> MetalKernel:
349
+ """Construct one named source-order Metal kernel."""
348
350
  return mx.fast.metal_kernel(
349
351
  name="lesion_source_half_" + name,
350
352
  input_names=inputs,
@@ -2,18 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, Literal, Protocol
5
+ from typing import TYPE_CHECKING, Any, Protocol
6
6
 
7
7
  from tokenizers import Encoding
8
8
 
9
9
  from lesiondiffusion_mlx._arrays import HostArray as HostArray
10
10
 
11
11
  if TYPE_CHECKING:
12
- from collections.abc import Callable, Sequence
12
+ from collections.abc import Sequence
13
13
 
14
14
  import mlx.core as mx
15
15
  from medmlx_core.typing import FastRuntime as CoreFastRuntime
16
- from medmlx_core.typing import MlxRuntime
17
16
 
18
17
  type Array = mx.array
19
18
  type Dtype = mx.Dtype
@@ -25,12 +24,20 @@ if TYPE_CHECKING:
25
24
  value: HostArray | Array | ArrayValue,
26
25
  /,
27
26
  dtype: Dtype | None = None,
28
- ) -> Array: ...
27
+ ) -> Array:
28
+ """Construct a native array from values and an optional dtype."""
29
+ ...
29
30
 
30
31
  class TokenizerContract(Protocol):
31
- def enable_truncation(self, max_length: int) -> None: ...
32
- def enable_padding(self, *, length: int, pad_id: int, pad_token: str) -> None: ...
33
- def encode_batch(self, inputs: Sequence[str]) -> list[Encoding]: ...
32
+ def enable_truncation(self, max_length: int) -> None:
33
+ """Enable tokenizer truncation at the requested length."""
34
+ ...
35
+ def enable_padding(self, *, length: int, pad_id: int, pad_token: str) -> None:
36
+ """Configure tokenizer padding and its token ID."""
37
+ ...
38
+ def encode_batch(self, inputs: Sequence[str]) -> list[Encoding]:
39
+ """Encode a batch of input strings."""
40
+ ...
34
41
 
35
42
  class MetalKernel(Protocol):
36
43
  def __call__(
@@ -42,7 +49,9 @@ if TYPE_CHECKING:
42
49
  threadgroup: tuple[int, int, int],
43
50
  output_shapes: Sequence[Sequence[int]],
44
51
  output_dtypes: Sequence[Dtype],
45
- ) -> list[Array]: ...
52
+ ) -> list[Array]:
53
+ """Launch a Metal kernel and return its output arrays."""
54
+ ...
46
55
 
47
56
  class Fast(CoreFastRuntime, Protocol):
48
57
  def scaled_dot_product_attention(
@@ -55,7 +64,9 @@ if TYPE_CHECKING:
55
64
  mask: str | Array | None = None,
56
65
  sinks: Array | None = None,
57
66
  force_fused: bool = False,
58
- ) -> Array: ...
67
+ ) -> Array:
68
+ """Compute native scaled dot-product attention."""
69
+ ...
59
70
 
60
71
  def metal_kernel(
61
72
  self,
@@ -67,40 +78,19 @@ if TYPE_CHECKING:
67
78
  ensure_row_contiguous: bool = True,
68
79
  atomic_outputs: bool = False,
69
80
  compile_options: object | None = None,
70
- ) -> MetalKernel: ...
81
+ ) -> MetalKernel:
82
+ """Compile a named native Metal kernel."""
83
+ ...
71
84
 
72
85
  class Random(Protocol):
73
- def seed(self, seed: int) -> None: ...
74
- def normal(self, shape: Sequence[int]) -> Array: ...
75
-
76
- class Mlx(MlxRuntime, Protocol):
77
- """The MLX module surface consumed by this port, without importing it eagerly."""
78
-
79
- @property
80
- def fast(self) -> Fast: ...
81
-
82
- random: Random
83
-
84
- def addmm(self, c: Array, a: Array, b: Array, /) -> Array: ...
85
- def all(self, a: Array, /) -> Array: ...
86
- def argmin(self, a: Array, /, *, axis: int | None = None) -> Array: ...
87
- def clear_cache(self) -> None: ...
88
- def compile[**P, R](self, fun: Callable[P, R], /) -> Callable[P, R]: ...
89
- def contiguous(self, a: Array, /) -> Array: ...
90
- def cos(self, a: Array, /) -> Array: ...
91
- def device_info(self) -> dict[str, str | int]: ...
92
- def erf(self, a: Array, /) -> Array: ...
93
- def exp(self, a: Array, /) -> Array: ...
94
- def full(self, shape: Sequence[int], vals: object, *, dtype: Dtype) -> Array: ...
95
- def isfinite(self, a: Array, /) -> Array: ...
96
- def load(self, file: str, *, format: Literal["safetensors"]) -> dict[str, Array]: ...
97
- def reciprocal(self, a: Array, /) -> Array: ...
98
- def sin(self, a: Array, /) -> Array: ...
99
- def softmax(
100
- self, a: Array, /, *, axis: int | None = None, precise: bool = False
101
- ) -> Array: ...
102
- def sqrt(self, a: Array | float, /) -> Array: ...
103
- def sum(self, a: Array, /, *, axis: int | None = None, keepdims: bool = False) -> Array: ...
86
+ def seed(self, seed: int) -> None:
87
+ """Set the native random generator seed."""
88
+ ...
89
+ def normal(self, shape: Sequence[int]) -> Array:
90
+ """Draw normally distributed native values."""
91
+ ...
92
+
93
+ Mlx = Any
104
94
  else:
105
95
 
106
96
  class ArrayConstructor(Protocol):
@@ -118,5 +108,4 @@ else:
118
108
  class Random(Protocol):
119
109
  pass
120
110
 
121
- class Mlx(Protocol):
122
- pass
111
+ Mlx = Any
@@ -249,6 +249,7 @@ class LesionDiffusionOptions:
249
249
  output_region: str = DEFAULT_OUTPUT_REGION
250
250
 
251
251
  def __post_init__(self) -> None:
252
+ """Validate inference, geometry, and lesion-generation options."""
252
253
  if self.inference_mode not in {"conditioned", "source"}:
253
254
  raise InvalidInputError("LesionDiffusion inference_mode must be conditioned or source")
254
255
  if self.output_region not in {"full", "box"}:
@@ -495,6 +496,7 @@ def _run_paths(
495
496
  output_region: str,
496
497
  overwrite: bool,
497
498
  ) -> tuple[Path, Path, dict[str, Path]]:
499
+ """Resolve input and output paths and prevent output collisions."""
498
500
  if not isinstance(cast(object, overwrite), bool):
499
501
  raise InvalidInputError("overwrite must be a boolean")
500
502
  source = Path(image_path).expanduser().resolve()
@@ -542,6 +544,7 @@ def _execute_run(
542
544
  directory: Path,
543
545
  outputs: dict[str, Path],
544
546
  ) -> tuple[GenerationSpec, dict[str, dict[str, object]]]:
547
+ """Run native generation and write its validated outputs."""
545
548
  model_label, _ = source_organ_label(options.organ)
546
549
  report = _structured_report(
547
550
  reference=geometry.reference,
@@ -603,6 +606,7 @@ def _run_result(
603
606
  started_at: datetime,
604
607
  started: float,
605
608
  ) -> RunResult:
609
+ """Build the output paths and generation metadata for a completed run."""
606
610
  grid = [int(value) for value in geometry.output_reference.shape]
607
611
  details: RunDetails = {
608
612
  "model_id": MODEL_ID,
@@ -767,6 +771,7 @@ def run_native_pipeline(
767
771
  def _linet_attributes(
768
772
  attributes: Mapping[str, object], options: LesionDiffusionOptions
769
773
  ) -> dict[str, object]:
774
+ """Build image-synthesis text attributes for the selected organ and mode."""
770
775
  _, organ_name = source_organ_label(options.organ)
771
776
  omitted = {"size"}
772
777
  if options.inference_mode == "conditioned":
@@ -787,6 +792,7 @@ def _lmnet_attributes(
787
792
  attributes: Mapping[str, object],
788
793
  options: LesionDiffusionOptions,
789
794
  ) -> dict[str, object]:
795
+ """Build mask-synthesis text attributes using the pinned source conventions."""
790
796
  _, organ_name = source_organ_label(options.organ)
791
797
  lm_attributes = dict(attributes)
792
798
  lm_attributes["lesion location"] = organ_name
@@ -822,6 +828,7 @@ def _run_lmnet(
822
828
  *,
823
829
  anatomy: HostArray,
824
830
  ) -> tuple[BoolArray, dict[str, object]]:
831
+ """Generate and validate a lesion mask within the selected crop."""
825
832
  crop = source_crop(bbox, LMNET_CROP)
826
833
  lm_started = time.perf_counter()
827
834
  optimized = options.inference_mode == "conditioned"
@@ -890,6 +897,7 @@ def _run_linet(
890
897
  tokenizer_path: Path,
891
898
  mx: Mlx,
892
899
  ) -> tuple[HostArray, dict[str, object]]:
900
+ """Generate the lesion image using the selected mask and attributes."""
893
901
  lin_started = time.perf_counter()
894
902
  source_arithmetic = options.inference_mode == "source"
895
903
  linet = LdmUnet(
@@ -1156,6 +1164,7 @@ def load_stage(directory: Path, name: str, mx: Mlx, *, dtype: Dtype) -> dict[str
1156
1164
 
1157
1165
 
1158
1166
  def _load_json_object(path: Path) -> dict[str, object]:
1167
+ """Read a JSON object or report an invalid metadata file."""
1159
1168
  try:
1160
1169
  payload: object = json.loads(path.read_text(encoding="utf-8"))
1161
1170
  except (UnicodeError, json.JSONDecodeError) as exc:
@@ -1188,6 +1197,7 @@ def _parse_options(
1188
1197
  output_region: object = DEFAULT_OUTPUT_REGION,
1189
1198
  lesion_mask_supplied: bool = False,
1190
1199
  ) -> LesionDiffusionOptions:
1200
+ """Validate request values and construct generation options."""
1191
1201
  for name, value in (
1192
1202
  ("organ", organ),
1193
1203
  ("lesion_type", lesion_type),
@@ -1274,6 +1284,7 @@ def _check_box_source(
1274
1284
 
1275
1285
 
1276
1286
  def _is_integer(value: object) -> bool:
1287
+ """Recognize integer inputs while excluding booleans."""
1277
1288
  return isinstance(value, int) and not isinstance(value, bool)
1278
1289
 
1279
1290
 
@@ -2137,11 +2148,13 @@ def localize_output(
2137
2148
 
2138
2149
  def _with_comma(value: str) -> str:
2139
2150
  # Upstream report phrases are comma-terminated.
2151
+ """Normalize an upstream report phrase to end with one comma."""
2140
2152
  stripped = value.strip().rstrip(",")
2141
2153
  return f"{stripped},"
2142
2154
 
2143
2155
 
2144
2156
  def _json_safe(value: object) -> object:
2157
+ """Convert nested mappings, sequences, and NumPy scalars to JSON-compatible values."""
2145
2158
  if isinstance(value, Mapping):
2146
2159
  return {
2147
2160
  str(key): _json_safe(item) for key, item in cast(Mapping[object, object], value).items()
@@ -16,6 +16,11 @@ from typing import TYPE_CHECKING, cast
16
16
  if TYPE_CHECKING:
17
17
  from lesiondiffusion_mlx._typing import Array, Mlx
18
18
 
19
+ from medmlx_core.group_norm import (
20
+ group_norm_affine,
21
+ native_group_norm,
22
+ native_group_norm_eligible,
23
+ )
19
24
  from medmlx_core.ops import (
20
25
  conv3d_ncdhw,
21
26
  group_norm_ncdhw,
@@ -24,11 +29,6 @@ from medmlx_core.ops import (
24
29
  )
25
30
 
26
31
  from lesiondiffusion_mlx._attention import flash_attention, flash_eligible
27
- from lesiondiffusion_mlx._group_norm import (
28
- group_norm_affine,
29
- native_group_norm,
30
- native_group_norm_eligible,
31
- )
32
32
  from lesiondiffusion_mlx._nax_conv import (
33
33
  nax_available,
34
34
  nax_conv3d,
@@ -99,6 +99,7 @@ class SourceLayers:
99
99
  source_arithmetic: bool = True,
100
100
  native_kernels: bool | None = None,
101
101
  ):
102
+ """Initialize source-keyed weights and the selected native arithmetic."""
102
103
  self.weights = weights
103
104
  self.mx = mx
104
105
  self.source_arithmetic = source_arithmetic
@@ -188,6 +189,7 @@ class SourceLayers:
188
189
  return linear(x, weight, bias, self.mx).astype(dtype)
189
190
 
190
191
  def _affine_inputs(self, x: Array, key: str) -> tuple[Array, Array, Array | None]:
192
+ """Promote half inputs and weights for source-compatible affine accumulation."""
191
193
  weight = self.weights[key + ".weight"]
192
194
  bias = self.weights.get(key + ".bias")
193
195
  if x.dtype == self.mx.float16:
@@ -313,6 +315,7 @@ class SourceLayers:
313
315
  return silu(x, self.mx)
314
316
 
315
317
  def _native_norm(self, x: Array, key: str, *, groups: int, eps: float, silu: bool) -> Array:
318
+ """Apply the native group-normalization kernel with optional SiLU."""
316
319
  return native_group_norm(
317
320
  x,
318
321
  self.weights[key + ".weight"],
@@ -374,6 +377,7 @@ class LdmUnet(SourceLayers):
374
377
  fused_attention: bool = False,
375
378
  native_kernels: bool | None = None,
376
379
  ):
380
+ """Initialize the source UNet and its attention and arithmetic policies."""
377
381
  super().__init__(
378
382
  weights, mx, source_arithmetic=source_arithmetic, native_kernels=native_kernels
379
383
  )
@@ -383,10 +387,12 @@ class LdmUnet(SourceLayers):
383
387
  def silu(self, x: Array) -> Array:
384
388
  # Source nn.SiLU rounds once after the activation. VQ's separate
385
389
  # sigmoid/product deliberately retains its two half rounding steps.
390
+ """Apply SiLU with FP32 intermediate rounding and restore the input dtype."""
386
391
  return silu(x.astype(self.mx.float32), self.mx).astype(x.dtype)
387
392
 
388
393
  def softmax(self, x: Array) -> Array:
389
394
  # Torch softmax accumulates in float32, then returns the input dtype.
395
+ """Apply source-compatible precise softmax on the final axis."""
390
396
  return self.mx.softmax(x, axis=-1, precise=True)
391
397
 
392
398
  def residual(self, x: Array, emb: Array, key: str) -> Array:
@@ -432,6 +438,7 @@ class LdmUnet(SourceLayers):
432
438
  return self.dense(result, key + ".to_out.0")
433
439
 
434
440
  def split(tensor: Array) -> Array:
441
+ """Split projected tokens into attention heads."""
435
442
  return mx.transpose(
436
443
  mx.reshape(tensor, (tensor.shape[0], tensor.shape[1], heads, depth)), (0, 2, 1, 3)
437
444
  )
@@ -548,6 +555,7 @@ class VqAutoencoder(SourceLayers):
548
555
  """
549
556
 
550
557
  def residual(self, x: Array, key: str) -> Array:
558
+ """Apply one VQ autoencoder residual block."""
551
559
  h = self.norm_silu_conv(x, key + ".norm1", key + ".conv1", groups=16, eps=1e-6)
552
560
  if key + ".nin_shortcut.weight" in self.weights:
553
561
  x = self.conv(x, key + ".nin_shortcut", padding=0)
@@ -653,6 +661,7 @@ class BiomedTextEncoder(SourceLayers):
653
661
  )
654
662
 
655
663
  def split(tensor: Array) -> Array:
664
+ """Split text-attention projections into heads."""
656
665
  return mx.transpose(
657
666
  mx.reshape(tensor, (tensor.shape[0], tensor.shape[1], 12, 64)), (0, 2, 1, 3)
658
667
  )
@@ -1,217 +0,0 @@
1
- """Native NCDHW group normalization with an optional fused SiLU.
2
-
3
- Conditioned mode does not need the source-ordered Welford cascade in
4
- ``_source_half``. In NCDHW each ``(batch, group)`` is one contiguous run of
5
- ``C / G * D * H * W`` values, so statistics take three Metal dispatches:
6
-
7
- 1. Every threadgroup sums a ``CHUNK``-value slice of one group, shifted by the
8
- group's first value, accumulating the sum and sum of squares in FP32.
9
- 2. One thread per group converts each chunk to a mean and M2, merges chunks
10
- with Chan's parallel update, and writes each channel's FP32 scale and offset.
11
- 3. A vectorized pass applies ``scale * x + offset`` and, optionally,
12
- ``y / (1 + exp(-y))``, rounding once to the input dtype.
13
-
14
- Shifting by a sample of the group keeps the per-chunk sums well conditioned;
15
- the chunk merge avoids the global ``E[x^2] - E[x]^2`` cancellation. Results
16
- match FP32 statistics to FP32 rounding. For FP16 inputs the single rounding
17
- after SiLU differs from normalizing, rounding to FP16 and then applying SiLU.
18
- """
19
-
20
- from __future__ import annotations
21
-
22
- import math
23
- from functools import lru_cache
24
- from typing import TYPE_CHECKING, cast
25
-
26
- from lesiondiffusion_mlx._typing import ArrayConstructor
27
-
28
- if TYPE_CHECKING:
29
- from lesiondiffusion_mlx._typing import Array, MetalKernel, Mlx
30
-
31
- _CHUNK = 16384
32
- _THREADS = 256
33
-
34
- _PARTIAL = r"""
35
- const uint chunk = threadgroup_position_in_grid.x, bg = threadgroup_position_in_grid.y;
36
- const uint tid = thread_position_in_threadgroup.x;
37
- const ulong base = ulong(bg) * SIZE;
38
- const float shift = float(x[base]);
39
- const uint start = chunk * CHUNK, stop = min(start + CHUNK, uint(SIZE));
40
- float s = 0.0f, ss = 0.0f;
41
- for (uint i = start + tid * 4; i < stop; i += TG * 4) {
42
- const float4 v = float4(*reinterpret_cast<const device vec<T, 4>*>(x + base + i)) - shift;
43
- s += v.x + v.y + v.z + v.w;
44
- ss = fma(v.x, v.x, fma(v.y, v.y, fma(v.z, v.z, fma(v.w, v.w, ss))));
45
- }
46
- threadgroup float reduced[2][TG / 32];
47
- s = simd_sum(s);
48
- ss = simd_sum(ss);
49
- if (thread_index_in_simdgroup == 0) {
50
- reduced[0][simdgroup_index_in_threadgroup] = s;
51
- reduced[1][simdgroup_index_in_threadgroup] = ss;
52
- }
53
- threadgroup_barrier(mem_flags::mem_threadgroup);
54
- if (tid == 0) {
55
- float a = 0.0f, b = 0.0f;
56
- for (uint i = 0; i < TG / 32; i++) { a += reduced[0][i]; b += reduced[1][i]; }
57
- partials[(bg * CHUNKS + chunk) * 2] = a;
58
- partials[(bg * CHUNKS + chunk) * 2 + 1] = b;
59
- }
60
- """
61
-
62
- _AFFINE = r"""
63
- const uint bg = thread_position_in_grid.x;
64
- if (bg >= B * G) return;
65
- float count = 0.0f, mean = 0.0f, m2 = 0.0f;
66
- for (uint c = 0; c < CHUNKS; c++) {
67
- const float n = float(min(uint(CHUNK), uint(SIZE) - c * CHUNK));
68
- const float s = partials[(bg * CHUNKS + c) * 2], ss = partials[(bg * CHUNKS + c) * 2 + 1];
69
- const float chunk_mean = s / n;
70
- const float total = count + n;
71
- const float delta = chunk_mean - mean;
72
- mean += delta * (n / total);
73
- m2 += max(ss - s * chunk_mean, 0.0f) + delta * delta * (count * n / total);
74
- count = total;
75
- }
76
- mean += float(x[ulong(bg) * SIZE]);
77
- const float rstd = metal::precise::rsqrt(m2 / count + epsilon[0]);
78
- const uint g = bg % G, b = bg / G;
79
- for (uint j = 0; j < C / G; j++) {
80
- const uint c = g * (C / G) + j;
81
- const float scale = rstd * float(weight[c]);
82
- affine[(b * C + c) * 2] = scale;
83
- affine[(b * C + c) * 2 + 1] = float(bias[c]) - mean * scale;
84
- }
85
- """
86
-
87
- _APPLY = r"""
88
- const uint vector = thread_position_in_grid.x;
89
- const uint bc = thread_position_in_grid.y;
90
- if (vector * 4 >= SPATIAL) return;
91
- const ulong index = ulong(bc) * SPATIAL + vector * 4;
92
- const float scale = affine[bc * 2], offset = affine[bc * 2 + 1];
93
- float4 y = float4(*reinterpret_cast<const device vec<T, 4>*>(x + index)) * scale + offset;
94
- if (SILU) y = y / (1.0f + metal::precise::exp(-y));
95
- *reinterpret_cast<device vec<T, 4>*>(out + index) = vec<T, 4>(y);
96
- """
97
-
98
-
99
- @lru_cache(maxsize=1)
100
- def _kernels(mx: Mlx) -> tuple[MetalKernel, MetalKernel, MetalKernel]:
101
- return (
102
- mx.fast.metal_kernel(
103
- name="lesion_group_norm_partial",
104
- input_names=["x"],
105
- output_names=["partials"],
106
- source=_PARTIAL,
107
- ),
108
- mx.fast.metal_kernel(
109
- name="lesion_group_norm_affine",
110
- input_names=["x", "partials", "weight", "bias", "epsilon"],
111
- output_names=["affine"],
112
- source=_AFFINE,
113
- ),
114
- mx.fast.metal_kernel(
115
- name="lesion_group_norm_apply",
116
- input_names=["x", "affine"],
117
- output_names=["out"],
118
- source=_APPLY,
119
- ),
120
- )
121
-
122
-
123
- def native_group_norm_eligible(x: Array, groups: int) -> bool:
124
- """Whether NCDHW ``x`` fits the vectorized kernels: rank 5, ``groups | C``, ``4 | DHW``."""
125
- return (
126
- x.ndim == 5
127
- and int(x.shape[1]) % groups == 0
128
- and math.prod(int(size) for size in x.shape[2:]) % 4 == 0
129
- )
130
-
131
-
132
- def group_norm_affine(
133
- x: Array, weight: Array, bias: Array, *, groups: int, eps: float, mx: Mlx
134
- ) -> Array:
135
- """Fold NCDHW group statistics and the affine into per-channel FP32 pairs.
136
-
137
- Args:
138
- x: Contiguous ``(B, C, D, H, W)`` float16 or float32 input satisfying
139
- ``native_group_norm_eligible``.
140
- weight: Per-channel scale ``(C,)``.
141
- bias: Per-channel shift ``(C,)``.
142
- groups: Number of groups dividing ``C``.
143
- eps: Variance epsilon.
144
- mx: The imported ``mlx.core`` module.
145
-
146
- Returns:
147
- FP32 ``(B * C * 2)`` array; entries ``2 i`` and ``2 i + 1`` are the
148
- scale and offset that normalize channel ``i = b * C + c`` as
149
- ``x * scale + offset``.
150
- """
151
- batch, channels = int(x.shape[0]), int(x.shape[1])
152
- spatial = math.prod(int(size) for size in x.shape[2:])
153
- size = channels // groups * spatial
154
- chunks = -(-size // _CHUNK)
155
- partial_kernel, affine_kernel, _ = _kernels(mx)
156
- partials = partial_kernel(
157
- inputs=[x],
158
- template=[
159
- ("T", x.dtype),
160
- ("SIZE", size),
161
- ("CHUNK", _CHUNK),
162
- ("CHUNKS", chunks),
163
- ("TG", _THREADS),
164
- ],
165
- grid=(_THREADS * chunks, batch * groups, 1),
166
- threadgroup=(_THREADS, 1, 1),
167
- output_shapes=[(batch * groups * chunks * 2,)],
168
- output_dtypes=[mx.float32],
169
- )[0]
170
- epsilon = cast(ArrayConstructor, mx.array)([eps], dtype=mx.float32)
171
- return affine_kernel(
172
- inputs=[x, partials, weight, bias, epsilon],
173
- template=[
174
- ("B", batch),
175
- ("G", groups),
176
- ("C", channels),
177
- ("SIZE", size),
178
- ("CHUNK", _CHUNK),
179
- ("CHUNKS", chunks),
180
- ],
181
- grid=(batch * groups, 1, 1),
182
- threadgroup=(min(32, batch * groups), 1, 1),
183
- output_shapes=[(batch * channels * 2,)],
184
- output_dtypes=[mx.float32],
185
- )[0]
186
-
187
-
188
- def native_group_norm(
189
- x: Array, weight: Array, bias: Array, *, groups: int, eps: float, silu: bool, mx: Mlx
190
- ) -> Array:
191
- """Group-normalize NCDHW ``x`` with per-channel affine, then optionally SiLU.
192
-
193
- Args:
194
- x: ``(B, C, D, H, W)`` float16 or float32 input satisfying
195
- ``native_group_norm_eligible``.
196
- weight: Per-channel scale ``(C,)``.
197
- bias: Per-channel shift ``(C,)``.
198
- groups: Number of groups dividing ``C``.
199
- eps: Variance epsilon.
200
- silu: Apply SiLU to the FP32 normalized value before rounding.
201
- mx: The imported ``mlx.core`` module.
202
-
203
- Returns:
204
- Contiguous array with ``x``'s shape and dtype.
205
- """
206
- # Every kernel reads x; one shared contiguous copy avoids three.
207
- x = mx.contiguous(x)
208
- affine = group_norm_affine(x, weight, bias, groups=groups, eps=eps, mx=mx)
209
- spatial = math.prod(int(size) for size in x.shape[2:])
210
- return _kernels(mx)[2](
211
- inputs=[x, affine],
212
- template=[("T", x.dtype), ("SPATIAL", spatial), ("SILU", silu)],
213
- grid=(spatial // 4, int(x.shape[0]) * int(x.shape[1]), 1),
214
- threadgroup=(_THREADS, 1, 1),
215
- output_shapes=[tuple(x.shape)],
216
- output_dtypes=[x.dtype],
217
- )[0]
@@ -1,73 +0,0 @@
1
- """The NIfTI surface used here, verified against NiBabel's image/header APIs."""
2
-
3
- from os import PathLike
4
- from typing import Literal, Protocol, cast
5
-
6
- import nibabel
7
- import numpy as np
8
- from nibabel.filebasedimages import ImageFileError as ImageFileError
9
-
10
- from lesiondiffusion_mlx._arrays import HostArray
11
-
12
- type PathArg = str | PathLike[str]
13
- type SpatialAffine = np.ndarray[tuple[int, ...], np.dtype[np.float64]]
14
-
15
-
16
- class ArrayBuffer(Protocol):
17
- def __array__(
18
- self, dtype: np.dtype[np.generic] | None = None, copy: bool | None = None
19
- ) -> HostArray: ...
20
-
21
-
22
- class NiftiHeader(Protocol):
23
- def get_zooms(self) -> tuple[float, ...]: ...
24
- def get_xyzt_units(self) -> tuple[str, str]: ...
25
- def set_xyzt_units(self, xyz: str, t: str) -> None: ...
26
- def set_data_dtype(self, dtype: type[np.generic]) -> None: ...
27
-
28
-
29
- class HeaderFactory(Protocol):
30
- def from_header(self, header: NiftiHeader) -> NiftiHeader: ...
31
-
32
-
33
- class NiftiImage(Protocol):
34
- shape: tuple[int, ...]
35
- affine: SpatialAffine
36
- dataobj: ArrayBuffer | HostArray
37
- header: NiftiHeader
38
-
39
- def get_qform(self, *, coded: Literal[True]) -> tuple[SpatialAffine | None, int]: ...
40
- def get_sform(self, *, coded: Literal[True]) -> tuple[SpatialAffine | None, int]: ...
41
- def set_qform(self, affine: HostArray, code: int) -> None: ...
42
- def set_sform(self, affine: HostArray, code: int) -> None: ...
43
-
44
-
45
- class ImageFactory(Protocol):
46
- def __call__(
47
- self, dataobj: HostArray, affine: HostArray, header: NiftiHeader | None = None
48
- ) -> NiftiImage: ...
49
-
50
-
51
- class OrientationFunctions(Protocol):
52
- """The subset of ``nibabel.orientations`` used to resample to RAS 1 mm."""
53
-
54
- def axcodes2ornt(self, axcodes: tuple[str, str, str]) -> HostArray: ...
55
- def ornt_transform(self, start_ornt: HostArray, end_ornt: HostArray) -> HostArray: ...
56
- def apply_orientation(self, data: HostArray, ornt: HostArray) -> HostArray: ...
57
- def inv_ornt_aff(self, ornt: HostArray, shape: tuple[int, ...]) -> SpatialAffine: ...
58
-
59
-
60
- class Nibabel(Protocol):
61
- Nifti1Header: HeaderFactory
62
- Nifti1Image: ImageFactory
63
- orientations: OrientationFunctions
64
-
65
- def load(self, filename: PathArg) -> NiftiImage: ...
66
- def save(self, image: NiftiImage, filename: PathArg) -> None: ...
67
- def aff2axcodes(self, affine: HostArray) -> tuple[str | None, ...]: ...
68
- def io_orientation(self, affine: HostArray) -> HostArray: ...
69
-
70
-
71
- # This adapter is used only for .nii/.nii.gz inputs and NIfTI output; the wider
72
- # NiBabel loader supports unrelated image classes outside the runner contract.
73
- nib = cast(Nibabel, nibabel)