medmlx-core 0.1.2__py3-none-any.whl
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.
- medmlx_core/THIRD_PARTY_NOTICES.md +16 -0
- medmlx_core/__init__.py +118 -0
- medmlx_core/channel_last.py +82 -0
- medmlx_core/checkpoints.py +68 -0
- medmlx_core/conversion.py +31 -0
- medmlx_core/errors.py +87 -0
- medmlx_core/layout.py +70 -0
- medmlx_core/licenses/MONAI_LICENSE +201 -0
- medmlx_core/ops.py +281 -0
- medmlx_core/precision.py +327 -0
- medmlx_core/py.typed +0 -0
- medmlx_core/runtime.py +306 -0
- medmlx_core/sliding_window.py +258 -0
- medmlx_core/upsample.py +143 -0
- medmlx_core-0.1.2.dist-info/METADATA +176 -0
- medmlx_core-0.1.2.dist-info/RECORD +20 -0
- medmlx_core-0.1.2.dist-info/WHEEL +4 -0
- medmlx_core-0.1.2.dist-info/licenses/LICENSE +202 -0
- medmlx_core-0.1.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +16 -0
- medmlx_core-0.1.2.dist-info/licenses/licenses/MONAI_LICENSE +201 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
`src/medmlx_core/sliding_window.py` implements algorithms derived from MONAI
|
|
4
|
+
1.6.0 `monai/inferers/utils.py` and `monai/data/utils.py`.
|
|
5
|
+
|
|
6
|
+
Copyright (c) MONAI Consortium. Licensed under the Apache License, Version 2.0.
|
|
7
|
+
The original license is preserved in `licenses/MONAI_LICENSE`.
|
|
8
|
+
The NumPy/MLX implementation, restricted output/device API, and validation are
|
|
9
|
+
modifications made in this extraction and licensed under Apache-2.0;
|
|
10
|
+
the upstream MONAI portions retain their Apache license.
|
|
11
|
+
|
|
12
|
+
`src/medmlx_core/channel_last.py` retains layer arithmetic translated from
|
|
13
|
+
MONAI 1.4.0 for the source-pinned released network graphs. The new shared class
|
|
14
|
+
was extracted from RadNN's qualified working source; its model consumers are
|
|
15
|
+
SwinUNETR, FlexibleUNet and HoVer-Net. MONAI Consortium copyright and Apache-2.0
|
|
16
|
+
obligations apply; the full license remains in `licenses/MONAI_LICENSE`.
|
medmlx_core/__init__.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Shared MLX runtime for MedMLX model packages."""
|
|
2
|
+
|
|
3
|
+
from medmlx_core.checkpoints import (
|
|
4
|
+
load_torch_checkpoint,
|
|
5
|
+
mapping_from_pairs,
|
|
6
|
+
tensor_mapping_from_payload,
|
|
7
|
+
)
|
|
8
|
+
from medmlx_core.errors import (
|
|
9
|
+
AssetNotReadyError,
|
|
10
|
+
InvalidInputError,
|
|
11
|
+
MedmlxError,
|
|
12
|
+
MissingDependencyError,
|
|
13
|
+
ModelExecutionError,
|
|
14
|
+
)
|
|
15
|
+
from medmlx_core.layout import (
|
|
16
|
+
conv3d_weight_to_mlx,
|
|
17
|
+
conv_transpose3d_weight_to_mlx,
|
|
18
|
+
require_ncdhw,
|
|
19
|
+
to_ncdhw,
|
|
20
|
+
to_ndhwc,
|
|
21
|
+
tokens_from_ncdhw,
|
|
22
|
+
tokens_to_ncdhw,
|
|
23
|
+
)
|
|
24
|
+
from medmlx_core.ops import (
|
|
25
|
+
as_fp32,
|
|
26
|
+
avg_pool3d_ncdhw,
|
|
27
|
+
concat_channels_ncdhw,
|
|
28
|
+
conv3d_ncdhw,
|
|
29
|
+
conv_transpose3d_ncdhw,
|
|
30
|
+
group_norm_ncdhw,
|
|
31
|
+
linear,
|
|
32
|
+
pad_spatial_trailing_ncdhw,
|
|
33
|
+
silu,
|
|
34
|
+
split_conv3d_ncdhw,
|
|
35
|
+
split_conv_transpose3d_ncdhw,
|
|
36
|
+
upsample_nearest_ncdhw,
|
|
37
|
+
upsample_trilinear_ncdhw,
|
|
38
|
+
)
|
|
39
|
+
from medmlx_core.precision import Float32Operators
|
|
40
|
+
from medmlx_core.runtime import (
|
|
41
|
+
MLX_EXTRA,
|
|
42
|
+
MlxHostReport,
|
|
43
|
+
import_mlx,
|
|
44
|
+
mlx_default_device_name,
|
|
45
|
+
mlx_peak_memory_bytes,
|
|
46
|
+
probe_mlx_runtime,
|
|
47
|
+
require_mlx_device,
|
|
48
|
+
require_mlx_runtime,
|
|
49
|
+
reset_mlx_peak_memory,
|
|
50
|
+
)
|
|
51
|
+
from medmlx_core.upsample import deconv2x_ncdhw, upsample_add_ncdhw
|
|
52
|
+
|
|
53
|
+
__version__ = "0.1.2"
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
"MLX_EXTRA",
|
|
57
|
+
"AssetNotReadyError",
|
|
58
|
+
"Float32Operators",
|
|
59
|
+
"InvalidInputError",
|
|
60
|
+
"MedmlxError",
|
|
61
|
+
"MissingDependencyError",
|
|
62
|
+
"MlxHostReport",
|
|
63
|
+
"ModelExecutionError",
|
|
64
|
+
"as_fp32",
|
|
65
|
+
"avg_pool3d_ncdhw",
|
|
66
|
+
"compute_importance_map",
|
|
67
|
+
"concat_channels_ncdhw",
|
|
68
|
+
"conv3d_ncdhw",
|
|
69
|
+
"conv3d_weight_to_mlx",
|
|
70
|
+
"conv_transpose3d_ncdhw",
|
|
71
|
+
"conv_transpose3d_weight_to_mlx",
|
|
72
|
+
"deconv2x_ncdhw",
|
|
73
|
+
"dense_patch_slices",
|
|
74
|
+
"group_norm_ncdhw",
|
|
75
|
+
"import_mlx",
|
|
76
|
+
"linear",
|
|
77
|
+
"load_torch_checkpoint",
|
|
78
|
+
"mapping_from_pairs",
|
|
79
|
+
"mlx_default_device_name",
|
|
80
|
+
"mlx_peak_memory_bytes",
|
|
81
|
+
"pad_spatial_trailing_ncdhw",
|
|
82
|
+
"probe_mlx_runtime",
|
|
83
|
+
"require_mlx_device",
|
|
84
|
+
"require_mlx_runtime",
|
|
85
|
+
"require_ncdhw",
|
|
86
|
+
"reset_mlx_peak_memory",
|
|
87
|
+
"silu",
|
|
88
|
+
"sliding_window_inference",
|
|
89
|
+
"split_conv3d_ncdhw",
|
|
90
|
+
"split_conv_transpose3d_ncdhw",
|
|
91
|
+
"tensor_mapping_from_payload",
|
|
92
|
+
"to_ncdhw",
|
|
93
|
+
"to_ndhwc",
|
|
94
|
+
"tokens_from_ncdhw",
|
|
95
|
+
"tokens_to_ncdhw",
|
|
96
|
+
"upsample_add_ncdhw",
|
|
97
|
+
"upsample_nearest_ncdhw",
|
|
98
|
+
"upsample_trilinear_ncdhw",
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
# The sliding window imports MLX at module level, so load it on first use to
|
|
102
|
+
# keep `import medmlx_core` from importing MLX.
|
|
103
|
+
_LAZY = {
|
|
104
|
+
"compute_importance_map": "medmlx_core.sliding_window",
|
|
105
|
+
"dense_patch_slices": "medmlx_core.sliding_window",
|
|
106
|
+
"sliding_window_inference": "medmlx_core.sliding_window",
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def __getattr__(name: str) -> object:
|
|
111
|
+
module = _LAZY.get(name)
|
|
112
|
+
if module is None:
|
|
113
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
114
|
+
from importlib import import_module
|
|
115
|
+
|
|
116
|
+
value = getattr(import_module(module), name)
|
|
117
|
+
globals()[name] = value
|
|
118
|
+
return value
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Channel-last MLX layers shared by standalone medical imaging models."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from medmlx_core.upsample import deconv2x_ncdhw
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ChannelLastGraph:
|
|
10
|
+
def __init__(self, weights: Mapping[str, Any], *, mx: Any) -> None:
|
|
11
|
+
self.w = weights
|
|
12
|
+
self.mx = mx
|
|
13
|
+
|
|
14
|
+
def conv(self, x: Any, name: str, *, padding: int = 0, stride: int = 1, groups: int = 1) -> Any:
|
|
15
|
+
w = self.w[f"{name}.weight"]
|
|
16
|
+
axes = (0, *range(2, w.ndim), 1)
|
|
17
|
+
operation = self.mx.conv3d if w.ndim == 5 else self.mx.conv2d
|
|
18
|
+
y = operation(x, w.transpose(axes), stride=stride, padding=padding, groups=groups)
|
|
19
|
+
bias = self.w.get(f"{name}.bias")
|
|
20
|
+
return y if bias is None else y + bias
|
|
21
|
+
|
|
22
|
+
def linear(self, x: Any, name: str) -> Any:
|
|
23
|
+
y = x @ self.w[f"{name}.weight"].T
|
|
24
|
+
bias = self.w.get(f"{name}.bias")
|
|
25
|
+
return y if bias is None else y + bias
|
|
26
|
+
|
|
27
|
+
def layer_norm(self, x: Any, name: str | None = None) -> Any:
|
|
28
|
+
weight = None if name is None else self.w[f"{name}.weight"]
|
|
29
|
+
bias = None if name is None else self.w[f"{name}.bias"]
|
|
30
|
+
return self.mx.fast.layer_norm(x, weight, bias, 1e-5)
|
|
31
|
+
|
|
32
|
+
def batch_norm(self, x: Any, name: str, *, eps: float = 1e-5) -> Any:
|
|
33
|
+
scale = self.w[f"{name}.weight"] * self.mx.rsqrt(self.w[f"{name}.running_var"] + eps)
|
|
34
|
+
return (x - self.w[f"{name}.running_mean"]) * scale + self.w[f"{name}.bias"]
|
|
35
|
+
|
|
36
|
+
def relu(self, x: Any) -> Any:
|
|
37
|
+
return self.mx.maximum(x, 0)
|
|
38
|
+
|
|
39
|
+
def swish(self, x: Any) -> Any:
|
|
40
|
+
return x * self.mx.sigmoid(x)
|
|
41
|
+
|
|
42
|
+
def instance_norm(self, x: Any) -> Any:
|
|
43
|
+
axes = tuple(range(1, x.ndim - 1))
|
|
44
|
+
mean = self.mx.mean(x, axis=axes, keepdims=True)
|
|
45
|
+
return (x - mean) * self.mx.rsqrt(self.mx.var(x, axis=axes, keepdims=True) + 1e-5)
|
|
46
|
+
|
|
47
|
+
def residual3d(self, x: Any, name: str) -> Any:
|
|
48
|
+
def activate(y: Any) -> Any:
|
|
49
|
+
return self.mx.where(y >= 0, y, y * 0.01)
|
|
50
|
+
|
|
51
|
+
y = activate(self.instance_norm(self.conv(x, f"{name}.conv1.conv", padding=1)))
|
|
52
|
+
y = self.instance_norm(self.conv(y, f"{name}.conv2.conv", padding=1))
|
|
53
|
+
if f"{name}.conv3.conv.weight" in self.w:
|
|
54
|
+
x = self.instance_norm(self.conv(x, f"{name}.conv3.conv"))
|
|
55
|
+
return activate(y + x)
|
|
56
|
+
|
|
57
|
+
def deconv3d(self, x: Any, name: str) -> Any:
|
|
58
|
+
result = deconv2x_ncdhw(
|
|
59
|
+
x.transpose(0, 4, 1, 2, 3), self.w[f"{name}.weight"], None, mx=self.mx
|
|
60
|
+
)
|
|
61
|
+
return result.transpose(0, 2, 3, 4, 1)
|
|
62
|
+
|
|
63
|
+
def bilinear2x(self, x: Any) -> Any:
|
|
64
|
+
"""Source HoVer-Net uses align_corners=True at every 2x decoder stage."""
|
|
65
|
+
mx = self.mx
|
|
66
|
+
for axis in (1, 2):
|
|
67
|
+
size = x.shape[axis]
|
|
68
|
+
coordinate = mx.arange(size * 2, dtype=mx.float32) * ((size - 1) / (size * 2 - 1))
|
|
69
|
+
low = mx.floor(coordinate).astype(mx.int32)
|
|
70
|
+
high = mx.minimum(low + 1, size - 1)
|
|
71
|
+
fraction = coordinate - low.astype(mx.float32)
|
|
72
|
+
shape = [1] * x.ndim
|
|
73
|
+
shape[axis] = size * 2
|
|
74
|
+
fraction = fraction.reshape(shape)
|
|
75
|
+
x = mx.take(x, low, axis=axis) * (1 - fraction) + mx.take(x, high, axis=axis) * fraction
|
|
76
|
+
return x
|
|
77
|
+
|
|
78
|
+
def require_input(self, x: Any, shape: tuple[int, ...]) -> None:
|
|
79
|
+
if x.ndim != len(shape) + 1 or tuple(x.shape[1:]) != shape or x.shape[0] < 1:
|
|
80
|
+
raise ValueError(f"Expected Bx{'x'.join(map(str, shape))} input; got {x.shape}")
|
|
81
|
+
if x.dtype != self.mx.float32:
|
|
82
|
+
raise ValueError("MedMLX channel-last graphs require float32 inputs")
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Host checkpoint deserialization shared by native model converters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from typing import cast
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import NDArray
|
|
10
|
+
|
|
11
|
+
from medmlx_core.conversion import load_torch_checkpoint
|
|
12
|
+
from medmlx_core.errors import InvalidInputError
|
|
13
|
+
|
|
14
|
+
HostArray = NDArray[np.generic]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def mapping_from_pairs(
|
|
18
|
+
pairs: Sequence[tuple[str, HostArray]], *, what: str
|
|
19
|
+
) -> dict[str, HostArray]:
|
|
20
|
+
"""Build a tensor mapping or reject duplicate names."""
|
|
21
|
+
|
|
22
|
+
tensors: dict[str, HostArray] = {}
|
|
23
|
+
for name, array in pairs:
|
|
24
|
+
if name in tensors:
|
|
25
|
+
raise InvalidInputError(f"duplicate {what} parameter: {name}")
|
|
26
|
+
tensors[name] = array
|
|
27
|
+
return tensors
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def tensor_mapping_from_payload(payload: object, *, what: str) -> dict[str, HostArray]:
|
|
31
|
+
if not isinstance(payload, Mapping):
|
|
32
|
+
raise InvalidInputError(f"{what} checkpoint payload must be a mapping")
|
|
33
|
+
pairs: list[tuple[str, HostArray]] = []
|
|
34
|
+
mapping = cast(Mapping[object, object], payload)
|
|
35
|
+
for raw_name, value in mapping.items():
|
|
36
|
+
name = str(raw_name)
|
|
37
|
+
array = _maybe_array(value)
|
|
38
|
+
if array is None:
|
|
39
|
+
continue
|
|
40
|
+
pairs.append((name, array))
|
|
41
|
+
return mapping_from_pairs(pairs, what=what)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _maybe_array(value: object) -> HostArray | None:
|
|
45
|
+
if isinstance(value, np.ndarray):
|
|
46
|
+
return cast(HostArray, value)
|
|
47
|
+
if isinstance(value, (np.generic, int, float, bool, str)):
|
|
48
|
+
return None
|
|
49
|
+
detach = getattr(value, "detach", None)
|
|
50
|
+
tensor = detach() if callable(detach) else value
|
|
51
|
+
cpu = getattr(tensor, "cpu", None)
|
|
52
|
+
host = cpu() if callable(cpu) else tensor
|
|
53
|
+
numpy_fn = getattr(host, "numpy", None)
|
|
54
|
+
if not callable(numpy_fn):
|
|
55
|
+
return None
|
|
56
|
+
raw_array: object = numpy_fn()
|
|
57
|
+
if not isinstance(raw_array, np.ndarray):
|
|
58
|
+
raise InvalidInputError("tensor numpy() must return an ndarray")
|
|
59
|
+
return cast(HostArray, raw_array)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"HostArray",
|
|
64
|
+
"_maybe_array",
|
|
65
|
+
"load_torch_checkpoint",
|
|
66
|
+
"mapping_from_pairs",
|
|
67
|
+
"tensor_mapping_from_payload",
|
|
68
|
+
]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Optional Torch checkpoint deserialization; install the conversion extra."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import cast
|
|
7
|
+
|
|
8
|
+
from medmlx_core.errors import InvalidInputError, MissingDependencyError
|
|
9
|
+
|
|
10
|
+
type RawCheckpoint = dict[object, object]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_torch_checkpoint(path: Path, *, weights_only: bool = True) -> RawCheckpoint:
|
|
14
|
+
"""Deserialize source weights on the host; requires Torch, without model execution."""
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import torch
|
|
18
|
+
except ImportError as exc:
|
|
19
|
+
raise MissingDependencyError(
|
|
20
|
+
"Checkpoint conversion requires torch to unpickle the source files",
|
|
21
|
+
extra="conversion",
|
|
22
|
+
hint="Install medmlx-core[conversion] and rerun the converter.",
|
|
23
|
+
) from exc
|
|
24
|
+
payload: object = torch.load(path, map_location="cpu", weights_only=weights_only)
|
|
25
|
+
if not isinstance(payload, dict):
|
|
26
|
+
raise InvalidInputError(f"{path.name} is not a mapping checkpoint")
|
|
27
|
+
# Deserialization proves only a raw mapping; tensor_mapping_from_payload parses it.
|
|
28
|
+
return cast(RawCheckpoint, payload)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
__all__ = ["load_torch_checkpoint"]
|
medmlx_core/errors.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Shared MedMLX exceptions with builtin base classes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MedmlxError(Exception):
|
|
7
|
+
"""Base class for every error raised by the public MedMLX API."""
|
|
8
|
+
|
|
9
|
+
def __str__(self) -> str:
|
|
10
|
+
if not self.args:
|
|
11
|
+
return ""
|
|
12
|
+
if len(self.args) == 1:
|
|
13
|
+
return str(self.args[0])
|
|
14
|
+
return str(self.args)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MissingDependencyError(MedmlxError, ImportError):
|
|
18
|
+
"""Raised when an optional model dependency/extra is not installed.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
message: Human-readable description of the missing dependency.
|
|
22
|
+
extra: The pip extra that provides the dependency (e.g. ``"conversion"``),
|
|
23
|
+
or ``None`` when no single extra covers it.
|
|
24
|
+
hint: An actionable install/setup hint, e.g.
|
|
25
|
+
``"Install medmlx-core[conversion]"``.
|
|
26
|
+
|
|
27
|
+
Attributes:
|
|
28
|
+
extra (str | None): The pip extra carrying the dependency.
|
|
29
|
+
hint (str | None): Suggested install/setup command.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
message: str,
|
|
35
|
+
*,
|
|
36
|
+
extra: str | None = None,
|
|
37
|
+
hint: str | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.extra = extra
|
|
41
|
+
self.hint = hint
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ModelExecutionError(MedmlxError, RuntimeError):
|
|
45
|
+
"""Raised when a model runner fails during execution.
|
|
46
|
+
|
|
47
|
+
This signals a model/runtime failure, not a caller input error.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class InvalidInputError(MedmlxError, ValueError):
|
|
52
|
+
"""Raised when caller-supplied inputs are missing, malformed, or an unsupported combination."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class AssetNotReadyError(MedmlxError, FileNotFoundError):
|
|
56
|
+
"""Raised when a model's local assets or checkpoints are missing or mismatched.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
message: Human-readable description of the missing or incompatible asset.
|
|
60
|
+
reason: Short machine-friendly reason, e.g.
|
|
61
|
+
``"missing weights/model.safetensors"``.
|
|
62
|
+
hint: An actionable setup hint, e.g. a model checkpoint conversion command.
|
|
63
|
+
|
|
64
|
+
Attributes:
|
|
65
|
+
reason (str | None): Why the asset is not ready.
|
|
66
|
+
hint (str | None): Suggested conversion or setup command.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
message: str,
|
|
72
|
+
*,
|
|
73
|
+
reason: str | None = None,
|
|
74
|
+
hint: str | None = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
super().__init__(message)
|
|
77
|
+
self.reason = reason
|
|
78
|
+
self.hint = hint
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
__all__ = [
|
|
82
|
+
"AssetNotReadyError",
|
|
83
|
+
"InvalidInputError",
|
|
84
|
+
"MedmlxError",
|
|
85
|
+
"MissingDependencyError",
|
|
86
|
+
"ModelExecutionError",
|
|
87
|
+
]
|
medmlx_core/layout.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""NCDHW module layout and NDHWC remaps for MLX 3D conv/norm."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
LAYOUT_NCDHW = "maisi.layout.ncdhw"
|
|
8
|
+
LAYOUT_TO_NDHWC = "maisi.layout.to_ndhwc"
|
|
9
|
+
LAYOUT_TO_NCDHW = "maisi.layout.to_ncdhw"
|
|
10
|
+
LAYOUT_CONV3D_W = "maisi.layout.conv3d_w"
|
|
11
|
+
LAYOUT_CONV_TRANSPOSE3D_W = "maisi.layout.conv_transpose3d_w"
|
|
12
|
+
LAYOUT_LINEAR_W = "maisi.layout.linear_w"
|
|
13
|
+
LAYOUT_EMBED_W = "maisi.layout.embed_w"
|
|
14
|
+
LAYOUT_GN_AFFINE = "maisi.layout.gn_affine"
|
|
15
|
+
LAYOUT_VECTOR = "maisi.layout.vector"
|
|
16
|
+
IDENTITY_WEIGHT_LAYOUTS = frozenset(
|
|
17
|
+
{LAYOUT_LINEAR_W, LAYOUT_EMBED_W, LAYOUT_GN_AFFINE, LAYOUT_VECTOR}
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def require_ncdhw(array: Any, *, name: str) -> None:
|
|
22
|
+
"""Raise if *array* is not a rank-5 NCDHW tensor."""
|
|
23
|
+
|
|
24
|
+
if int(array.ndim) != 5:
|
|
25
|
+
raise ValueError(f"{name} must be NCDHW rank-5; got ndim={array.ndim}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def to_ndhwc(array: Any, mx: Any) -> Any:
|
|
29
|
+
"""NCDHW → NDHWC at a conv/norm call."""
|
|
30
|
+
|
|
31
|
+
return mx.transpose(array, (0, 2, 3, 4, 1))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def to_ncdhw(array: Any, mx: Any) -> Any:
|
|
35
|
+
"""NDHWC → NCDHW after a conv/norm call."""
|
|
36
|
+
|
|
37
|
+
return mx.transpose(array, (0, 4, 1, 2, 3))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def conv3d_weight_to_mlx(weight: Any, mx: Any) -> Any:
|
|
41
|
+
"""Torch conv3d weight [O, I, KD, KH, KW] → MLX [O, KD, KH, KW, I]."""
|
|
42
|
+
|
|
43
|
+
if int(weight.ndim) != 5:
|
|
44
|
+
raise ValueError(f"conv3d weight must be rank-5 [O,I,K]; got ndim={weight.ndim}")
|
|
45
|
+
return mx.transpose(weight, (0, 2, 3, 4, 1))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def conv_transpose3d_weight_to_mlx(weight: Any, mx: Any) -> Any:
|
|
49
|
+
"""Torch conv_transpose3d weight [I, O, KD, KH, KW] → MLX [O, KD, KH, KW, I]."""
|
|
50
|
+
|
|
51
|
+
if int(weight.ndim) != 5:
|
|
52
|
+
raise ValueError(f"conv_transpose3d weight must be rank-5 [I,O,K]; got ndim={weight.ndim}")
|
|
53
|
+
return mx.transpose(weight, (1, 2, 3, 4, 0))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def tokens_from_ncdhw(array: Any, mx: Any) -> Any:
|
|
57
|
+
"""NCDHW [B,C,D,H,W] → tokens [B, D*H*W, C]."""
|
|
58
|
+
|
|
59
|
+
require_ncdhw(array, name="attention input")
|
|
60
|
+
batch, channels, depth, height, width = (int(dim) for dim in array.shape)
|
|
61
|
+
flat = mx.reshape(array, (batch, channels, depth * height * width))
|
|
62
|
+
return mx.transpose(flat, (0, 2, 1))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def tokens_to_ncdhw(tokens: Any, spatial: tuple[int, int, int, int, int], mx: Any) -> Any:
|
|
66
|
+
"""Tokens [B, N, C] → NCDHW *spatial*."""
|
|
67
|
+
|
|
68
|
+
batch, channels, depth, height, width = spatial
|
|
69
|
+
ncdhw = mx.transpose(tokens, (0, 2, 1))
|
|
70
|
+
return mx.reshape(ncdhw, (batch, channels, depth, height, width))
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|