lesiondiffusion-mlx 0.2.4__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.
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/PKG-INFO +6 -4
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/README.md +2 -2
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/THIRD_PARTY_NOTICES.md +5 -3
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/pyproject.toml +7 -7
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/__init__.py +1 -1
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_typing.py +4 -71
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_model.py +5 -5
- lesiondiffusion_mlx-0.2.4/src/lesiondiffusion_mlx/_group_norm.py +0 -218
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/.gitignore +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/LICENSE +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_arrays.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_attention.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_nax_conv.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_nifti.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_reference.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_schedules.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_source_half.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_spatial.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/medmlx.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_pipeline.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_sampling.py +0 -0
- {lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/py.typed +0 -0
- {lesiondiffusion_mlx-0.2.4 → 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
|
+
Version: 0.2.5
|
|
4
4
|
Summary: Native MLX implementation of LesionDiffusion
|
|
5
|
-
Project-URL: Homepage, https://
|
|
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.
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
|
146
|
-
|
|
147
|
-
|
|
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.
|
|
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://
|
|
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"
|
|
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 = "
|
|
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 = [
|
|
@@ -2,18 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from typing import TYPE_CHECKING,
|
|
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
|
|
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
|
|
@@ -91,72 +90,7 @@ if TYPE_CHECKING:
|
|
|
91
90
|
"""Draw normally distributed native values."""
|
|
92
91
|
...
|
|
93
92
|
|
|
94
|
-
|
|
95
|
-
"""The MLX module surface consumed by this port, without importing it eagerly."""
|
|
96
|
-
|
|
97
|
-
@property
|
|
98
|
-
def fast(self) -> Fast:
|
|
99
|
-
"""Return the native fast operations boundary."""
|
|
100
|
-
...
|
|
101
|
-
|
|
102
|
-
random: Random
|
|
103
|
-
|
|
104
|
-
def addmm(self, c: Array, a: Array, b: Array, /) -> Array:
|
|
105
|
-
"""Multiply matrices and add the supplied bias."""
|
|
106
|
-
...
|
|
107
|
-
def all(self, a: Array, /) -> Array:
|
|
108
|
-
"""Reduce a native array with logical all."""
|
|
109
|
-
...
|
|
110
|
-
def argmin(self, a: Array, /, *, axis: int | None = None) -> Array:
|
|
111
|
-
"""Return indices of minimum values along an axis."""
|
|
112
|
-
...
|
|
113
|
-
def clear_cache(self) -> None:
|
|
114
|
-
"""Clear the native allocator cache."""
|
|
115
|
-
...
|
|
116
|
-
def compile[**P, R](self, fun: Callable[P, R], /) -> Callable[P, R]:
|
|
117
|
-
"""Compile a callable for native execution."""
|
|
118
|
-
...
|
|
119
|
-
def contiguous(self, a: Array, /) -> Array:
|
|
120
|
-
"""Return a contiguous native array."""
|
|
121
|
-
...
|
|
122
|
-
def cos(self, a: Array, /) -> Array:
|
|
123
|
-
"""Compute elementwise cosine."""
|
|
124
|
-
...
|
|
125
|
-
def device_info(self) -> dict[str, str | int]:
|
|
126
|
-
"""Return native device capability information."""
|
|
127
|
-
...
|
|
128
|
-
def erf(self, a: Array, /) -> Array:
|
|
129
|
-
"""Compute the elementwise error function."""
|
|
130
|
-
...
|
|
131
|
-
def exp(self, a: Array, /) -> Array:
|
|
132
|
-
"""Compute the elementwise exponential."""
|
|
133
|
-
...
|
|
134
|
-
def full(self, shape: Sequence[int], vals: object, *, dtype: Dtype) -> Array:
|
|
135
|
-
"""Create a native array filled with the supplied value."""
|
|
136
|
-
...
|
|
137
|
-
def isfinite(self, a: Array, /) -> Array:
|
|
138
|
-
"""Test native values for finiteness."""
|
|
139
|
-
...
|
|
140
|
-
def load(self, file: str, *, format: Literal["safetensors"]) -> dict[str, Array]:
|
|
141
|
-
"""Load named arrays from a safetensors file."""
|
|
142
|
-
...
|
|
143
|
-
def reciprocal(self, a: Array, /) -> Array:
|
|
144
|
-
"""Compute elementwise reciprocals."""
|
|
145
|
-
...
|
|
146
|
-
def sin(self, a: Array, /) -> Array:
|
|
147
|
-
"""Compute elementwise sine."""
|
|
148
|
-
...
|
|
149
|
-
def softmax(
|
|
150
|
-
self, a: Array, /, *, axis: int | None = None, precise: bool = False
|
|
151
|
-
) -> Array:
|
|
152
|
-
"""Normalize scores along the requested axis."""
|
|
153
|
-
...
|
|
154
|
-
def sqrt(self, a: Array | float, /) -> Array:
|
|
155
|
-
"""Compute elementwise square roots."""
|
|
156
|
-
...
|
|
157
|
-
def sum(self, a: Array, /, *, axis: int | None = None, keepdims: bool = False) -> Array:
|
|
158
|
-
"""Sum native values over an optional axis."""
|
|
159
|
-
...
|
|
93
|
+
Mlx = Any
|
|
160
94
|
else:
|
|
161
95
|
|
|
162
96
|
class ArrayConstructor(Protocol):
|
|
@@ -174,5 +108,4 @@ else:
|
|
|
174
108
|
class Random(Protocol):
|
|
175
109
|
pass
|
|
176
110
|
|
|
177
|
-
|
|
178
|
-
pass
|
|
111
|
+
Mlx = Any
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_model.py
RENAMED
|
@@ -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,
|
|
@@ -1,218 +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
|
-
"""Build or reuse the native group-normalization Metal kernels."""
|
|
102
|
-
return (
|
|
103
|
-
mx.fast.metal_kernel(
|
|
104
|
-
name="lesion_group_norm_partial",
|
|
105
|
-
input_names=["x"],
|
|
106
|
-
output_names=["partials"],
|
|
107
|
-
source=_PARTIAL,
|
|
108
|
-
),
|
|
109
|
-
mx.fast.metal_kernel(
|
|
110
|
-
name="lesion_group_norm_affine",
|
|
111
|
-
input_names=["x", "partials", "weight", "bias", "epsilon"],
|
|
112
|
-
output_names=["affine"],
|
|
113
|
-
source=_AFFINE,
|
|
114
|
-
),
|
|
115
|
-
mx.fast.metal_kernel(
|
|
116
|
-
name="lesion_group_norm_apply",
|
|
117
|
-
input_names=["x", "affine"],
|
|
118
|
-
output_names=["out"],
|
|
119
|
-
source=_APPLY,
|
|
120
|
-
),
|
|
121
|
-
)
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
def native_group_norm_eligible(x: Array, groups: int) -> bool:
|
|
125
|
-
"""Whether NCDHW ``x`` fits the vectorized kernels: rank 5, ``groups | C``, ``4 | DHW``."""
|
|
126
|
-
return (
|
|
127
|
-
x.ndim == 5
|
|
128
|
-
and int(x.shape[1]) % groups == 0
|
|
129
|
-
and math.prod(int(size) for size in x.shape[2:]) % 4 == 0
|
|
130
|
-
)
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
def group_norm_affine(
|
|
134
|
-
x: Array, weight: Array, bias: Array, *, groups: int, eps: float, mx: Mlx
|
|
135
|
-
) -> Array:
|
|
136
|
-
"""Fold NCDHW group statistics and the affine into per-channel FP32 pairs.
|
|
137
|
-
|
|
138
|
-
Args:
|
|
139
|
-
x: Contiguous ``(B, C, D, H, W)`` float16 or float32 input satisfying
|
|
140
|
-
``native_group_norm_eligible``.
|
|
141
|
-
weight: Per-channel scale ``(C,)``.
|
|
142
|
-
bias: Per-channel shift ``(C,)``.
|
|
143
|
-
groups: Number of groups dividing ``C``.
|
|
144
|
-
eps: Variance epsilon.
|
|
145
|
-
mx: The imported ``mlx.core`` module.
|
|
146
|
-
|
|
147
|
-
Returns:
|
|
148
|
-
FP32 ``(B * C * 2)`` array; entries ``2 i`` and ``2 i + 1`` are the
|
|
149
|
-
scale and offset that normalize channel ``i = b * C + c`` as
|
|
150
|
-
``x * scale + offset``.
|
|
151
|
-
"""
|
|
152
|
-
batch, channels = int(x.shape[0]), int(x.shape[1])
|
|
153
|
-
spatial = math.prod(int(size) for size in x.shape[2:])
|
|
154
|
-
size = channels // groups * spatial
|
|
155
|
-
chunks = -(-size // _CHUNK)
|
|
156
|
-
partial_kernel, affine_kernel, _ = _kernels(mx)
|
|
157
|
-
partials = partial_kernel(
|
|
158
|
-
inputs=[x],
|
|
159
|
-
template=[
|
|
160
|
-
("T", x.dtype),
|
|
161
|
-
("SIZE", size),
|
|
162
|
-
("CHUNK", _CHUNK),
|
|
163
|
-
("CHUNKS", chunks),
|
|
164
|
-
("TG", _THREADS),
|
|
165
|
-
],
|
|
166
|
-
grid=(_THREADS * chunks, batch * groups, 1),
|
|
167
|
-
threadgroup=(_THREADS, 1, 1),
|
|
168
|
-
output_shapes=[(batch * groups * chunks * 2,)],
|
|
169
|
-
output_dtypes=[mx.float32],
|
|
170
|
-
)[0]
|
|
171
|
-
epsilon = cast(ArrayConstructor, mx.array)([eps], dtype=mx.float32)
|
|
172
|
-
return affine_kernel(
|
|
173
|
-
inputs=[x, partials, weight, bias, epsilon],
|
|
174
|
-
template=[
|
|
175
|
-
("B", batch),
|
|
176
|
-
("G", groups),
|
|
177
|
-
("C", channels),
|
|
178
|
-
("SIZE", size),
|
|
179
|
-
("CHUNK", _CHUNK),
|
|
180
|
-
("CHUNKS", chunks),
|
|
181
|
-
],
|
|
182
|
-
grid=(batch * groups, 1, 1),
|
|
183
|
-
threadgroup=(min(32, batch * groups), 1, 1),
|
|
184
|
-
output_shapes=[(batch * channels * 2,)],
|
|
185
|
-
output_dtypes=[mx.float32],
|
|
186
|
-
)[0]
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
def native_group_norm(
|
|
190
|
-
x: Array, weight: Array, bias: Array, *, groups: int, eps: float, silu: bool, mx: Mlx
|
|
191
|
-
) -> Array:
|
|
192
|
-
"""Group-normalize NCDHW ``x`` with per-channel affine, then optionally SiLU.
|
|
193
|
-
|
|
194
|
-
Args:
|
|
195
|
-
x: ``(B, C, D, H, W)`` float16 or float32 input satisfying
|
|
196
|
-
``native_group_norm_eligible``.
|
|
197
|
-
weight: Per-channel scale ``(C,)``.
|
|
198
|
-
bias: Per-channel shift ``(C,)``.
|
|
199
|
-
groups: Number of groups dividing ``C``.
|
|
200
|
-
eps: Variance epsilon.
|
|
201
|
-
silu: Apply SiLU to the FP32 normalized value before rounding.
|
|
202
|
-
mx: The imported ``mlx.core`` module.
|
|
203
|
-
|
|
204
|
-
Returns:
|
|
205
|
-
Contiguous array with ``x``'s shape and dtype.
|
|
206
|
-
"""
|
|
207
|
-
# Every kernel reads x; one shared contiguous copy avoids three.
|
|
208
|
-
x = mx.contiguous(x)
|
|
209
|
-
affine = group_norm_affine(x, weight, bias, groups=groups, eps=eps, mx=mx)
|
|
210
|
-
spatial = math.prod(int(size) for size in x.shape[2:])
|
|
211
|
-
return _kernels(mx)[2](
|
|
212
|
-
inputs=[x, affine],
|
|
213
|
-
template=[("T", x.dtype), ("SPATIAL", spatial), ("SILU", silu)],
|
|
214
|
-
grid=(spatial // 4, int(x.shape[0]) * int(x.shape[1]), 1),
|
|
215
|
-
threadgroup=(_THREADS, 1, 1),
|
|
216
|
-
output_shapes=[tuple(x.shape)],
|
|
217
|
-
output_dtypes=[x.dtype],
|
|
218
|
-
)[0]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_attention.py
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_nax_conv.py
RENAMED
|
File without changes
|
|
File without changes
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_reference.py
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_schedules.py
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/_source_half.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_pipeline.py
RENAMED
|
File without changes
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/mlx_sampling.py
RENAMED
|
File without changes
|
|
File without changes
|
{lesiondiffusion_mlx-0.2.4 → lesiondiffusion_mlx-0.2.5}/src/lesiondiffusion_mlx/reference.json
RENAMED
|
File without changes
|