brainchop 0.2.2__tar.gz → 0.2.4__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.
- {brainchop-0.2.2/brainchop.egg-info → brainchop-0.2.4}/PKG-INFO +10 -1
- {brainchop-0.2.2 → brainchop-0.2.4}/README.md +9 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/api.py +70 -16
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/cli.py +10 -4
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/niimath/__init__.py +78 -23
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/sae_model.py +32 -5
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/tiny_meshnet.py +70 -19
- {brainchop-0.2.2 → brainchop-0.2.4/brainchop.egg-info}/PKG-INFO +10 -1
- {brainchop-0.2.2 → brainchop-0.2.4}/pyproject.toml +1 -1
- {brainchop-0.2.2 → brainchop-0.2.4}/tests/test_api.py +17 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/LICENSE +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/MANIFEST.in +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/__init__.py +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/convert_tfjs_to_pth.py +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/export_model.py +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop/utils.py +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop.egg-info/SOURCES.txt +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop.egg-info/dependency_links.txt +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop.egg-info/entry_points.txt +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop.egg-info/requires.txt +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/brainchop.egg-info/top_level.txt +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/setup.cfg +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/tests/test_backend_comparison.py +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/tests/test_batching.py +0 -0
- {brainchop-0.2.2 → brainchop-0.2.4}/tests/test_sequential_argmax.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: brainchop
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.4
|
|
4
4
|
Summary: Portable and lightweight brain segmentation using tinygrad
|
|
5
5
|
Author-email: Mike Doan <spikedoanz@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -31,6 +31,15 @@ BrainChop is a lightweight tool for brain segmentation that runs on pretty much
|
|
|
31
31
|
|
|
32
32
|
---
|
|
33
33
|
|
|
34
|
+
## (NEW) No install single command use
|
|
35
|
+
|
|
36
|
+
Using [uv](https://docs.astral.sh/uv/), brainchop can be ran without needing an enviroment
|
|
37
|
+
```
|
|
38
|
+
uvx brainchop --help
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
|
|
34
43
|
## Installation
|
|
35
44
|
|
|
36
45
|
```bash
|
|
@@ -4,6 +4,15 @@ BrainChop is a lightweight tool for brain segmentation that runs on pretty much
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## (NEW) No install single command use
|
|
8
|
+
|
|
9
|
+
Using [uv](https://docs.astral.sh/uv/), brainchop can be ran without needing an enviroment
|
|
10
|
+
```
|
|
11
|
+
uvx brainchop --help
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
|
|
7
16
|
## Installation
|
|
8
17
|
|
|
9
18
|
```bash
|
|
@@ -22,6 +22,8 @@ from brainchop.niimath import (
|
|
|
22
22
|
conform,
|
|
23
23
|
bwlabel,
|
|
24
24
|
truncate_header_bytes,
|
|
25
|
+
set_header_intent_label,
|
|
26
|
+
_run_niimath,
|
|
25
27
|
)
|
|
26
28
|
from brainchop.tiny_meshnet import load_meshnet, chunked_conv
|
|
27
29
|
from brainchop.sae_model import load_sae
|
|
@@ -83,6 +85,17 @@ def _is_first_run(model_name: str, batch_size: int) -> bool:
|
|
|
83
85
|
return not any(e["BS"] == batch_size for e in cache_data["beams"])
|
|
84
86
|
|
|
85
87
|
|
|
88
|
+
def _save_fuse_chunk(model_name: str, chunk_size: int) -> None:
|
|
89
|
+
"""Save FUSE_CHUNK to model cache."""
|
|
90
|
+
cache_dir = _get_cache_dir(model_name)
|
|
91
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
cache_file = cache_dir / "optimizations.json"
|
|
93
|
+
cache_data = _load_optimization_cache(model_name)
|
|
94
|
+
cache_data["fuse_chunk"] = chunk_size
|
|
95
|
+
with open(cache_file, "w") as f:
|
|
96
|
+
json.dump(cache_data, f, indent=2)
|
|
97
|
+
|
|
98
|
+
|
|
86
99
|
@dataclass
|
|
87
100
|
class Volume:
|
|
88
101
|
"""
|
|
@@ -119,18 +132,33 @@ def list_models() -> dict[str, str]:
|
|
|
119
132
|
return {name: details["description"] for name, details in AVAILABLE_MODELS.items()}
|
|
120
133
|
|
|
121
134
|
|
|
122
|
-
def
|
|
135
|
+
def _load_single(path: str | Path, *, crop: float | None = None, ct: bool = False, comply: bool = False) -> Volume:
|
|
136
|
+
from brainchop.utils import crop_to_cutoff
|
|
137
|
+
|
|
138
|
+
data, header = conform(os.path.abspath(path), ct=ct, comply=comply)
|
|
139
|
+
if crop is not None:
|
|
140
|
+
data, _ = crop_to_cutoff(data, crop)
|
|
141
|
+
return Volume(Tensor(data.copy()), header)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def load(
|
|
145
|
+
path: str | Path | list[str | Path],
|
|
146
|
+
*,
|
|
147
|
+
crop: float | None = None,
|
|
148
|
+
ct: bool = False,
|
|
149
|
+
comply: bool = False,
|
|
150
|
+
) -> Volume | list[Volume]:
|
|
123
151
|
"""
|
|
124
|
-
Load NIfTI file and conform to 256x256x256.
|
|
152
|
+
Load NIfTI file(s) and conform to 256x256x256.
|
|
125
153
|
|
|
126
154
|
Args:
|
|
127
|
-
path: Path to NIfTI file (.nii or .nii.gz)
|
|
155
|
+
path: Path or list of paths to NIfTI file(s) (.nii or .nii.gz)
|
|
128
156
|
crop: Crop intensity percentile (e.g., 0.01 removes bottom 1%)
|
|
129
157
|
ct: Use CT windowing instead of MRI normalization
|
|
130
158
|
comply: Insert niimath compliance arguments before conform
|
|
131
159
|
|
|
132
160
|
Returns:
|
|
133
|
-
Volume
|
|
161
|
+
Single Volume if path is a single path, list[Volume] if path is a list
|
|
134
162
|
|
|
135
163
|
Example:
|
|
136
164
|
```python
|
|
@@ -138,15 +166,16 @@ def load(path: str, *, crop: float | None = None, ct: bool = False, comply: bool
|
|
|
138
166
|
>>> vol.data.shape
|
|
139
167
|
(256, 256, 256)
|
|
140
168
|
|
|
169
|
+
>>> vols = load(["brain1.nii.gz", "brain2.nii.gz"])
|
|
170
|
+
>>> len(vols)
|
|
171
|
+
2
|
|
172
|
+
|
|
141
173
|
>>> vol = load("brain.nii.gz", crop=0.01) # crop dark voxels
|
|
142
174
|
```
|
|
143
175
|
"""
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
if crop is not None:
|
|
148
|
-
data, _ = crop_to_cutoff(data, crop)
|
|
149
|
-
return Volume(Tensor(data.copy()), header)
|
|
176
|
+
if isinstance(path, list):
|
|
177
|
+
return [_load_single(p, crop=crop, ct=ct, comply=comply) for p in path]
|
|
178
|
+
return _load_single(path, crop=crop, ct=ct, comply=comply)
|
|
150
179
|
|
|
151
180
|
|
|
152
181
|
def save(volume: Volume, path: str) -> None:
|
|
@@ -164,13 +193,14 @@ def save(volume: Volume, path: str) -> None:
|
|
|
164
193
|
>>> save(result, "segmented.nii.gz")
|
|
165
194
|
```
|
|
166
195
|
"""
|
|
167
|
-
|
|
196
|
+
# Segmentation output is a categorical label map: tag the NIfTI header with
|
|
197
|
+
# NIFTI_INTENT_LABEL (1002) so downstream viewers treat it as labels.
|
|
198
|
+
header = set_header_intent_label(truncate_header_bytes(volume.header))
|
|
168
199
|
gz = "1" if path.endswith(".gz") else "0"
|
|
169
200
|
data = volume.data.cast("uint8").numpy().tobytes()
|
|
170
|
-
|
|
201
|
+
_run_niimath(
|
|
171
202
|
["niimath", "-", "-gz", gz, path, "-odt", "char"],
|
|
172
203
|
input=header + data,
|
|
173
|
-
check=True,
|
|
174
204
|
)
|
|
175
205
|
|
|
176
206
|
|
|
@@ -283,9 +313,9 @@ class TTAModel:
|
|
|
283
313
|
logits_flipped = self._forward_no_argmax(x_flipped)
|
|
284
314
|
logits_unflipped = self._flip(logits_flipped)
|
|
285
315
|
|
|
286
|
-
# Sum logits and argmax
|
|
316
|
+
# Sum logits and argmax (logits already computed, use non-fused path)
|
|
287
317
|
summed = logits_orig + logits_unflipped
|
|
288
|
-
return self._model.seq_conv_argmax(summed)
|
|
318
|
+
return self._model.seq_conv_argmax.argmax_only(summed)
|
|
289
319
|
|
|
290
320
|
|
|
291
321
|
def _load_model(model: str, *, tta: bool = False, flip_axis: str = "sagittal"):
|
|
@@ -384,6 +414,30 @@ def optimize(model: str, *, beam: int = 2, batch_size: int = 1) -> None:
|
|
|
384
414
|
del os.environ["BEAM"]
|
|
385
415
|
|
|
386
416
|
|
|
417
|
+
def _run_with_fuse_chunk(m, batched, model_name: str, tta: bool = False):
|
|
418
|
+
"""Run model, auto-probing FUSE_CHUNK on MemoryError. Priority: envvar > cache > auto."""
|
|
419
|
+
if tta:
|
|
420
|
+
return m(batched)
|
|
421
|
+
|
|
422
|
+
n_classes = m.n_classes
|
|
423
|
+
env_val = os.environ.get("FUSE_CHUNK")
|
|
424
|
+
chunk = int(env_val) if env_val is not None else \
|
|
425
|
+
_load_optimization_cache(model_name).get("fuse_chunk") or n_classes
|
|
426
|
+
|
|
427
|
+
while chunk >= 1:
|
|
428
|
+
try:
|
|
429
|
+
result = m(batched, fuse_chunk=chunk)
|
|
430
|
+
if chunk < n_classes and env_val is None:
|
|
431
|
+
print(f"brainchop :: FUSE_CHUNK={chunk} (auto-detected for '{model_name}', set FUSE_CHUNK to override)")
|
|
432
|
+
_save_fuse_chunk(model_name, chunk)
|
|
433
|
+
return result
|
|
434
|
+
except MemoryError:
|
|
435
|
+
if chunk == 1:
|
|
436
|
+
raise
|
|
437
|
+
chunk = max(1, chunk // 2)
|
|
438
|
+
print(f"brainchop :: OOM at FUSE_CHUNK={chunk * 2}, retrying with FUSE_CHUNK={chunk}...")
|
|
439
|
+
|
|
440
|
+
|
|
387
441
|
def segment(
|
|
388
442
|
volume: Volume | list[Volume],
|
|
389
443
|
model: str,
|
|
@@ -459,7 +513,7 @@ def segment(
|
|
|
459
513
|
if hasattr(m, "normalize"):
|
|
460
514
|
batched = m.normalize(batched)
|
|
461
515
|
|
|
462
|
-
raw_output = m
|
|
516
|
+
raw_output = _run_with_fuse_chunk(m, batched, model_name, tta=tta)
|
|
463
517
|
# TTAModel returns raw logits (B, C, D, H, W), MeshNet returns argmaxed (B, D, H, W)
|
|
464
518
|
if len(raw_output.shape) == 5:
|
|
465
519
|
output = raw_output.argmax(axis=1) # (B, C, D, H, W) -> (B, D, H, W)
|
|
@@ -11,7 +11,12 @@ from brainchop.api import (
|
|
|
11
11
|
Volume, load, save, segment, list_models, optimize, export_classes,
|
|
12
12
|
_is_first_run, _get_best_beam,
|
|
13
13
|
)
|
|
14
|
-
from brainchop.niimath import
|
|
14
|
+
from brainchop.niimath import (
|
|
15
|
+
grow_border,
|
|
16
|
+
truncate_header_bytes,
|
|
17
|
+
set_header_intent_label,
|
|
18
|
+
_run_niimath,
|
|
19
|
+
)
|
|
15
20
|
|
|
16
21
|
|
|
17
22
|
def get_parser() -> argparse.ArgumentParser:
|
|
@@ -205,11 +210,12 @@ def _save_mindgrab(result: Volume, source_path: str, args, output_path: str):
|
|
|
205
210
|
|
|
206
211
|
def _save_inverse_conform(result: Volume, source_path: str, output_path: str):
|
|
207
212
|
"""Save with inverse conform."""
|
|
208
|
-
header
|
|
213
|
+
# Categorical label output -> tag header with NIFTI_INTENT_LABEL (1002).
|
|
214
|
+
header = set_header_intent_label(truncate_header_bytes(result.header))
|
|
209
215
|
gz = "0" if output_path.endswith(".nii") else "1"
|
|
210
|
-
|
|
216
|
+
_run_niimath(
|
|
211
217
|
["niimath", "-", "-reslice_nn", source_path, "-gz", gz, output_path, "-odt", "char"],
|
|
212
|
-
input=header + result.data.cast("uint8").numpy().tobytes(),
|
|
218
|
+
input=header + result.data.cast("uint8").numpy().tobytes(),
|
|
213
219
|
)
|
|
214
220
|
|
|
215
221
|
|
|
@@ -10,6 +10,25 @@ from tinygrad import Tensor
|
|
|
10
10
|
from typing import Tuple
|
|
11
11
|
|
|
12
12
|
|
|
13
|
+
def _run_niimath(cmd, *, input: bytes | None = None) -> subprocess.CompletedProcess:
|
|
14
|
+
"""Run a niimath command, surfacing its stderr on failure.
|
|
15
|
+
|
|
16
|
+
niimath aborts (e.g. SIGABRT / exit 134) on some inputs -- extended headers
|
|
17
|
+
with operation history, unusual datatypes, 4D volumes. ``capture_output``
|
|
18
|
+
otherwise swallows the reason and leaves only an opaque CalledProcessError,
|
|
19
|
+
so on a non-zero exit we decode and re-raise niimath's own stderr.
|
|
20
|
+
"""
|
|
21
|
+
try:
|
|
22
|
+
return subprocess.run(cmd, input=input, capture_output=True, check=True)
|
|
23
|
+
except subprocess.CalledProcessError as e:
|
|
24
|
+
stderr = (e.stderr or b"").decode("utf-8", "replace").strip()
|
|
25
|
+
msg = f"niimath failed (exit {e.returncode}): {' '.join(map(str, cmd))}"
|
|
26
|
+
if stderr:
|
|
27
|
+
msg += f"\n{stderr}"
|
|
28
|
+
print(msg, file=sys.stderr)
|
|
29
|
+
raise RuntimeError(msg) from e
|
|
30
|
+
|
|
31
|
+
|
|
13
32
|
def _get_executable():
|
|
14
33
|
"""
|
|
15
34
|
Locate the niimath binary, either via NIIMATH_PATH or on your PATH.
|
|
@@ -127,21 +146,23 @@ def _read_nifti(filename):
|
|
|
127
146
|
|
|
128
147
|
INITIAL_HEADER_READ_SIZE = 352
|
|
129
148
|
|
|
130
|
-
# NIfTI datatype codes
|
|
149
|
+
# NIfTI-1 datatype codes -> numpy dtypes (see nifti1.h). NOTE: the previous
|
|
150
|
+
# table was shifted (e.g. 16 mapped to complex64 instead of float32) and
|
|
151
|
+
# referenced np.float128, which does not exist on Apple Silicon. Both are
|
|
152
|
+
# fixed here.
|
|
131
153
|
nifti_dtypes = {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
1792: np.complex128, # DT_COMPLEX128 (NIfTI-1 extension)
|
|
154
|
+
2: np.uint8, # DT_UINT8
|
|
155
|
+
4: np.int16, # DT_INT16
|
|
156
|
+
8: np.int32, # DT_INT32
|
|
157
|
+
16: np.float32, # DT_FLOAT32
|
|
158
|
+
32: np.complex64, # DT_COMPLEX64
|
|
159
|
+
64: np.float64, # DT_FLOAT64
|
|
160
|
+
256: np.int8, # DT_INT8
|
|
161
|
+
512: np.uint16, # DT_UINT16
|
|
162
|
+
768: np.uint32, # DT_UINT32
|
|
163
|
+
1024: np.int64, # DT_INT64
|
|
164
|
+
1280: np.uint64, # DT_UINT64
|
|
165
|
+
1792: np.complex128, # DT_COMPLEX128
|
|
145
166
|
}
|
|
146
167
|
|
|
147
168
|
file_size = os.path.getsize(filename)
|
|
@@ -244,6 +265,28 @@ def _read_nifti(filename):
|
|
|
244
265
|
return data.reshape(reshaped_dims), header_bytes
|
|
245
266
|
|
|
246
267
|
|
|
268
|
+
def _read_nifti_any(path):
|
|
269
|
+
"""Like _read_nifti but transparently handles gzip-compressed (.nii.gz) files.
|
|
270
|
+
|
|
271
|
+
_read_nifti seeks by byte offset on the raw file, so a gzip stream must be
|
|
272
|
+
decompressed to a plain NIfTI first.
|
|
273
|
+
"""
|
|
274
|
+
with open(path, "rb") as f:
|
|
275
|
+
magic = f.read(2)
|
|
276
|
+
if magic == b"\x1f\x8b": # gzip
|
|
277
|
+
import tempfile
|
|
278
|
+
with gzip.open(path, "rb") as gf:
|
|
279
|
+
raw = gf.read()
|
|
280
|
+
tmp = tempfile.NamedTemporaryFile(suffix=".nii", delete=False)
|
|
281
|
+
try:
|
|
282
|
+
tmp.write(raw)
|
|
283
|
+
tmp.close()
|
|
284
|
+
return _read_nifti(tmp.name)
|
|
285
|
+
finally:
|
|
286
|
+
os.unlink(tmp.name)
|
|
287
|
+
return _read_nifti(path)
|
|
288
|
+
|
|
289
|
+
|
|
247
290
|
def _write_nifti(path, data, header):
|
|
248
291
|
# write header + raw voxel data
|
|
249
292
|
with open(path, "wb") as f:
|
|
@@ -262,16 +305,28 @@ def conform(input_image_path, comply=False, ct=False):
|
|
|
262
305
|
|
|
263
306
|
comply_args = ["-comply", "256", "256", "256", "1", "1", "1", "1", "1"]
|
|
264
307
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
308
|
+
def _conform_args(read_from):
|
|
309
|
+
cmd = ["niimath", read_from]
|
|
310
|
+
if ct:
|
|
311
|
+
cmd += ["-h2c"]
|
|
312
|
+
if comply:
|
|
313
|
+
cmd += comply_args
|
|
314
|
+
cmd += ["-conform", "-gz", "0", "-", "-odt", "char"]
|
|
315
|
+
return cmd
|
|
271
316
|
|
|
272
|
-
#
|
|
273
|
-
|
|
274
|
-
|
|
317
|
+
# Fast path: let niimath read the file directly.
|
|
318
|
+
try:
|
|
319
|
+
out = _run_niimath(_conform_args(str(inp))).stdout
|
|
320
|
+
except RuntimeError:
|
|
321
|
+
# niimath could not read the file. This happens with NIfTI files that
|
|
322
|
+
# carry a header extension (e.g. AFNI/FSL operation history): vox_offset
|
|
323
|
+
# points past the extension and niimath's reader miscounts the image
|
|
324
|
+
# buffer ("data bytes needed > data bytes input"). Re-read the volume in
|
|
325
|
+
# Python honoring vox_offset, then hand niimath a clean, extension-free
|
|
326
|
+
# volume (vox_offset=352) via stdin.
|
|
327
|
+
vol_data, clean_header = _read_nifti_any(str(inp))
|
|
328
|
+
piped = clean_header + np.ascontiguousarray(vol_data).tobytes()
|
|
329
|
+
out = _run_niimath(_conform_args("-"), input=piped).stdout
|
|
275
330
|
|
|
276
331
|
# split off header and data
|
|
277
332
|
header, data = header_data_split(out)
|
|
@@ -105,7 +105,16 @@ class SAENet:
|
|
|
105
105
|
|
|
106
106
|
self.layers.append((layer_type, idx, weight, bias))
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
# Build a dummy nn.Conv2d to hold the final layer's weights for fused argmax
|
|
109
|
+
_, idx, weight, bias = self.layers[-1]
|
|
110
|
+
kernel_size = weight.shape[2]
|
|
111
|
+
padding = (kernel_size - 1) // 2
|
|
112
|
+
from tinygrad import nn as tg_nn
|
|
113
|
+
final_conv = tg_nn.Conv2d(weight.shape[1], weight.shape[0],
|
|
114
|
+
kernel_size=[kernel_size]*3, padding=padding)
|
|
115
|
+
final_conv.weight = weight
|
|
116
|
+
final_conv.bias = bias
|
|
117
|
+
self.seq_conv_argmax = SequentialConvArgmax(self.n_classes, final_conv)
|
|
109
118
|
|
|
110
119
|
def normalize(self, x: Tensor) -> Tensor:
|
|
111
120
|
"""Quantile normalization (same as MeshNet)."""
|
|
@@ -146,19 +155,37 @@ class SAENet:
|
|
|
146
155
|
|
|
147
156
|
return x
|
|
148
157
|
|
|
149
|
-
def
|
|
158
|
+
def forward_no_final(self, x: Tensor) -> Tensor:
|
|
159
|
+
"""Forward pass through all layers except the final conv."""
|
|
160
|
+
for layer_type, idx, weight, bias in self.layers[:-1]:
|
|
161
|
+
dilation = DILATION_SCHEDULE.get(idx, 1)
|
|
162
|
+
padding = dilation
|
|
163
|
+
|
|
164
|
+
if layer_type == "conv":
|
|
165
|
+
x = x.conv2d(weight, bias, padding=padding, dilation=dilation)
|
|
166
|
+
elif layer_type == "conv_s2":
|
|
167
|
+
x = x.conv2d(weight, bias, padding=padding, stride=2, dilation=dilation)
|
|
168
|
+
elif layer_type == "convT":
|
|
169
|
+
x = x.conv_transpose2d(weight, bias, stride=2, padding=0)
|
|
170
|
+
|
|
171
|
+
if layer_type != "convT":
|
|
172
|
+
x = x.silu()
|
|
173
|
+
|
|
174
|
+
return x
|
|
175
|
+
|
|
176
|
+
def __call__(self, x: Tensor, fuse_chunk=None) -> Tensor:
|
|
150
177
|
"""
|
|
151
178
|
Forward pass.
|
|
152
179
|
|
|
153
180
|
Args:
|
|
154
181
|
x: Input tensor (B, 1, D, H, W)
|
|
182
|
+
fuse_chunk: Number of output channels per chunk (None = full conv)
|
|
155
183
|
|
|
156
184
|
Returns:
|
|
157
185
|
Segmentation (B, D, H, W) after argmax
|
|
158
186
|
"""
|
|
159
|
-
x = self.
|
|
160
|
-
|
|
161
|
-
return self.seq_conv_argmax(x)
|
|
187
|
+
x = self.forward_no_final(x)
|
|
188
|
+
return self.seq_conv_argmax(x, chunk_size=fuse_chunk)
|
|
162
189
|
|
|
163
190
|
|
|
164
191
|
def load_sae(model_path: str, n_classes: int = 3, permute: bool = False) -> SAENet:
|
|
@@ -44,25 +44,67 @@ def sequential_argmax(x: Tensor) -> Tensor:
|
|
|
44
44
|
|
|
45
45
|
class SequentialConvArgmax:
|
|
46
46
|
"""
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
Fused conv + argmax with adaptive chunking.
|
|
48
|
+
|
|
49
|
+
Tries the full conv first (fastest). On MemoryError, halves the chunk
|
|
50
|
+
size and retries until it fits. The working chunk size is cached so
|
|
51
|
+
subsequent runs skip the probing.
|
|
52
|
+
|
|
53
|
+
Set FUSE_CHUNK envvar to override (0 = auto-probe).
|
|
49
54
|
"""
|
|
50
55
|
|
|
51
|
-
def __init__(self, out_channels: int,
|
|
56
|
+
def __init__(self, out_channels: int, final_conv: nn.Conv2d):
|
|
52
57
|
self.out_channels = out_channels
|
|
53
|
-
self.
|
|
58
|
+
self.weight = final_conv.weight
|
|
59
|
+
self.bias = final_conv.bias
|
|
60
|
+
self.conv_kwargs = dict(
|
|
61
|
+
stride=final_conv.stride,
|
|
62
|
+
dilation=final_conv.dilation,
|
|
63
|
+
padding=final_conv.padding,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def _conv_channels(self, x: Tensor, start: int, end: int) -> Tensor:
|
|
67
|
+
"""Compute a slice of output channels [start:end] of the final conv."""
|
|
68
|
+
b = self.bias[start:end] if self.bias is not None else None
|
|
69
|
+
return x.conv2d(self.weight[start:end], b, **self.conv_kwargs)
|
|
70
|
+
|
|
71
|
+
def _chunked_argmax(self, x: Tensor, chunk_size: int) -> Tensor:
|
|
72
|
+
"""Conv + argmax in chunks of chunk_size channels."""
|
|
73
|
+
# First chunk
|
|
74
|
+
end = min(chunk_size, self.out_channels)
|
|
75
|
+
logits = self._conv_channels(x, 0, end).realize()
|
|
76
|
+
outB = logits.max(axis=1, keepdim=True)
|
|
77
|
+
outC = logits.argmax(axis=1, keepdim=True).cast("float32")
|
|
78
|
+
del logits
|
|
79
|
+
outB, outC = outB.realize(), outC.realize()
|
|
80
|
+
|
|
81
|
+
offset = end
|
|
82
|
+
while offset < self.out_channels:
|
|
83
|
+
end = min(offset + chunk_size, self.out_channels)
|
|
84
|
+
logits = self._conv_channels(x, offset, end).realize()
|
|
85
|
+
chunk_max = logits.max(axis=1, keepdim=True)
|
|
86
|
+
chunk_idx = logits.argmax(axis=1, keepdim=True).cast("float32") + float(offset)
|
|
87
|
+
del logits
|
|
88
|
+
mask = chunk_max > outB
|
|
89
|
+
outB = mask.where(chunk_max, outB).realize()
|
|
90
|
+
outC = mask.where(chunk_idx, outC).realize()
|
|
91
|
+
offset = end
|
|
54
92
|
|
|
55
|
-
|
|
93
|
+
return outC.squeeze(1)
|
|
94
|
+
|
|
95
|
+
def __call__(self, x: Tensor, chunk_size: int | None = None) -> Tensor:
|
|
96
|
+
"""Fused conv+argmax. x is the input to the final conv (pre-conv features)."""
|
|
97
|
+
return self._chunked_argmax(x, chunk_size or self.out_channels)
|
|
98
|
+
|
|
99
|
+
def argmax_only(self, x: Tensor) -> Tensor:
|
|
100
|
+
"""Argmax over pre-computed logits (B, C, D, H, W). No conv fusion."""
|
|
56
101
|
outB = x[:, 0:1].realize()
|
|
57
102
|
outC = Tensor.zeros_like(outB)
|
|
58
103
|
|
|
59
104
|
for i in range(1, self.out_channels):
|
|
60
105
|
mask = x[:, i:i+1] > outB
|
|
61
|
-
outB = mask.where(x[:, i:i+1], outB)
|
|
62
|
-
outC = mask.where(float(i), outC)
|
|
63
|
-
if i % self.chunk_size == 0:
|
|
64
|
-
outB = outB.realize()
|
|
65
|
-
outC = outC.realize()
|
|
106
|
+
outB = mask.where(x[:, i:i+1], outB).realize()
|
|
107
|
+
outC = mask.where(float(i), outC).realize()
|
|
66
108
|
|
|
67
109
|
return outC.squeeze(1)
|
|
68
110
|
|
|
@@ -129,7 +171,7 @@ def set_channel_num(config, in_channels, n_classes, channels):
|
|
|
129
171
|
return config
|
|
130
172
|
|
|
131
173
|
|
|
132
|
-
def construct_layer(dropout_p=0, bnorm=True, gelu=False, elu=False, *args, **kwargs):
|
|
174
|
+
def construct_layer(dropout_p=0, bnorm=True, gelu=False, elu=False, affine=False, *args, **kwargs):
|
|
133
175
|
layers = []
|
|
134
176
|
kwargs["kernel_size"] = [kwargs["kernel_size"]] * 3
|
|
135
177
|
layers.append(nn.Conv2d(*args, **kwargs))
|
|
@@ -138,7 +180,7 @@ def construct_layer(dropout_p=0, bnorm=True, gelu=False, elu=False, *args, **kwa
|
|
|
138
180
|
nn.GroupNorm(
|
|
139
181
|
num_groups=kwargs["out_channels"],
|
|
140
182
|
num_channels=kwargs["out_channels"],
|
|
141
|
-
affine=
|
|
183
|
+
affine=affine,
|
|
142
184
|
)
|
|
143
185
|
)
|
|
144
186
|
|
|
@@ -181,15 +223,23 @@ class MeshNet:
|
|
|
181
223
|
self.model = []
|
|
182
224
|
# Check if config specifies bias (default False for backward compat)
|
|
183
225
|
use_bias = config.get("bias", False)
|
|
226
|
+
# Learnable per-channel scale/shift in GroupNorm (default False for
|
|
227
|
+
# backward compat). Models trained with affine GroupNorm (e.g. the deep
|
|
228
|
+
# gridding-free DK-atlas model) carry extra GN weight/bias params.
|
|
229
|
+
use_affine = config.get("affine", False)
|
|
184
230
|
|
|
185
231
|
for block_kwargs in config["layers"][:-1]: # All but the last layer
|
|
232
|
+
# Per-layer "bias" overrides the global default, so a stack can keep
|
|
233
|
+
# bias-free hidden convs while still allowing a biased layer.
|
|
234
|
+
layer_bias = block_kwargs.get("bias", use_bias)
|
|
186
235
|
self.model.extend(
|
|
187
236
|
construct_layer(
|
|
188
237
|
dropout_p=config["dropout_p"],
|
|
189
238
|
bnorm=config["bnorm"],
|
|
190
239
|
gelu=config.get("gelu", False),
|
|
191
240
|
elu=config.get("elu", False),
|
|
192
|
-
|
|
241
|
+
affine=use_affine,
|
|
242
|
+
**{**block_kwargs, "bias": layer_bias},
|
|
193
243
|
)
|
|
194
244
|
)
|
|
195
245
|
|
|
@@ -203,7 +253,7 @@ class MeshNet:
|
|
|
203
253
|
padding=last_config["padding"],
|
|
204
254
|
stride=last_config["stride"],
|
|
205
255
|
dilation=last_config["dilation"],
|
|
206
|
-
bias=use_bias,
|
|
256
|
+
bias=last_config.get("bias", use_bias),
|
|
207
257
|
)
|
|
208
258
|
)
|
|
209
259
|
|
|
@@ -211,20 +261,21 @@ class MeshNet:
|
|
|
211
261
|
self.seq_conv_argmax: SequentialConvArgmax | None = None
|
|
212
262
|
|
|
213
263
|
def init_seq_conv_argmax(self):
|
|
214
|
-
"""Initialize SequentialConvArgmax
|
|
215
|
-
|
|
264
|
+
"""Initialize SequentialConvArgmax with the final conv layer fused in."""
|
|
265
|
+
final_conv = self.model[-1] # last layer is always nn.Conv2d
|
|
266
|
+
self.seq_conv_argmax = SequentialConvArgmax(self.n_classes, final_conv)
|
|
216
267
|
|
|
217
268
|
def normalize(self, x):
|
|
218
269
|
return qnormalize(x) # TODO: interpret normalization from config file
|
|
219
270
|
|
|
220
|
-
def __call__(self, x):
|
|
221
|
-
for layer in self.model:
|
|
271
|
+
def __call__(self, x, fuse_chunk=None):
|
|
272
|
+
for layer in self.model[:-1]: # all layers except final conv
|
|
222
273
|
if isinstance(layer, nn.Conv2d):
|
|
223
274
|
x = chunked_conv(x, layer)
|
|
224
275
|
else:
|
|
225
276
|
x = layer(x)
|
|
226
277
|
assert self.seq_conv_argmax is not None
|
|
227
|
-
return self.seq_conv_argmax(x)
|
|
278
|
+
return self.seq_conv_argmax(x, chunk_size=fuse_chunk)
|
|
228
279
|
|
|
229
280
|
def half(self):
|
|
230
281
|
"""Convert all weights to float16/half precision"""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: brainchop
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.4
|
|
4
4
|
Summary: Portable and lightweight brain segmentation using tinygrad
|
|
5
5
|
Author-email: Mike Doan <spikedoanz@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -31,6 +31,15 @@ BrainChop is a lightweight tool for brain segmentation that runs on pretty much
|
|
|
31
31
|
|
|
32
32
|
---
|
|
33
33
|
|
|
34
|
+
## (NEW) No install single command use
|
|
35
|
+
|
|
36
|
+
Using [uv](https://docs.astral.sh/uv/), brainchop can be ran without needing an enviroment
|
|
37
|
+
```
|
|
38
|
+
uvx brainchop --help
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
|
|
34
43
|
## Installation
|
|
35
44
|
|
|
36
45
|
```bash
|
|
@@ -35,6 +35,23 @@ class TestLoad:
|
|
|
35
35
|
assert vol.data.shape == (256, 256, 256)
|
|
36
36
|
assert isinstance(vol.header, bytes)
|
|
37
37
|
|
|
38
|
+
def test_load_pathlib(self, test_nifti_path):
|
|
39
|
+
vol = load(test_nifti_path)
|
|
40
|
+
assert isinstance(vol, Volume)
|
|
41
|
+
assert vol.data.shape == (256, 256, 256)
|
|
42
|
+
|
|
43
|
+
def test_load_list_of_str(self, test_nifti_path):
|
|
44
|
+
vols = load([str(test_nifti_path), str(test_nifti_path)])
|
|
45
|
+
assert isinstance(vols, list)
|
|
46
|
+
assert len(vols) == 2
|
|
47
|
+
assert all(isinstance(v, Volume) for v in vols)
|
|
48
|
+
|
|
49
|
+
def test_load_list_of_paths(self, test_nifti_path):
|
|
50
|
+
vols = load([test_nifti_path, test_nifti_path])
|
|
51
|
+
assert isinstance(vols, list)
|
|
52
|
+
assert len(vols) == 2
|
|
53
|
+
assert all(isinstance(v, Volume) for v in vols)
|
|
54
|
+
|
|
38
55
|
def test_load_with_crop(self, test_nifti_path):
|
|
39
56
|
vol = load(str(test_nifti_path), crop=2.0)
|
|
40
57
|
assert vol.data.shape[0] <= 256
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|