lesiondiffusion-mlx 0.2.6.post1__tar.gz → 0.2.7__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.
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/PKG-INFO +10 -11
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/README.md +8 -9
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/pyproject.toml +7 -5
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/__init__.py +1 -1
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_schedules.py +3 -3
- lesiondiffusion_mlx-0.2.7/src/lesiondiffusion_mlx/_typing.py +129 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/medmlx.py +21 -89
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/mlx_model.py +77 -2
- lesiondiffusion_mlx-0.2.6.post1/src/lesiondiffusion_mlx/_typing.py +0 -111
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/.gitignore +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/LICENSE +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/THIRD_PARTY_NOTICES.md +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_arrays.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_attention.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_nax_conv.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_nifti.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_reference.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_source_half.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_spatial.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/mlx_pipeline.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/mlx_sampling.py +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/py.typed +0 -0
- {lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/reference.json +0 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: lesiondiffusion-mlx
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.7
|
|
4
4
|
Summary: Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype
|
|
5
5
|
Project-URL: Homepage, https://medmlx.org
|
|
6
|
-
Project-URL: Documentation, https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.
|
|
6
|
+
Project-URL: Documentation, https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/README.md
|
|
7
7
|
Project-URL: Repository, https://github.com/MedMLX/lesiondiffusion-mlx
|
|
8
8
|
Project-URL: Issues, https://github.com/MedMLX/lesiondiffusion-mlx/issues
|
|
9
9
|
Project-URL: Weights, https://huggingface.co/MedMLX/lesiondiffusion-mlx
|
|
@@ -54,14 +54,14 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
|
|
|
54
54
|
|
|
55
55
|
[](https://pypi.org/project/lesiondiffusion-mlx/)
|
|
56
56
|
[](https://pypi.org/project/lesiondiffusion-mlx/)
|
|
57
|
-
[](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.
|
|
57
|
+
[](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/LICENSE)
|
|
58
58
|
[](https://github.com/ml-explore/mlx)
|
|
59
59
|
[](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
|
|
60
60
|
[](https://github.com/MedMLX/medmlx)
|
|
61
61
|
|
|
62
62
|
[Model weights](https://huggingface.co/MedMLX/lesiondiffusion-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
|
|
63
63
|
|
|
64
|
-
<img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.
|
|
64
|
+
<img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.7/docs/showcase.png" alt="CT with a synthetic lesion placed inside an organ mask" width="100%">
|
|
65
65
|
|
|
66
66
|
</div>
|
|
67
67
|
|
|
@@ -69,12 +69,11 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
|
|
|
69
69
|
| :--- | :--- |
|
|
70
70
|
| **Input** | CT + aligned binary organ mask |
|
|
71
71
|
| **Output** | Synthetic CT and lesion mask |
|
|
72
|
-
| **Hardware** | Apple Silicon with Metal; **
|
|
72
|
+
| **Hardware** | Apple Silicon with Metal; **3.46 GB** peak MLX memory for `lesiondiffusion` in source mode and **3.29 GB** in the default conditioned mode on a 160×160×128, 1 mm RAS crop. |
|
|
73
73
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
memory excludes host preprocessing and other applications.
|
|
74
|
+
Both measurements used an AMOS case 0008 crop and 200 diffusion steps: FP32 LMNet and
|
|
75
|
+
text encoders, FP16 LINet and VQ. They do not measure larger volumes. Peak MLX memory
|
|
76
|
+
excludes host preprocessing and other applications.
|
|
78
77
|
|
|
79
78
|
## Use with MedMLX
|
|
80
79
|
|
|
@@ -96,7 +95,7 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
|
|
|
96
95
|
```bash
|
|
97
96
|
uv venv --python 3.13
|
|
98
97
|
source .venv/bin/activate
|
|
99
|
-
uv pip install "lesiondiffusion-mlx>=0.2.
|
|
98
|
+
uv pip install "lesiondiffusion-mlx>=0.2.7"
|
|
100
99
|
```
|
|
101
100
|
|
|
102
101
|
## Run
|
|
@@ -177,6 +176,6 @@ only within MLX. Inference needs Apple Silicon with Metal and has no CPU fallbac
|
|
|
177
176
|
|
|
178
177
|
## License
|
|
179
178
|
|
|
180
|
-
[Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.
|
|
179
|
+
[Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
|
|
181
180
|
|
|
182
181
|
For research and education. Outputs require human review.
|
|
@@ -6,14 +6,14 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
|
|
|
6
6
|
|
|
7
7
|
[](https://pypi.org/project/lesiondiffusion-mlx/)
|
|
8
8
|
[](https://pypi.org/project/lesiondiffusion-mlx/)
|
|
9
|
-
[](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.
|
|
9
|
+
[](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/LICENSE)
|
|
10
10
|
[](https://github.com/ml-explore/mlx)
|
|
11
11
|
[](https://huggingface.co/MedMLX/lesiondiffusion-mlx)
|
|
12
12
|
[](https://github.com/MedMLX/medmlx)
|
|
13
13
|
|
|
14
14
|
[Model weights](https://huggingface.co/MedMLX/lesiondiffusion-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
|
|
15
15
|
|
|
16
|
-
<img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.
|
|
16
|
+
<img src="https://raw.githubusercontent.com/MedMLX/lesiondiffusion-mlx/v0.2.7/docs/showcase.png" alt="CT with a synthetic lesion placed inside an organ mask" width="100%">
|
|
17
17
|
|
|
18
18
|
</div>
|
|
19
19
|
|
|
@@ -21,12 +21,11 @@ Add synthetic lesions to CT with native MLX, with controls for organ, size, plac
|
|
|
21
21
|
| :--- | :--- |
|
|
22
22
|
| **Input** | CT + aligned binary organ mask |
|
|
23
23
|
| **Output** | Synthetic CT and lesion mask |
|
|
24
|
-
| **Hardware** | Apple Silicon with Metal; **
|
|
24
|
+
| **Hardware** | Apple Silicon with Metal; **3.46 GB** peak MLX memory for `lesiondiffusion` in source mode and **3.29 GB** in the default conditioned mode on a 160×160×128, 1 mm RAS crop. |
|
|
25
25
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
memory excludes host preprocessing and other applications.
|
|
26
|
+
Both measurements used an AMOS case 0008 crop and 200 diffusion steps: FP32 LMNet and
|
|
27
|
+
text encoders, FP16 LINet and VQ. They do not measure larger volumes. Peak MLX memory
|
|
28
|
+
excludes host preprocessing and other applications.
|
|
30
29
|
|
|
31
30
|
## Use with MedMLX
|
|
32
31
|
|
|
@@ -48,7 +47,7 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
|
|
|
48
47
|
```bash
|
|
49
48
|
uv venv --python 3.13
|
|
50
49
|
source .venv/bin/activate
|
|
51
|
-
uv pip install "lesiondiffusion-mlx>=0.2.
|
|
50
|
+
uv pip install "lesiondiffusion-mlx>=0.2.7"
|
|
52
51
|
```
|
|
53
52
|
|
|
54
53
|
## Run
|
|
@@ -129,6 +128,6 @@ only within MLX. Inference needs Apple Silicon with Metal and has no CPU fallbac
|
|
|
129
128
|
|
|
130
129
|
## License
|
|
131
130
|
|
|
132
|
-
[Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.
|
|
131
|
+
[Apache-2.0](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/LICENSE). See [third-party notices](https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
|
|
133
132
|
|
|
134
133
|
For research and education. Outputs require human review.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "lesiondiffusion-mlx"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.7"
|
|
8
8
|
description = "Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.13,<3.14"
|
|
@@ -48,7 +48,7 @@ dependencies = [
|
|
|
48
48
|
|
|
49
49
|
[project.urls]
|
|
50
50
|
Homepage = "https://medmlx.org"
|
|
51
|
-
Documentation = "https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.
|
|
51
|
+
Documentation = "https://github.com/MedMLX/lesiondiffusion-mlx/blob/v0.2.7/README.md"
|
|
52
52
|
Repository = "https://github.com/MedMLX/lesiondiffusion-mlx"
|
|
53
53
|
Issues = "https://github.com/MedMLX/lesiondiffusion-mlx/issues"
|
|
54
54
|
Weights = "https://huggingface.co/MedMLX/lesiondiffusion-mlx"
|
|
@@ -94,10 +94,10 @@ extend-select = ["TID251", "TID252"]
|
|
|
94
94
|
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
|
|
95
95
|
|
|
96
96
|
[tool.pyright]
|
|
97
|
-
include = ["
|
|
98
|
-
extraPaths = ["src"
|
|
97
|
+
include = ["src", "tests", "typings"]
|
|
98
|
+
extraPaths = ["src"]
|
|
99
99
|
pythonVersion = "3.13"
|
|
100
|
-
typeCheckingMode = "
|
|
100
|
+
typeCheckingMode = "strict"
|
|
101
101
|
enableTypeIgnoreComments = false
|
|
102
102
|
reportUnnecessaryTypeIgnoreComment = "error"
|
|
103
103
|
|
|
@@ -105,6 +105,8 @@ reportUnnecessaryTypeIgnoreComment = "error"
|
|
|
105
105
|
ban-relative-imports = "all"
|
|
106
106
|
|
|
107
107
|
[tool.ruff.lint.flake8-tidy-imports.banned-api]
|
|
108
|
+
"typing.Any" = {msg = "Use a precise type and parse untyped values at the boundary."}
|
|
109
|
+
"typing_extensions.Any" = {msg = "Use a precise type and parse untyped values at the boundary."}
|
|
108
110
|
|
|
109
111
|
[tool.hatch.build.targets.sdist]
|
|
110
112
|
only-include = [
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_schedules.py
RENAMED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
def
|
|
6
|
+
def is_integer(value: object) -> bool:
|
|
7
7
|
"""Recognize integer inputs while excluding booleans."""
|
|
8
8
|
return isinstance(value, int) and not isinstance(value, bool)
|
|
9
9
|
|
|
@@ -26,9 +26,9 @@ def lesion_diffusion_timesteps(steps: int, total: int = 1000) -> tuple[int, ...]
|
|
|
26
26
|
``total < steps``, or the last index would reach ``total`` (for example
|
|
27
27
|
``steps=3`` or ``steps=1000`` with ``total=1000``).
|
|
28
28
|
"""
|
|
29
|
-
if not
|
|
29
|
+
if not is_integer(steps) or steps < 1:
|
|
30
30
|
raise ValueError("LesionDiffusion DDIM steps must be a positive integer")
|
|
31
|
-
if not
|
|
31
|
+
if not is_integer(total) or total < steps:
|
|
32
32
|
raise ValueError("LesionDiffusion DDIM schedule must contain at least as many timesteps")
|
|
33
33
|
timesteps = tuple(value + 1 for value in range(0, total, total // steps))
|
|
34
34
|
if timesteps[-1] >= total:
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Native array and dependency contracts used by the source implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Protocol
|
|
6
|
+
|
|
7
|
+
from lesiondiffusion_mlx._arrays import HostArray as HostArray
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from typing import Literal, overload
|
|
12
|
+
|
|
13
|
+
import mlx.core as mx
|
|
14
|
+
from medmlx_core.typing import FastRuntime as CoreFastRuntime
|
|
15
|
+
from medmlx_core.typing import MlxRuntime as CoreMlxRuntime
|
|
16
|
+
from tokenizers import Encoding
|
|
17
|
+
|
|
18
|
+
type Array = mx.array
|
|
19
|
+
type Dtype = mx.Dtype
|
|
20
|
+
type ArrayValue = bool | int | float | complex | list[ArrayValue] | tuple[ArrayValue, ...]
|
|
21
|
+
|
|
22
|
+
class TokenizerContract(Protocol):
|
|
23
|
+
def enable_truncation(self, max_length: int) -> None:
|
|
24
|
+
"""Enable tokenizer truncation at the requested length."""
|
|
25
|
+
...
|
|
26
|
+
def enable_padding(self, *, length: int, pad_id: int, pad_token: str) -> None:
|
|
27
|
+
"""Configure tokenizer padding and its token ID."""
|
|
28
|
+
...
|
|
29
|
+
def encode_batch(self, inputs: Sequence[str]) -> list[Encoding]:
|
|
30
|
+
"""Encode a batch of input strings."""
|
|
31
|
+
...
|
|
32
|
+
|
|
33
|
+
class MetalKernel(Protocol):
|
|
34
|
+
def __call__(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
inputs: Sequence[Array],
|
|
38
|
+
template: Sequence[tuple[str, int | bool | Dtype]],
|
|
39
|
+
grid: tuple[int, int, int],
|
|
40
|
+
threadgroup: tuple[int, int, int],
|
|
41
|
+
output_shapes: Sequence[Sequence[int]],
|
|
42
|
+
output_dtypes: Sequence[Dtype],
|
|
43
|
+
) -> list[Array]:
|
|
44
|
+
"""Launch a Metal kernel and return its output arrays."""
|
|
45
|
+
...
|
|
46
|
+
|
|
47
|
+
class Fast(CoreFastRuntime, Protocol):
|
|
48
|
+
"""The part of ``mx.fast`` used here, with typed Metal-kernel construction."""
|
|
49
|
+
|
|
50
|
+
scaled_dot_product_attention = staticmethod(mx.fast.scaled_dot_product_attention)
|
|
51
|
+
|
|
52
|
+
def metal_kernel(
|
|
53
|
+
self,
|
|
54
|
+
name: str,
|
|
55
|
+
input_names: Sequence[str],
|
|
56
|
+
output_names: Sequence[str],
|
|
57
|
+
source: str,
|
|
58
|
+
header: str = "",
|
|
59
|
+
ensure_row_contiguous: bool = True,
|
|
60
|
+
atomic_outputs: bool = False,
|
|
61
|
+
compile_options: object | None = None,
|
|
62
|
+
) -> MetalKernel:
|
|
63
|
+
"""Compile a named Metal kernel with the supplied source."""
|
|
64
|
+
...
|
|
65
|
+
|
|
66
|
+
class Random(Protocol):
|
|
67
|
+
normal = staticmethod(mx.random.normal)
|
|
68
|
+
seed = staticmethod(mx.random.seed)
|
|
69
|
+
|
|
70
|
+
class Mlx(CoreMlxRuntime, Protocol):
|
|
71
|
+
"""Native ``mlx.core`` operations injected into the model and pipeline."""
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def fast(self) -> Fast:
|
|
75
|
+
"""Return native fast operations and Metal-kernel construction."""
|
|
76
|
+
...
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def random(self) -> Random:
|
|
80
|
+
"""Return native random generation operations."""
|
|
81
|
+
...
|
|
82
|
+
|
|
83
|
+
@overload
|
|
84
|
+
def load(
|
|
85
|
+
self,
|
|
86
|
+
file: str,
|
|
87
|
+
/,
|
|
88
|
+
format: Literal["safetensors"],
|
|
89
|
+
return_metadata: Literal[False] = False,
|
|
90
|
+
) -> dict[str, Array]:
|
|
91
|
+
"""Load a safetensors file as a name-to-array mapping."""
|
|
92
|
+
...
|
|
93
|
+
|
|
94
|
+
@overload
|
|
95
|
+
def load(
|
|
96
|
+
self, file: str, /, format: str | None = None, return_metadata: bool = False
|
|
97
|
+
) -> Array | dict[str, Array] | tuple[dict[str, Array], dict[str, object]]:
|
|
98
|
+
"""Load arrays, and optionally metadata, from a supported file format."""
|
|
99
|
+
...
|
|
100
|
+
|
|
101
|
+
addmm = staticmethod(mx.addmm)
|
|
102
|
+
all = staticmethod(mx.all)
|
|
103
|
+
argmin = staticmethod(mx.argmin)
|
|
104
|
+
clear_cache = staticmethod(mx.clear_cache)
|
|
105
|
+
compile = staticmethod(mx.compile)
|
|
106
|
+
contiguous = staticmethod(mx.contiguous)
|
|
107
|
+
cos = staticmethod(mx.cos)
|
|
108
|
+
device_info = staticmethod(mx.device_info)
|
|
109
|
+
erf = staticmethod(mx.erf)
|
|
110
|
+
exp = staticmethod(mx.exp)
|
|
111
|
+
full = staticmethod(mx.full)
|
|
112
|
+
isfinite = staticmethod(mx.isfinite)
|
|
113
|
+
reciprocal = staticmethod(mx.reciprocal)
|
|
114
|
+
sin = staticmethod(mx.sin)
|
|
115
|
+
softmax = staticmethod(mx.softmax)
|
|
116
|
+
sqrt = staticmethod(mx.sqrt)
|
|
117
|
+
sum = staticmethod(mx.sum)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# Defined at runtime because callers pass it to ``typing.cast`` unquoted.
|
|
121
|
+
class ArrayConstructor(Protocol):
|
|
122
|
+
def __call__(
|
|
123
|
+
self,
|
|
124
|
+
value: HostArray | Array | ArrayValue,
|
|
125
|
+
/,
|
|
126
|
+
dtype: Dtype | None = None,
|
|
127
|
+
) -> Array:
|
|
128
|
+
"""Construct a native array from values and an optional dtype."""
|
|
129
|
+
...
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/medmlx.py
RENAMED
|
@@ -11,15 +11,14 @@ human review.
|
|
|
11
11
|
from __future__ import annotations
|
|
12
12
|
|
|
13
13
|
import gc
|
|
14
|
-
import json
|
|
15
14
|
import math
|
|
16
|
-
import os
|
|
17
15
|
import time
|
|
18
16
|
from collections.abc import Callable, Mapping, Sequence
|
|
19
17
|
from dataclasses import dataclass, replace
|
|
20
18
|
from datetime import UTC, datetime
|
|
21
19
|
from os import PathLike
|
|
22
20
|
from pathlib import Path
|
|
21
|
+
from tempfile import TemporaryDirectory
|
|
23
22
|
from typing import TYPE_CHECKING, Final, Literal, NotRequired, TypedDict, cast
|
|
24
23
|
|
|
25
24
|
import numpy as np
|
|
@@ -35,6 +34,7 @@ from medmlx_core.weights import weights_dir, weights_revision
|
|
|
35
34
|
from lesiondiffusion_mlx._arrays import BoolArray, FloatArray, HostArray, NumericArray
|
|
36
35
|
from lesiondiffusion_mlx._nifti import ImageFileError, NiftiImage, nib
|
|
37
36
|
from lesiondiffusion_mlx._reference import REFERENCE as _REFERENCE
|
|
37
|
+
from lesiondiffusion_mlx._schedules import is_integer
|
|
38
38
|
from lesiondiffusion_mlx._typing import ArrayConstructor
|
|
39
39
|
|
|
40
40
|
if TYPE_CHECKING:
|
|
@@ -68,12 +68,9 @@ DEFAULT_OUTPUT_REGION: Final = "full"
|
|
|
68
68
|
# blended into the input CT over this margin; farther voxels retain its float32 cast.
|
|
69
69
|
LOCALIZATION_MARGIN_MM: Final = 6.0
|
|
70
70
|
SOURCE_REF: Final[str] = _REFERENCE["revision"]
|
|
71
|
-
CONVERSION_SCHEMA: Final = "medmlx.lesiondiffusion.weights.v1"
|
|
72
|
-
CONVERSION_VERSION: Final = 1
|
|
73
71
|
WEIGHT_STAGES: Final = ("lmnet", "linet", "vq", "lmnet_text", "linet_text")
|
|
74
72
|
SOURCE_INFERENCE_STAGES: Final = tuple(name for name in WEIGHT_STAGES if name != "linet_text")
|
|
75
73
|
TOKENIZER_FILE: Final = "tokenizer.json"
|
|
76
|
-
CONVERSION_FILE: Final = "conversion.json"
|
|
77
74
|
WARNING: Final = (
|
|
78
75
|
"Synthetic lesion output requires human review and is not patient data or ground truth."
|
|
79
76
|
)
|
|
@@ -111,8 +108,9 @@ MODEL: Final[dict[str, str | float]] = {
|
|
|
111
108
|
"Insert one phenotype-controlled synthetic lesion into a CT, given a binary organ "
|
|
112
109
|
"mask, or inpaint a supplied binary lesion mask. Outputs use a RAS 1 mm grid."
|
|
113
110
|
),
|
|
114
|
-
# README: source mode
|
|
115
|
-
|
|
111
|
+
# README: source mode (the larger of the two modes), 200 steps, 160x160x128
|
|
112
|
+
# RAS 1 mm AMOS case 0008 crop.
|
|
113
|
+
"peak_memory_gb": 3.46,
|
|
116
114
|
}
|
|
117
115
|
|
|
118
116
|
|
|
@@ -283,17 +281,17 @@ class LesionDiffusionOptions:
|
|
|
283
281
|
if self.bbox_center_voxel is not None:
|
|
284
282
|
if len(self.bbox_center_voxel) != 3:
|
|
285
283
|
raise InvalidInputError("LesionDiffusion bbox_center_voxel must contain I, J, K")
|
|
286
|
-
if any(not
|
|
284
|
+
if any(not is_integer(value) for value in self.bbox_center_voxel):
|
|
287
285
|
raise InvalidInputError("LesionDiffusion bbox_center_voxel values must be integers")
|
|
288
286
|
if any(value < 0 for value in self.bbox_center_voxel):
|
|
289
287
|
raise InvalidInputError("LesionDiffusion bbox_center_voxel must not be negative")
|
|
290
|
-
if not
|
|
288
|
+
if not is_integer(self.diffusion_steps):
|
|
291
289
|
raise InvalidInputError("LesionDiffusion diffusion_steps must be an integer")
|
|
292
290
|
try:
|
|
293
291
|
lesion_diffusion_timesteps(self.diffusion_steps)
|
|
294
292
|
except ValueError as exc:
|
|
295
293
|
raise InvalidInputError(str(exc)) from exc
|
|
296
|
-
if not
|
|
294
|
+
if not is_integer(self.seed):
|
|
297
295
|
raise InvalidInputError("LesionDiffusion seed must be an integer")
|
|
298
296
|
if self.seed < 0:
|
|
299
297
|
raise InvalidInputError("LesionDiffusion seed must not be negative")
|
|
@@ -434,7 +432,7 @@ def run(
|
|
|
434
432
|
would overwrite an input or an existing file.
|
|
435
433
|
AssetNotReadyError: If the weights directory is missing or not current.
|
|
436
434
|
ModelExecutionError: If a stage produces non-finite values, LMNet yields an
|
|
437
|
-
empty lesion mask, or
|
|
435
|
+
empty lesion mask, or MLX raises a runtime error during execution.
|
|
438
436
|
"""
|
|
439
437
|
|
|
440
438
|
options = _parse_options(
|
|
@@ -485,7 +483,8 @@ def run(
|
|
|
485
483
|
spec, stages = _execute_run(geometry, options, directory, outputs)
|
|
486
484
|
except MedmlxError:
|
|
487
485
|
raise
|
|
488
|
-
except
|
|
486
|
+
except RuntimeError as exc:
|
|
487
|
+
# MLX and Metal failures surface as RuntimeError; report them as execution errors.
|
|
489
488
|
raise ModelExecutionError(f"LesionDiffusion failed during execution: {exc}") from exc
|
|
490
489
|
return _run_result(options, geometry, outputs, directory, spec, stages, started_at, started)
|
|
491
490
|
|
|
@@ -518,7 +517,7 @@ def _run_paths(
|
|
|
518
517
|
if output.exists() and not output.is_dir():
|
|
519
518
|
raise InvalidInputError(f"LesionDiffusion output path is not a directory: {output}")
|
|
520
519
|
if not overwrite:
|
|
521
|
-
existing = [path for path in outputs.values() if path.exists()]
|
|
520
|
+
existing = [path for path in outputs.values() if path.exists() or path.is_symlink()]
|
|
522
521
|
if existing:
|
|
523
522
|
raise InvalidInputError(
|
|
524
523
|
f"{existing[0]} already exists; pass overwrite=true to replace outputs"
|
|
@@ -843,6 +842,8 @@ def _run_lmnet(
|
|
|
843
842
|
)
|
|
844
843
|
text = BiomedTextEncoder(load_stage(directory, "lmnet_text", mx, dtype=mx.float32), mx)
|
|
845
844
|
condition = encode_attributes(lm_attributes, text, tokenizer_path, mx)
|
|
845
|
+
# The evaluated condition no longer needs the 0.44 GB FP32 text encoder.
|
|
846
|
+
del text
|
|
846
847
|
denoiser = mx.compile(lmnet.__call__) if optimized else lmnet.__call__
|
|
847
848
|
# Conditioning channels: anatomy label id / 104 (the upstream label count),
|
|
848
849
|
# target organ, box; shape (1, 3, *LMNET_CROP).
|
|
@@ -867,7 +868,7 @@ def _run_lmnet(
|
|
|
867
868
|
if int(np.sum(component)) > (50 if "stone" in options.lesion_type else 400):
|
|
868
869
|
break
|
|
869
870
|
# Release LMNet before LINet and the VQ autoencoder load, to bound peak memory.
|
|
870
|
-
del lmnet, denoiser,
|
|
871
|
+
del lmnet, denoiser, condition, conditioning, sampler, samples
|
|
871
872
|
gc.collect()
|
|
872
873
|
mx.clear_cache()
|
|
873
874
|
if not np.any(lesion):
|
|
@@ -1113,44 +1114,6 @@ def require_weights(path: _PathArg, *, inference_mode: str = DEFAULT_INFERENCE_M
|
|
|
1113
1114
|
return directory
|
|
1114
1115
|
|
|
1115
1116
|
|
|
1116
|
-
def load_conversion(directory: Path) -> dict[str, object]:
|
|
1117
|
-
"""Read and check ``conversion.json``; return its provenance fields.
|
|
1118
|
-
|
|
1119
|
-
Raises:
|
|
1120
|
-
ValueError: If the file is not a JSON object, or its schema, source revision,
|
|
1121
|
-
EMA flag, layout or precision profile is not the current one.
|
|
1122
|
-
OSError: If the file cannot be read.
|
|
1123
|
-
"""
|
|
1124
|
-
metadata = _load_json_object(directory / CONVERSION_FILE)
|
|
1125
|
-
if (
|
|
1126
|
-
metadata.get("schema_version") != CONVERSION_SCHEMA
|
|
1127
|
-
or metadata.get("source_ref") != SOURCE_REF
|
|
1128
|
-
):
|
|
1129
|
-
raise ValueError("LesionDiffusion MLX conversion schema/source is not current")
|
|
1130
|
-
if metadata.get("converter_version") != CONVERSION_VERSION or metadata.get("ema") is not True:
|
|
1131
|
-
raise ValueError("LesionDiffusion MLX conversion must use current EMA conversion")
|
|
1132
|
-
if metadata.get("layout") != "source_torch_ncdhw" or metadata.get("stored_dtype") != "float32":
|
|
1133
|
-
raise ValueError("LesionDiffusion MLX conversion layout/dtype is not current")
|
|
1134
|
-
if metadata.get("inference_dtype") != {
|
|
1135
|
-
"lmnet": "float32",
|
|
1136
|
-
"linet": "float16",
|
|
1137
|
-
"vq": "float16",
|
|
1138
|
-
}:
|
|
1139
|
-
raise ValueError("LesionDiffusion MLX conversion precision profile is not current")
|
|
1140
|
-
return {
|
|
1141
|
-
key: metadata[key]
|
|
1142
|
-
for key in (
|
|
1143
|
-
"schema_version",
|
|
1144
|
-
"converter_version",
|
|
1145
|
-
"source_ref",
|
|
1146
|
-
"layout",
|
|
1147
|
-
"stored_dtype",
|
|
1148
|
-
"inference_dtype",
|
|
1149
|
-
"ema",
|
|
1150
|
-
)
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
1117
|
def load_stage(directory: Path, name: str, mx: Mlx, *, dtype: Dtype) -> dict[str, Array]:
|
|
1155
1118
|
"""Load one stage from the native safetensors bundle and cast its arrays.
|
|
1156
1119
|
|
|
@@ -1165,17 +1128,6 @@ def load_stage(directory: Path, name: str, mx: Mlx, *, dtype: Dtype) -> dict[str
|
|
|
1165
1128
|
}
|
|
1166
1129
|
|
|
1167
1130
|
|
|
1168
|
-
def _load_json_object(path: Path) -> dict[str, object]:
|
|
1169
|
-
"""Read a JSON object or report an invalid metadata file."""
|
|
1170
|
-
try:
|
|
1171
|
-
payload: object = json.loads(path.read_text(encoding="utf-8"))
|
|
1172
|
-
except (UnicodeError, json.JSONDecodeError) as exc:
|
|
1173
|
-
raise ValueError(f"Could not read JSON object: {path}") from exc
|
|
1174
|
-
if not isinstance(payload, dict):
|
|
1175
|
-
raise ValueError(f"Expected JSON object: {path}")
|
|
1176
|
-
return cast(dict[str, object], payload)
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
1131
|
# --- options --------------------------------------------------------------------------
|
|
1180
1132
|
|
|
1181
1133
|
|
|
@@ -1285,11 +1237,6 @@ def _check_box_source(
|
|
|
1285
1237
|
)
|
|
1286
1238
|
|
|
1287
1239
|
|
|
1288
|
-
def _is_integer(value: object) -> bool:
|
|
1289
|
-
"""Recognize integer inputs while excluding booleans."""
|
|
1290
|
-
return isinstance(value, int) and not isinstance(value, bool)
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
1240
|
# --- geometry -------------------------------------------------------------------------
|
|
1294
1241
|
|
|
1295
1242
|
|
|
@@ -1559,18 +1506,6 @@ def _pad_to_even(
|
|
|
1559
1506
|
return padded_image, padded
|
|
1560
1507
|
|
|
1561
1508
|
|
|
1562
|
-
def load_reference_nifti(
|
|
1563
|
-
path: Path, *, resampling: Literal["source", "affine"] = "source"
|
|
1564
|
-
) -> tuple[NiftiImage, NumericArray]:
|
|
1565
|
-
"""Load CT on an even-padded RAS 1 mm grid; default to pinned source resampling.
|
|
1566
|
-
|
|
1567
|
-
``resampling="affine"`` selects the world-coordinate sampling used by the
|
|
1568
|
-
conditioned runner. See ``_standardize_to_ras_1mm`` for the edge convention.
|
|
1569
|
-
"""
|
|
1570
|
-
image, data = _load_standardized_ct(path, resampling=resampling)
|
|
1571
|
-
return _pad_to_even(image, data, mode="edge")
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
1509
|
def _load_standardized_ct(
|
|
1575
1510
|
path: Path, *, resampling: Literal["source", "affine"] = "source"
|
|
1576
1511
|
) -> tuple[NiftiImage, NumericArray]:
|
|
@@ -1923,8 +1858,8 @@ def materialize_arrays(
|
|
|
1923
1858
|
) -> tuple[OutputValidation, dict[str, object] | None]:
|
|
1924
1859
|
"""Validate the generated arrays and write every output NIfTI file.
|
|
1925
1860
|
|
|
1926
|
-
All files, including ``organ_mask``, are first written
|
|
1927
|
-
beside their destinations and moved into place
|
|
1861
|
+
All files, including ``organ_mask``, are first written in a private temporary
|
|
1862
|
+
directory beside their destinations and moved into place after every write succeeds.
|
|
1928
1863
|
A failure before the final moves leaves no new output that would block a retry
|
|
1929
1864
|
without ``overwrite``; a failure or interruption during those moves can leave a subset.
|
|
1930
1865
|
|
|
@@ -2001,9 +1936,10 @@ def materialize_arrays(
|
|
|
2001
1936
|
(lesion, "target_mask", np.uint8),
|
|
2002
1937
|
(organ, "organ_mask", np.uint8),
|
|
2003
1938
|
]
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
1939
|
+
directory = outputs["synthetic_image"].parent
|
|
1940
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
1941
|
+
with TemporaryDirectory(prefix=".lesiondiffusion-", dir=directory) as staging:
|
|
1942
|
+
staged = {role: Path(staging) / outputs[role].name for _, role, _ in writes}
|
|
2007
1943
|
for data, role, dtype in writes:
|
|
2008
1944
|
_save_like_reference(
|
|
2009
1945
|
data=data,
|
|
@@ -2013,9 +1949,6 @@ def materialize_arrays(
|
|
|
2013
1949
|
)
|
|
2014
1950
|
for role, path in staged.items():
|
|
2015
1951
|
path.replace(outputs[role])
|
|
2016
|
-
finally:
|
|
2017
|
-
for path in staged.values():
|
|
2018
|
-
path.unlink(missing_ok=True)
|
|
2019
1952
|
validation: OutputValidation = {
|
|
2020
1953
|
"schema_version": 1,
|
|
2021
1954
|
"lesion_voxel_count": int(lesion.sum()),
|
|
@@ -2171,7 +2104,6 @@ def _json_safe(value: object) -> object:
|
|
|
2171
2104
|
__all__ = [
|
|
2172
2105
|
"MODEL",
|
|
2173
2106
|
"LesionDiffusionOptions",
|
|
2174
|
-
"load_conversion",
|
|
2175
2107
|
"load_stage",
|
|
2176
2108
|
"require_weights",
|
|
2177
2109
|
"run",
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/mlx_model.py
RENAMED
|
@@ -11,6 +11,7 @@ import math
|
|
|
11
11
|
import re
|
|
12
12
|
from collections.abc import Mapping
|
|
13
13
|
from dataclasses import dataclass
|
|
14
|
+
from itertools import pairwise
|
|
14
15
|
from typing import TYPE_CHECKING, cast
|
|
15
16
|
|
|
16
17
|
if TYPE_CHECKING:
|
|
@@ -70,6 +71,11 @@ LMNET_CONFIG = UnetConfig(16, 1, (4,))
|
|
|
70
71
|
# inference mode (context is enabled only in "conditioned" mode).
|
|
71
72
|
LINET_CONFIG = UnetConfig(128, 2, (4, 8), skip_context=True)
|
|
72
73
|
|
|
74
|
+
# Largest explicit-attention similarity tensor built at once. Source-mode LMNet's
|
|
75
|
+
# 23,104-token FP32 self-attention would otherwise hold several 4.3 GB tensors,
|
|
76
|
+
# which set the source-mode peak; LINet's 512 MiB FP16 similarity stays whole.
|
|
77
|
+
_SIMILARITY_CHUNK_BYTES = 1 << 30
|
|
78
|
+
|
|
73
79
|
# Convolutions applied only to a nearest 2x upsampling: the UNet decoder's
|
|
74
80
|
# ``Upsample.conv`` and the VQ decoder's ``upsample.conv``.
|
|
75
81
|
_UPSAMPLE_CONV = re.compile(r"(?:^output_blocks\.\d+\.\d+|\.upsample)\.conv$")
|
|
@@ -457,11 +463,37 @@ class LdmUnet(SourceLayers):
|
|
|
457
463
|
else:
|
|
458
464
|
# Source half attention rounds similarity and probability tensors;
|
|
459
465
|
# LINet retains those boundaries rather than using fused SDPA.
|
|
460
|
-
|
|
461
|
-
result = self.softmax(similarity) @ split(v)
|
|
466
|
+
result = self._explicit_attention(split(q), split(k), split(v), depth**-0.5)
|
|
462
467
|
result = mx.reshape(mx.transpose(result, (0, 2, 1, 3)), x.shape)
|
|
463
468
|
return self.dense(result, key + ".to_out.0")
|
|
464
469
|
|
|
470
|
+
def _explicit_attention(self, q: Array, k: Array, v: Array, scale: float) -> Array:
|
|
471
|
+
"""Return ``softmax(q @ k^T * scale) @ v`` for ``(B, heads, tokens, depth)`` inputs.
|
|
472
|
+
|
|
473
|
+
A similarity tensor above ``_SIMILARITY_CHUNK_BYTES`` is built in balanced
|
|
474
|
+
query-row chunks, each evaluated before the next, so this path must not be
|
|
475
|
+
traced by ``mx.compile`` at that size (the runner compiles only fused-attention
|
|
476
|
+
denoisers). Rows are independent in both products and the row softmax. For a
|
|
477
|
+
batched product (batch x heads > 1), MLX 0.32's GEMM never chooses split-K, and
|
|
478
|
+
chunks of two or more rows avoid its GEMV path, so each element keeps its
|
|
479
|
+
reduction order: the chunked output is bitwise identical to the whole product.
|
|
480
|
+
"""
|
|
481
|
+
mx = self.mx
|
|
482
|
+
k = mx.swapaxes(k, -1, -2)
|
|
483
|
+
batch, heads, queries = int(q.shape[0]), int(q.shape[1]), int(q.shape[2])
|
|
484
|
+
row_bytes = batch * heads * int(k.shape[-1]) * q.dtype.size
|
|
485
|
+
chunks = min(-(-queries * row_bytes // _SIMILARITY_CHUNK_BYTES), queries // 2)
|
|
486
|
+
if chunks <= 1 or batch * heads == 1:
|
|
487
|
+
return self.softmax((q @ k) * scale) @ v
|
|
488
|
+
# Balanced bounds give every chunk at least two rows.
|
|
489
|
+
bounds = [index * queries // chunks for index in range(chunks + 1)]
|
|
490
|
+
pieces: list[Array] = []
|
|
491
|
+
for start, stop in pairwise(bounds):
|
|
492
|
+
piece = self.softmax((q[:, :, start:stop] @ k) * scale) @ v
|
|
493
|
+
mx.eval(piece)
|
|
494
|
+
pieces.append(piece)
|
|
495
|
+
return mx.concatenate(pieces, axis=2)
|
|
496
|
+
|
|
465
497
|
def transformer(self, x: Array, context: Array | None, key: str) -> Array:
|
|
466
498
|
"""Apply self-attention, optional context attention and a feed-forward block.
|
|
467
499
|
|
|
@@ -552,8 +584,51 @@ class VqAutoencoder(SourceLayers):
|
|
|
552
584
|
Tensors are channels first. ``encode`` maps ``(B, C, D, H, W)`` to a latent of
|
|
553
585
|
half the spatial size (rounded down); ``decode`` snaps latent vectors to their
|
|
554
586
|
nearest codebook entry and returns twice the latent's spatial size.
|
|
587
|
+
|
|
588
|
+
Convolution, normalization and SiLU outputs are evaluated as they are built, so
|
|
589
|
+
the autoencoder must not be traced by ``mx.compile``. Full-resolution activations
|
|
590
|
+
are 96-channel volumes (629 MB in FP16 on a 160x160x128 grid). MLX keeps each op's
|
|
591
|
+
inputs alive until its command buffer completes and lets about ten buffers run
|
|
592
|
+
ahead, so an unsynchronized chain of such ops holds several times its live set:
|
|
593
|
+
this halves the encoder and decoder peaks. Evaluation order does not change the
|
|
594
|
+
arithmetic.
|
|
555
595
|
"""
|
|
556
596
|
|
|
597
|
+
def conv(self, x: Array, key: str, *, padding: int = 1, stride: int = 1) -> Array:
|
|
598
|
+
"""Apply ``SourceLayers.conv`` and evaluate the result."""
|
|
599
|
+
return self._evaluated(super().conv(x, key, padding=padding, stride=stride))
|
|
600
|
+
|
|
601
|
+
def norm(self, x: Array, key: str, *, groups: int, eps: float) -> Array:
|
|
602
|
+
"""Apply ``SourceLayers.norm`` and evaluate the result."""
|
|
603
|
+
return self._evaluated(super().norm(x, key, groups=groups, eps=eps))
|
|
604
|
+
|
|
605
|
+
def silu(self, x: Array) -> Array:
|
|
606
|
+
"""Apply ``SourceLayers.silu`` and evaluate the result."""
|
|
607
|
+
return self._evaluated(super().silu(x))
|
|
608
|
+
|
|
609
|
+
def norm_silu_conv(
|
|
610
|
+
self,
|
|
611
|
+
x: Array,
|
|
612
|
+
norm_key: str,
|
|
613
|
+
conv_key: str,
|
|
614
|
+
*,
|
|
615
|
+
groups: int,
|
|
616
|
+
eps: float,
|
|
617
|
+
shift: Array | None = None,
|
|
618
|
+
residual: Array | None = None,
|
|
619
|
+
) -> Array:
|
|
620
|
+
"""Apply ``SourceLayers.norm_silu_conv`` and evaluate the result."""
|
|
621
|
+
return self._evaluated(
|
|
622
|
+
super().norm_silu_conv(
|
|
623
|
+
x, norm_key, conv_key, groups=groups, eps=eps, shift=shift, residual=residual
|
|
624
|
+
)
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
def _evaluated(self, x: Array) -> Array:
|
|
628
|
+
"""Evaluate ``x`` so the queued GPU work releases its inputs."""
|
|
629
|
+
self.mx.eval(x)
|
|
630
|
+
return x
|
|
631
|
+
|
|
557
632
|
def residual(self, x: Array, key: str) -> Array:
|
|
558
633
|
"""Apply one VQ autoencoder residual block."""
|
|
559
634
|
h = self.norm_silu_conv(x, key + ".norm1", key + ".conv1", groups=16, eps=1e-6)
|
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
"""Native array and dependency contracts used by the source implementation."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
from typing import TYPE_CHECKING, Any, Protocol
|
|
6
|
-
|
|
7
|
-
from tokenizers import Encoding
|
|
8
|
-
|
|
9
|
-
from lesiondiffusion_mlx._arrays import HostArray as HostArray
|
|
10
|
-
|
|
11
|
-
if TYPE_CHECKING:
|
|
12
|
-
from collections.abc import Sequence
|
|
13
|
-
|
|
14
|
-
import mlx.core as mx
|
|
15
|
-
from medmlx_core.typing import FastRuntime as CoreFastRuntime
|
|
16
|
-
|
|
17
|
-
type Array = mx.array
|
|
18
|
-
type Dtype = mx.Dtype
|
|
19
|
-
type ArrayValue = bool | int | float | complex | list[ArrayValue] | tuple[ArrayValue, ...]
|
|
20
|
-
|
|
21
|
-
class ArrayConstructor(Protocol):
|
|
22
|
-
def __call__(
|
|
23
|
-
self,
|
|
24
|
-
value: HostArray | Array | ArrayValue,
|
|
25
|
-
/,
|
|
26
|
-
dtype: Dtype | None = None,
|
|
27
|
-
) -> Array:
|
|
28
|
-
"""Construct a native array from values and an optional dtype."""
|
|
29
|
-
...
|
|
30
|
-
|
|
31
|
-
class TokenizerContract(Protocol):
|
|
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
|
-
...
|
|
41
|
-
|
|
42
|
-
class MetalKernel(Protocol):
|
|
43
|
-
def __call__(
|
|
44
|
-
self,
|
|
45
|
-
*,
|
|
46
|
-
inputs: Sequence[Array],
|
|
47
|
-
template: Sequence[tuple[str, int | bool | Dtype]],
|
|
48
|
-
grid: tuple[int, int, int],
|
|
49
|
-
threadgroup: tuple[int, int, int],
|
|
50
|
-
output_shapes: Sequence[Sequence[int]],
|
|
51
|
-
output_dtypes: Sequence[Dtype],
|
|
52
|
-
) -> list[Array]:
|
|
53
|
-
"""Launch a Metal kernel and return its output arrays."""
|
|
54
|
-
...
|
|
55
|
-
|
|
56
|
-
class Fast(CoreFastRuntime, Protocol):
|
|
57
|
-
def scaled_dot_product_attention(
|
|
58
|
-
self,
|
|
59
|
-
q: Array,
|
|
60
|
-
k: Array,
|
|
61
|
-
v: Array,
|
|
62
|
-
*,
|
|
63
|
-
scale: float,
|
|
64
|
-
mask: str | Array | None = None,
|
|
65
|
-
sinks: Array | None = None,
|
|
66
|
-
force_fused: bool = False,
|
|
67
|
-
) -> Array:
|
|
68
|
-
"""Compute native scaled dot-product attention."""
|
|
69
|
-
...
|
|
70
|
-
|
|
71
|
-
def metal_kernel(
|
|
72
|
-
self,
|
|
73
|
-
name: str,
|
|
74
|
-
input_names: Sequence[str],
|
|
75
|
-
output_names: Sequence[str],
|
|
76
|
-
source: str,
|
|
77
|
-
header: str = "",
|
|
78
|
-
ensure_row_contiguous: bool = True,
|
|
79
|
-
atomic_outputs: bool = False,
|
|
80
|
-
compile_options: object | None = None,
|
|
81
|
-
) -> MetalKernel:
|
|
82
|
-
"""Compile a named native Metal kernel."""
|
|
83
|
-
...
|
|
84
|
-
|
|
85
|
-
class Random(Protocol):
|
|
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
|
|
94
|
-
else:
|
|
95
|
-
|
|
96
|
-
class ArrayConstructor(Protocol):
|
|
97
|
-
pass
|
|
98
|
-
|
|
99
|
-
class TokenizerContract(Protocol):
|
|
100
|
-
pass
|
|
101
|
-
|
|
102
|
-
class MetalKernel(Protocol):
|
|
103
|
-
pass
|
|
104
|
-
|
|
105
|
-
class Fast(Protocol):
|
|
106
|
-
pass
|
|
107
|
-
|
|
108
|
-
class Random(Protocol):
|
|
109
|
-
pass
|
|
110
|
-
|
|
111
|
-
Mlx = Any
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_arrays.py
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_attention.py
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_nax_conv.py
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_nifti.py
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_reference.py
RENAMED
|
File without changes
|
|
File without changes
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/_spatial.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/py.typed
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.6.post1 → lesiondiffusion_mlx-0.2.7}/src/lesiondiffusion_mlx/reference.json
RENAMED
|
File without changes
|