brainchop 0.2__tar.gz → 0.2.2__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 → brainchop-0.2.2}/LICENSE +1 -1
- {brainchop-0.2/brainchop.egg-info → brainchop-0.2.2}/PKG-INFO +7 -1
- {brainchop-0.2 → brainchop-0.2.2}/README.md +6 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop/__init__.py +8 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop/api.py +196 -12
- {brainchop-0.2 → brainchop-0.2.2}/brainchop/export_model.py +20 -7
- brainchop-0.2.2/brainchop/sae_model.py +173 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop/tiny_meshnet.py +6 -2
- {brainchop-0.2 → brainchop-0.2.2}/brainchop/utils.py +15 -0
- {brainchop-0.2 → brainchop-0.2.2/brainchop.egg-info}/PKG-INFO +7 -1
- {brainchop-0.2 → brainchop-0.2.2}/brainchop.egg-info/SOURCES.txt +2 -3
- {brainchop-0.2 → brainchop-0.2.2}/pyproject.toml +1 -1
- brainchop-0.2/tests/__init__.py +0 -0
- brainchop-0.2/tests/visual.py +0 -85
- {brainchop-0.2 → brainchop-0.2.2}/MANIFEST.in +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop/cli.py +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop/convert_tfjs_to_pth.py +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop/niimath/__init__.py +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop.egg-info/dependency_links.txt +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop.egg-info/entry_points.txt +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop.egg-info/requires.txt +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/brainchop.egg-info/top_level.txt +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/setup.cfg +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/tests/test_api.py +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/tests/test_backend_comparison.py +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/tests/test_batching.py +0 -0
- {brainchop-0.2 → brainchop-0.2.2}/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.2
|
|
4
4
|
Summary: Portable and lightweight brain segmentation using tinygrad
|
|
5
5
|
Author-email: Mike Doan <spikedoanz@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -112,6 +112,12 @@ docker run --rm -it --device=nvidia.com/gpu=all -v [[output directory]]:/app bra
|
|
|
112
112
|
- numpy
|
|
113
113
|
- requests
|
|
114
114
|
|
|
115
|
+
to use the WEBGPU export backend, also install dawn
|
|
116
|
+
```
|
|
117
|
+
brew tap wpmed92/dawn
|
|
118
|
+
brew install dawn
|
|
119
|
+
```
|
|
120
|
+
|
|
115
121
|
## License
|
|
116
122
|
|
|
117
123
|
MIT License
|
|
@@ -85,6 +85,12 @@ docker run --rm -it --device=nvidia.com/gpu=all -v [[output directory]]:/app bra
|
|
|
85
85
|
- numpy
|
|
86
86
|
- requests
|
|
87
87
|
|
|
88
|
+
to use the WEBGPU export backend, also install dawn
|
|
89
|
+
```
|
|
90
|
+
brew tap wpmed92/dawn
|
|
91
|
+
brew install dawn
|
|
92
|
+
```
|
|
93
|
+
|
|
88
94
|
## License
|
|
89
95
|
|
|
90
96
|
MIT License
|
|
@@ -9,6 +9,14 @@ Example:
|
|
|
9
9
|
save(result, "output.nii.gz")
|
|
10
10
|
"""
|
|
11
11
|
|
|
12
|
+
import os
|
|
13
|
+
|
|
14
|
+
# Auto-configure ROCm LD_LIBRARY_PATH if on a ROCm node. Set DIY=1 to skip.
|
|
15
|
+
if os.environ.get("DIY") != "1" and os.path.isdir("/opt/rocm/lib"):
|
|
16
|
+
ld = os.environ.get("LD_LIBRARY_PATH", "")
|
|
17
|
+
if "/opt/rocm/lib" not in ld:
|
|
18
|
+
os.environ["LD_LIBRARY_PATH"] = f"/opt/rocm/lib:{ld}" if ld else "/opt/rocm/lib"
|
|
19
|
+
|
|
12
20
|
from brainchop.api import Volume, load, save, segment, list_models, export, optimize, export_classes
|
|
13
21
|
|
|
14
22
|
__all__ = ["Volume", "load", "save", "segment", "list_models", "export", "optimize", "export_classes"]
|
|
@@ -23,7 +23,9 @@ from brainchop.niimath import (
|
|
|
23
23
|
bwlabel,
|
|
24
24
|
truncate_header_bytes,
|
|
25
25
|
)
|
|
26
|
-
from brainchop.tiny_meshnet import load_meshnet
|
|
26
|
+
from brainchop.tiny_meshnet import load_meshnet, chunked_conv
|
|
27
|
+
from brainchop.sae_model import load_sae
|
|
28
|
+
from tinygrad import nn
|
|
27
29
|
|
|
28
30
|
|
|
29
31
|
# =============================================================================
|
|
@@ -144,7 +146,7 @@ def load(path: str, *, crop: float | None = None, ct: bool = False, comply: bool
|
|
|
144
146
|
data, header = conform(os.path.abspath(path), ct=ct, comply=comply)
|
|
145
147
|
if crop is not None:
|
|
146
148
|
data, _ = crop_to_cutoff(data, crop)
|
|
147
|
-
return Volume(Tensor(data), header)
|
|
149
|
+
return Volume(Tensor(data.copy()), header)
|
|
148
150
|
|
|
149
151
|
|
|
150
152
|
def save(volume: Volume, path: str) -> None:
|
|
@@ -172,16 +174,132 @@ def save(volume: Volume, path: str) -> None:
|
|
|
172
174
|
)
|
|
173
175
|
|
|
174
176
|
|
|
175
|
-
def
|
|
177
|
+
def _create_flip_matrix(size: int) -> Tensor:
|
|
178
|
+
"""Create a permutation matrix that reverses order along an axis."""
|
|
179
|
+
import numpy as np
|
|
180
|
+
# Anti-diagonal identity matrix: P[i, j] = 1 if j = size-1-i
|
|
181
|
+
P = np.zeros((size, size), dtype=np.float32)
|
|
182
|
+
for i in range(size):
|
|
183
|
+
P[i, size - 1 - i] = 1.0
|
|
184
|
+
return Tensor(P)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class TTAModel:
|
|
188
|
+
"""Test-Time Augmentation wrapper using flip ensemble."""
|
|
189
|
+
|
|
190
|
+
def __init__(self, model, flip_axis: str = "sagittal"):
|
|
191
|
+
"""
|
|
192
|
+
Initialize TTA wrapper.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
model: The underlying segmentation model
|
|
196
|
+
flip_axis: Which axis to flip for TTA:
|
|
197
|
+
- "sagittal" (default): flip along D axis (left-right)
|
|
198
|
+
- "coronal": flip along H axis (front-back)
|
|
199
|
+
- "axial": flip along W axis (top-bottom)
|
|
200
|
+
"""
|
|
201
|
+
self._model = model
|
|
202
|
+
self.n_classes = model.n_classes
|
|
203
|
+
self._flip_axis = flip_axis
|
|
204
|
+
# Pre-create flip matrix for all dimensions (256)
|
|
205
|
+
self._flip_matrix = _create_flip_matrix(256)
|
|
206
|
+
|
|
207
|
+
def _flip_sagittal(self, x: Tensor) -> Tensor:
|
|
208
|
+
"""Flip tensor along depth/sagittal axis (D, axis 2)."""
|
|
209
|
+
# x: (B, C, D, H, W) - flip along D
|
|
210
|
+
b, c, d, h, w = x.shape
|
|
211
|
+
x_reshaped = x.reshape(b * c, d, h * w) # (B*C, D, H*W)
|
|
212
|
+
x_t = x_reshaped.permute(0, 2, 1) # (B*C, H*W, D)
|
|
213
|
+
x_flipped_t = x_t @ self._flip_matrix # (B*C, H*W, D)
|
|
214
|
+
x_flipped = x_flipped_t.permute(0, 2, 1) # (B*C, D, H*W)
|
|
215
|
+
return x_flipped.reshape(b, c, d, h, w)
|
|
216
|
+
|
|
217
|
+
def _flip_coronal(self, x: Tensor) -> Tensor:
|
|
218
|
+
"""Flip tensor along height/coronal axis (H, axis 3)."""
|
|
219
|
+
# x: (B, C, D, H, W) - flip along H
|
|
220
|
+
b, c, d, h, w = x.shape
|
|
221
|
+
x_reshaped = x.reshape(b * c * d, h, w) # (B*C*D, H, W)
|
|
222
|
+
x_t = x_reshaped.permute(0, 2, 1) # (B*C*D, W, H)
|
|
223
|
+
x_flipped_t = x_t @ self._flip_matrix # (B*C*D, W, H)
|
|
224
|
+
x_flipped = x_flipped_t.permute(0, 2, 1) # (B*C*D, H, W)
|
|
225
|
+
return x_flipped.reshape(b, c, d, h, w)
|
|
226
|
+
|
|
227
|
+
def _flip_axial(self, x: Tensor) -> Tensor:
|
|
228
|
+
"""Flip tensor along width/axial axis (W, axis 4)."""
|
|
229
|
+
# x: (B, C, D, H, W) - flip along W
|
|
230
|
+
b, c, d, h, w = x.shape
|
|
231
|
+
x_reshaped = x.reshape(b * c * d * h, w) # (B*C*D*H, W)
|
|
232
|
+
x_flipped = x_reshaped @ self._flip_matrix # (B*C*D*H, W)
|
|
233
|
+
return x_flipped.reshape(b, c, d, h, w)
|
|
234
|
+
|
|
235
|
+
def _flip(self, x: Tensor) -> Tensor:
|
|
236
|
+
"""Flip tensor along the configured axis."""
|
|
237
|
+
if self._flip_axis == "sagittal":
|
|
238
|
+
return self._flip_sagittal(x)
|
|
239
|
+
elif self._flip_axis == "coronal":
|
|
240
|
+
return self._flip_coronal(x)
|
|
241
|
+
elif self._flip_axis == "axial":
|
|
242
|
+
return self._flip_axial(x)
|
|
243
|
+
else:
|
|
244
|
+
raise ValueError(f"Unknown flip axis: {self._flip_axis}")
|
|
245
|
+
|
|
246
|
+
def _forward_no_argmax(self, x: Tensor) -> Tensor:
|
|
247
|
+
"""Forward pass through conv layers without final argmax."""
|
|
248
|
+
# Use forward_no_argmax if available (SAENet), otherwise iterate layers (MeshNet)
|
|
249
|
+
if hasattr(self._model, 'forward_no_argmax'):
|
|
250
|
+
return self._model.forward_no_argmax(x)
|
|
251
|
+
for layer in self._model.model:
|
|
252
|
+
if isinstance(layer, nn.Conv2d):
|
|
253
|
+
x = chunked_conv(x, layer)
|
|
254
|
+
else:
|
|
255
|
+
x = layer(x)
|
|
256
|
+
return x
|
|
257
|
+
|
|
258
|
+
def normalize(self, x: Tensor) -> Tensor:
|
|
259
|
+
"""Delegate normalization to underlying model."""
|
|
260
|
+
return self._model.normalize(x)
|
|
261
|
+
|
|
262
|
+
def __call__(self, x: Tensor) -> Tensor:
|
|
263
|
+
"""
|
|
264
|
+
Forward pass with flip ensemble (test-time augmentation).
|
|
265
|
+
|
|
266
|
+
Runs inference on both original and flipped inputs,
|
|
267
|
+
sums the logits, then applies argmax.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
x: Input tensor (B, 1, D, H, W)
|
|
271
|
+
|
|
272
|
+
Returns:
|
|
273
|
+
Segmentation (B, D, H, W) after argmax
|
|
274
|
+
"""
|
|
275
|
+
# Force input into computation graph - add zero to create explicit dependency
|
|
276
|
+
x = x + Tensor.zeros(1)
|
|
277
|
+
|
|
278
|
+
# Forward on original
|
|
279
|
+
logits_orig = self._forward_no_argmax(x)
|
|
280
|
+
|
|
281
|
+
# Flip input, run inference, then unflip output
|
|
282
|
+
x_flipped = self._flip(x)
|
|
283
|
+
logits_flipped = self._forward_no_argmax(x_flipped)
|
|
284
|
+
logits_unflipped = self._flip(logits_flipped)
|
|
285
|
+
|
|
286
|
+
# Sum logits and argmax
|
|
287
|
+
summed = logits_orig + logits_unflipped
|
|
288
|
+
return self._model.seq_conv_argmax(summed)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _load_model(model: str, *, tta: bool = False, flip_axis: str = "sagittal"):
|
|
176
292
|
"""
|
|
177
293
|
Load model by name or path.
|
|
178
294
|
|
|
179
295
|
Args:
|
|
180
296
|
model: Model name (e.g., "subcortical") or path to model directory
|
|
181
297
|
containing model.json and model.pth/model.bin
|
|
298
|
+
tta: If True, wrap model with test-time augmentation (flip ensemble)
|
|
299
|
+
flip_axis: Which axis to flip for TTA ("sagittal", "coronal", "axial")
|
|
182
300
|
"""
|
|
183
301
|
from pathlib import Path
|
|
184
|
-
from brainchop.utils import find_pth_files, AVAILABLE_MODELS, unwrap_path
|
|
302
|
+
from brainchop.utils import find_pth_files, find_sae_files, AVAILABLE_MODELS, unwrap_path
|
|
185
303
|
|
|
186
304
|
# Check if it's a path (absolute, relative, or file://)
|
|
187
305
|
if model.startswith("file://"):
|
|
@@ -206,14 +324,27 @@ def _load_model(model: str):
|
|
|
206
324
|
else:
|
|
207
325
|
raise FileNotFoundError(f"No model.pth or model.bin found in {model_path}")
|
|
208
326
|
|
|
209
|
-
|
|
327
|
+
m = load_meshnet(str(config_fn), str(weights_fn))
|
|
328
|
+
return TTAModel(m, flip_axis=flip_axis) if tta else m
|
|
210
329
|
|
|
211
330
|
# Otherwise treat as model name
|
|
212
331
|
if model not in AVAILABLE_MODELS:
|
|
213
332
|
raise ValueError(f"Unknown model: {model}. Available: {list(AVAILABLE_MODELS.keys())}")
|
|
214
333
|
|
|
334
|
+
model_info = AVAILABLE_MODELS[model]
|
|
335
|
+
|
|
336
|
+
# Check model type - SAE or MeshNet
|
|
337
|
+
if model_info.get("type") == "sae":
|
|
338
|
+
model_fn = find_sae_files(model)
|
|
339
|
+
n_classes = model_info.get("n_classes", 3)
|
|
340
|
+
permute = os.environ.get("SAE_PERMUTE", "0") == "1"
|
|
341
|
+
m = load_sae(unwrap_path(model_fn), n_classes=n_classes, permute=permute)
|
|
342
|
+
return TTAModel(m, flip_axis=flip_axis) if tta else m
|
|
343
|
+
|
|
344
|
+
# Default: MeshNet
|
|
215
345
|
config_fn, model_fn = find_pth_files(model)
|
|
216
|
-
|
|
346
|
+
m = load_meshnet(unwrap_path(config_fn), unwrap_path(model_fn))
|
|
347
|
+
return TTAModel(m, flip_axis=flip_axis) if tta else m
|
|
217
348
|
|
|
218
349
|
|
|
219
350
|
def optimize(model: str, *, beam: int = 2, batch_size: int = 1) -> None:
|
|
@@ -260,6 +391,7 @@ def segment(
|
|
|
260
391
|
shard_size: int = 1,
|
|
261
392
|
beam: int = 0,
|
|
262
393
|
return_raw: bool = False,
|
|
394
|
+
tta: bool = False,
|
|
263
395
|
): # type: ignore[return]
|
|
264
396
|
"""
|
|
265
397
|
Segment brain volume(s).
|
|
@@ -270,6 +402,7 @@ def segment(
|
|
|
270
402
|
shard_size: Batch size for processing multiple volumes
|
|
271
403
|
beam: BEAM optimization level (0 = use cached or none)
|
|
272
404
|
return_raw: If True, also return raw model output (pre-argmax) for export_classes
|
|
405
|
+
tta: If True, use test-time augmentation (flip ensemble)
|
|
273
406
|
|
|
274
407
|
Returns:
|
|
275
408
|
Segmented Volume(s) - single if input was single, list if input was list
|
|
@@ -312,7 +445,7 @@ def segment(
|
|
|
312
445
|
if beam > 0:
|
|
313
446
|
os.environ["BEAM"] = str(beam)
|
|
314
447
|
|
|
315
|
-
m = _load_model(model)
|
|
448
|
+
m = _load_model(model, tta=tta)
|
|
316
449
|
results: list[Volume] = []
|
|
317
450
|
raw_outputs: list[Tensor] = []
|
|
318
451
|
|
|
@@ -326,8 +459,12 @@ def segment(
|
|
|
326
459
|
if hasattr(m, "normalize"):
|
|
327
460
|
batched = m.normalize(batched)
|
|
328
461
|
|
|
329
|
-
raw_output = m(batched)
|
|
330
|
-
|
|
462
|
+
raw_output = m(batched)
|
|
463
|
+
# TTAModel returns raw logits (B, C, D, H, W), MeshNet returns argmaxed (B, D, H, W)
|
|
464
|
+
if len(raw_output.shape) == 5:
|
|
465
|
+
output = raw_output.argmax(axis=1) # (B, C, D, H, W) -> (B, D, H, W)
|
|
466
|
+
else:
|
|
467
|
+
output = raw_output # Already (B, D, H, W)
|
|
331
468
|
|
|
332
469
|
# Split batch and convert back to (X,Y,Z)
|
|
333
470
|
for j in range(output.shape[0]):
|
|
@@ -356,6 +493,9 @@ def export(
|
|
|
356
493
|
*,
|
|
357
494
|
target: str = "webgpu",
|
|
358
495
|
beam: int = 0,
|
|
496
|
+
tta: bool = False,
|
|
497
|
+
flip_axis: str = "sagittal",
|
|
498
|
+
force: bool = False,
|
|
359
499
|
) -> tuple[str, str]:
|
|
360
500
|
"""
|
|
361
501
|
Export model to WebGPU or other target format.
|
|
@@ -365,6 +505,9 @@ def export(
|
|
|
365
505
|
output_dir: Directory to save exported files
|
|
366
506
|
target: Export target ("webgpu", "clang", "wasm")
|
|
367
507
|
beam: BEAM optimization level (0 = no optimization)
|
|
508
|
+
tta: If True, export with test-time augmentation (flip ensemble)
|
|
509
|
+
flip_axis: Which axis to flip for TTA ("sagittal", "coronal", "axial")
|
|
510
|
+
force: If True, skip memory safety checks
|
|
368
511
|
|
|
369
512
|
Returns:
|
|
370
513
|
Tuple of (js_path, weights_path)
|
|
@@ -377,16 +520,57 @@ def export(
|
|
|
377
520
|
|
|
378
521
|
# With BEAM optimization
|
|
379
522
|
>>> js_path, weights_path = export("tissue_fast", "/tmp/export", beam=2)
|
|
523
|
+
|
|
524
|
+
# With test-time augmentation (sagittal flip)
|
|
525
|
+
>>> js_path, weights_path = export("tissue_fast", "/tmp/export", tta=True)
|
|
526
|
+
|
|
527
|
+
# With coronal TTA
|
|
528
|
+
>>> js_path, weights_path = export("tissue_fast", "/tmp/export", tta=True, flip_axis="coronal")
|
|
380
529
|
```
|
|
381
530
|
"""
|
|
382
531
|
from tinygrad.nn.state import safe_save
|
|
383
532
|
from brainchop.export_model import export_model
|
|
384
533
|
|
|
534
|
+
# Memory safety guard: small chunk limits can cause OOM
|
|
535
|
+
chunk_limit = int(os.environ.get("CHUNK_LIMIT", 0))
|
|
536
|
+
min_safe_chunk = 256 * 1024 * 1024 # 256MB
|
|
537
|
+
if chunk_limit > 0 and chunk_limit < min_safe_chunk and not force:
|
|
538
|
+
chunk_mb = chunk_limit // (1024 * 1024)
|
|
539
|
+
raise RuntimeError(
|
|
540
|
+
f"CHUNK_LIMIT={chunk_mb}MB is too small and may cause OOM. "
|
|
541
|
+
f"Use CHUNK_LIMIT >= 256MB or set force=True to override."
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
# Check available system memory - block if free memory is below threshold
|
|
545
|
+
require_free_gb = int(os.environ.get("REQUIRE_FREE_GB", 0))
|
|
546
|
+
if require_free_gb > 0:
|
|
547
|
+
import subprocess
|
|
548
|
+
result = subprocess.run(
|
|
549
|
+
["vm_stat"], capture_output=True, text=True
|
|
550
|
+
)
|
|
551
|
+
# Parse free pages from vm_stat output
|
|
552
|
+
for line in result.stdout.split("\n"):
|
|
553
|
+
if "Pages free:" in line:
|
|
554
|
+
free_pages = int(line.split(":")[1].strip().rstrip("."))
|
|
555
|
+
# macOS page size is typically 16KB
|
|
556
|
+
free_gb = (free_pages * 16384) / (1024 ** 3)
|
|
557
|
+
if free_gb < require_free_gb:
|
|
558
|
+
raise RuntimeError(
|
|
559
|
+
f"Only {free_gb:.1f}GB free memory, need {require_free_gb}GB. "
|
|
560
|
+
f"Close other apps or set force=True to override."
|
|
561
|
+
)
|
|
562
|
+
break
|
|
563
|
+
|
|
385
564
|
output_path = Path(output_dir)
|
|
386
565
|
output_path.mkdir(parents=True, exist_ok=True)
|
|
387
566
|
|
|
388
567
|
# Get model name for output files
|
|
389
568
|
model_name = Path(model).name if "/" in model else model
|
|
569
|
+
if tta:
|
|
570
|
+
if flip_axis == "sagittal":
|
|
571
|
+
model_name = f"{model_name}_tta"
|
|
572
|
+
else:
|
|
573
|
+
model_name = f"{model_name}_tta_{flip_axis}"
|
|
390
574
|
|
|
391
575
|
original_beam = os.environ.get("BEAM")
|
|
392
576
|
try:
|
|
@@ -394,10 +578,10 @@ def export(
|
|
|
394
578
|
os.environ["BEAM"] = str(beam)
|
|
395
579
|
|
|
396
580
|
# Load model
|
|
397
|
-
m = _load_model(model)
|
|
581
|
+
m = _load_model(model, tta=tta, flip_axis=flip_axis)
|
|
398
582
|
|
|
399
|
-
# Create dummy input
|
|
400
|
-
dummy_input = Tensor.
|
|
583
|
+
# Create dummy input - use randn to prevent JIT from treating as constant
|
|
584
|
+
dummy_input = Tensor.randn(1, 1, 256, 256, 256, dtype="float32")
|
|
401
585
|
|
|
402
586
|
# Export
|
|
403
587
|
prg, _input_sizes, _output_sizes, state = export_model(
|
|
@@ -112,7 +112,7 @@ const {model_name}_name_to_id = Object.fromEntries(weightNames.map((name, index)
|
|
|
112
112
|
def dtype_to_js_type(dtype: DType) -> str:
|
|
113
113
|
return f"{'Uint' if dtype in dtypes.uints else 'Int' if (dtype in dtypes.sints or dtype == dtypes.bool) else 'Float'}{8*dtype.itemsize}Array"
|
|
114
114
|
|
|
115
|
-
def export_model_webgpu(functions, statements, bufs, weight_names, input_names, output_names, model_name, symbolic_vars={}, stream_weights=False) -> Tuple[str,int,int]:
|
|
115
|
+
def export_model_webgpu(functions, statements, bufs, weight_names, input_names, output_names, model_name, symbolic_vars={}, stream_weights=False, batch_size=1) -> Tuple[str,int,int]:
|
|
116
116
|
kernel_code = '\n\n'.join([f"const {key} = `{code.replace(key, 'main')}`;" for key, code in functions.items()])
|
|
117
117
|
kernel_names = ', '.join([name for (name, _, _, _) in statements])
|
|
118
118
|
input_names += list(symbolic_vars.values())
|
|
@@ -127,7 +127,22 @@ def export_model_webgpu(functions, statements, bufs, weight_names, input_names,
|
|
|
127
127
|
for _, (_, args, _, _) in enumerate(statements)
|
|
128
128
|
])
|
|
129
129
|
layouts = f"const layouts=[{create_bind_group_layouts}]"
|
|
130
|
-
|
|
130
|
+
|
|
131
|
+
# Generate batched kernel calls to avoid GPU timeout on Windows
|
|
132
|
+
num_statements = len(statements)
|
|
133
|
+
if num_statements <= batch_size:
|
|
134
|
+
# Small enough to run in one batch
|
|
135
|
+
kernel_calls = '\n '.join([f"addComputePass(device, commandEncoder, pipelines[{i}], layouts[{i}], infinityBuf, [{', '.join(args)}], [{', '.join(str(x) for x in global_size)}]);" for i, (_name, args, global_size, _local_size) in enumerate(statements)])
|
|
136
|
+
else:
|
|
137
|
+
# Generate batched submissions
|
|
138
|
+
batches = []
|
|
139
|
+
for batch_start in range(0, num_statements, batch_size):
|
|
140
|
+
batch_end = min(batch_start + batch_size, num_statements)
|
|
141
|
+
batch_calls = [f"addComputePass(device, commandEncoder, pipelines[{i}], layouts[{i}], infinityBuf, [{', '.join(args)}], [{', '.join(str(x) for x in global_size)}]);" for i, (_name, args, global_size, _local_size) in enumerate(statements[batch_start:batch_end], start=batch_start)]
|
|
142
|
+
batches.append('\n '.join(batch_calls))
|
|
143
|
+
|
|
144
|
+
# Join batches with submit and new encoder
|
|
145
|
+
kernel_calls = '\n device.queue.submit([commandEncoder.finish()]);\n await device.queue.onSubmittedWorkDone();\n commandEncoder = device.createCommandEncoder();\n '.join(batches)
|
|
131
146
|
|
|
132
147
|
buf_type = lambda x: "createUniformBuf" if x in set(uop.arg[0] for uop in symbolic_vars) else "createEmptyBuf"
|
|
133
148
|
map_to_external_weight = lambda _key: f"state_dict['{weight_names[_key]}']" if stream_weights else f"getTensorBuffer(safetensor, metadata['{weight_names[_key]}'])"
|
|
@@ -223,12 +238,11 @@ const setupNet = async (device, {"state_dict" if stream_weights else "safetensor
|
|
|
223
238
|
}}))
|
|
224
239
|
|
|
225
240
|
return async ({",".join([f"_{input_name}" for input_name in input_names])}) => {{
|
|
226
|
-
|
|
241
|
+
let commandEncoder = device.createCommandEncoder();
|
|
227
242
|
{input_writers}
|
|
228
243
|
{kernel_calls}
|
|
229
244
|
{outbuf_copies}
|
|
230
|
-
|
|
231
|
-
device.queue.submit([gpuCommands]);
|
|
245
|
+
device.queue.submit([commandEncoder.finish()]);
|
|
232
246
|
|
|
233
247
|
{output_readers}
|
|
234
248
|
return {output_return};
|
|
@@ -243,8 +257,7 @@ export default {model_name};
|
|
|
243
257
|
def export_model(model, target:str, *inputs, model_name: Optional[str] = "model", stream_weights=False):
|
|
244
258
|
assert Device.DEFAULT in EXPORT_SUPPORTED_DEVICE, f"only {', '.join(EXPORT_SUPPORTED_DEVICE)} are supported"
|
|
245
259
|
|
|
246
|
-
|
|
247
|
-
with Context(JIT=2, CPU_COUNT=1): run,special_names = jit_model(model, *inputs)
|
|
260
|
+
with Context(JIT=2): run,special_names = jit_model(model, *inputs)
|
|
248
261
|
functions, statements, bufs, bufs_to_save = compile_net(run, special_names)
|
|
249
262
|
state = get_state_dict(model)
|
|
250
263
|
weight_names = {id(x.uop.base.realized): name for name, x in state.items()}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Spatial AutoEncoder (SAE) model for brain tissue segmentation.
|
|
3
|
+
|
|
4
|
+
This module provides SAENet, an encoder-decoder architecture with:
|
|
5
|
+
- Dilated convolutions for large receptive field
|
|
6
|
+
- Spatial bottleneck (256³ → 128³ → 256³)
|
|
7
|
+
- SiLU activation
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from tinygrad import Tensor
|
|
11
|
+
from tinygrad.nn.state import torch_load
|
|
12
|
+
|
|
13
|
+
from brainchop.tiny_meshnet import qnormalize, SequentialConvArgmax
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# Layer indices in the fused model (odd indices are SiLU activations, no params)
|
|
17
|
+
LAYER_INDICES = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 23, 25, 27, 29, 31, 33]
|
|
18
|
+
DOWNSAMPLE_LAYER = 10 # stride=2, 256³ → 128³
|
|
19
|
+
UPSAMPLE_LAYER = 22 # ConvTranspose stride=2, 128³ → 256³
|
|
20
|
+
|
|
21
|
+
# Dilation schedule from modelAEgelu_dilated.json
|
|
22
|
+
# JSON has 16 layers: 5 encoder + 5 bottleneck + 5 decoder + 1 final
|
|
23
|
+
# Downsample/upsample are added by model class (not in JSON)
|
|
24
|
+
# padding = dilation for 3x3 kernel to maintain spatial size
|
|
25
|
+
DILATION_SCHEDULE = {
|
|
26
|
+
# Encoder (JSON 0-4): d=1,2,4,6,8
|
|
27
|
+
0: 1,
|
|
28
|
+
2: 2,
|
|
29
|
+
4: 4,
|
|
30
|
+
6: 6,
|
|
31
|
+
8: 8,
|
|
32
|
+
# Downsample (not in JSON, strided conv)
|
|
33
|
+
10: 1,
|
|
34
|
+
# Bottleneck (JSON 5-9): d=10,12,16,12,10
|
|
35
|
+
12: 10,
|
|
36
|
+
14: 12,
|
|
37
|
+
16: 16, # peak
|
|
38
|
+
18: 12,
|
|
39
|
+
20: 10,
|
|
40
|
+
# Upsample (ConvTranspose, no dilation)
|
|
41
|
+
22: 1,
|
|
42
|
+
# Decoder (JSON 10-14): d=8,6,4,2,1
|
|
43
|
+
23: 8,
|
|
44
|
+
25: 6,
|
|
45
|
+
27: 4,
|
|
46
|
+
29: 2,
|
|
47
|
+
31: 1,
|
|
48
|
+
# Final 1x1 (JSON 15)
|
|
49
|
+
33: 1,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _permute_weights(weight, is_conv_transpose: bool = False):
|
|
54
|
+
"""
|
|
55
|
+
Permute conv weights by swapping D and W spatial dimensions.
|
|
56
|
+
|
|
57
|
+
This aligns PyTorch weights with the expected input orientation.
|
|
58
|
+
PyTorch weight shape: (out_ch, in_ch, D, H, W) for Conv3d
|
|
59
|
+
(in_ch, out_ch, D, H, W) for ConvTranspose3d
|
|
60
|
+
After permute: swap axes 2 and 4 (D <-> W)
|
|
61
|
+
"""
|
|
62
|
+
import numpy as np
|
|
63
|
+
w = weight.numpy()
|
|
64
|
+
w = np.swapaxes(w, 2, 4) # Swap D and W
|
|
65
|
+
return Tensor(w)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class SAENet:
|
|
69
|
+
"""
|
|
70
|
+
Spatial AutoEncoder network for brain segmentation.
|
|
71
|
+
|
|
72
|
+
Architecture:
|
|
73
|
+
- Encoder: Conv3d layers with SiLU, one strided conv for downsampling
|
|
74
|
+
- Bottleneck: Conv3d layers at reduced spatial resolution
|
|
75
|
+
- Decoder: ConvTranspose3d for upsampling, Conv3d layers with SiLU
|
|
76
|
+
- Output: 1x1x1 conv to n_classes
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, state_dict: dict, n_classes: int = 3, permute: bool = False):
|
|
80
|
+
"""Load model from state dict with numeric keys.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
state_dict: Model weights with numeric keys (0.weight, 0.bias, etc.)
|
|
84
|
+
n_classes: Number of output classes
|
|
85
|
+
permute: If True, swap D and W dimensions in weights to match input orientation
|
|
86
|
+
"""
|
|
87
|
+
self.layers = []
|
|
88
|
+
self.n_classes = n_classes
|
|
89
|
+
|
|
90
|
+
for idx in LAYER_INDICES:
|
|
91
|
+
# Move weights from DISK to compute device via numpy roundtrip
|
|
92
|
+
weight = Tensor(state_dict[f"{idx}.weight"].numpy())
|
|
93
|
+
bias = Tensor(state_dict[f"{idx}.bias"].numpy())
|
|
94
|
+
|
|
95
|
+
if idx == UPSAMPLE_LAYER:
|
|
96
|
+
layer_type = "convT"
|
|
97
|
+
elif idx == DOWNSAMPLE_LAYER:
|
|
98
|
+
layer_type = "conv_s2"
|
|
99
|
+
else:
|
|
100
|
+
layer_type = "conv"
|
|
101
|
+
|
|
102
|
+
# Permute weights if needed (swap D <-> W)
|
|
103
|
+
if permute:
|
|
104
|
+
weight = _permute_weights(weight, is_conv_transpose=(layer_type == "convT"))
|
|
105
|
+
|
|
106
|
+
self.layers.append((layer_type, idx, weight, bias))
|
|
107
|
+
|
|
108
|
+
self.seq_conv_argmax = SequentialConvArgmax(self.n_classes)
|
|
109
|
+
|
|
110
|
+
def normalize(self, x: Tensor) -> Tensor:
|
|
111
|
+
"""Quantile normalization (same as MeshNet)."""
|
|
112
|
+
return qnormalize(x)
|
|
113
|
+
|
|
114
|
+
def forward_no_argmax(self, x: Tensor) -> Tensor:
|
|
115
|
+
"""
|
|
116
|
+
Forward pass returning logits (no argmax).
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
x: Input tensor (B, 1, D, H, W)
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
Logits tensor (B, n_classes, D, H, W)
|
|
123
|
+
"""
|
|
124
|
+
# Process all layers except the last (which has no activation)
|
|
125
|
+
for layer_type, idx, weight, bias in self.layers[:-1]:
|
|
126
|
+
dilation = DILATION_SCHEDULE.get(idx, 1)
|
|
127
|
+
padding = dilation # padding = dilation for 3x3 kernel
|
|
128
|
+
|
|
129
|
+
if layer_type == "conv":
|
|
130
|
+
x = x.conv2d(weight, bias, padding=padding, dilation=dilation)
|
|
131
|
+
elif layer_type == "conv_s2":
|
|
132
|
+
x = x.conv2d(weight, bias, padding=padding, stride=2, dilation=dilation)
|
|
133
|
+
elif layer_type == "convT":
|
|
134
|
+
x = x.conv_transpose2d(weight, bias, stride=2, padding=0)
|
|
135
|
+
|
|
136
|
+
# SiLU activation after each conv (except output and ConvTranspose)
|
|
137
|
+
# ConvTranspose (upsample) has no activation - goes directly to next conv
|
|
138
|
+
if layer_type != "convT":
|
|
139
|
+
x = x.silu()
|
|
140
|
+
|
|
141
|
+
# Final layer: 1x1x1 conv, no activation, no padding
|
|
142
|
+
_, idx, weight, bias = self.layers[-1]
|
|
143
|
+
kernel_size = weight.shape[2]
|
|
144
|
+
padding = (kernel_size - 1) // 2 # 0 for 1x1, 1 for 3x3
|
|
145
|
+
x = x.conv2d(weight, bias, padding=padding)
|
|
146
|
+
|
|
147
|
+
return x
|
|
148
|
+
|
|
149
|
+
def __call__(self, x: Tensor) -> Tensor:
|
|
150
|
+
"""
|
|
151
|
+
Forward pass.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
x: Input tensor (B, 1, D, H, W)
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
Segmentation (B, D, H, W) after argmax
|
|
158
|
+
"""
|
|
159
|
+
x = self.forward_no_argmax(x)
|
|
160
|
+
# Memory-efficient argmax
|
|
161
|
+
return self.seq_conv_argmax(x)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def load_sae(model_path: str, n_classes: int = 3, permute: bool = False) -> SAENet:
|
|
165
|
+
"""Load SAENet model from .pth file.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
model_path: Path to .pth file with fused model weights
|
|
169
|
+
n_classes: Number of output classes
|
|
170
|
+
permute: If True, swap D and W dimensions in weights (default True for correct orientation)
|
|
171
|
+
"""
|
|
172
|
+
state_dict = torch_load(model_path)
|
|
173
|
+
return SAENet(state_dict, n_classes=n_classes, permute=permute)
|
|
@@ -67,11 +67,15 @@ class SequentialConvArgmax:
|
|
|
67
67
|
return outC.squeeze(1)
|
|
68
68
|
|
|
69
69
|
|
|
70
|
-
def chunked_conv(x: Tensor, conv_layer: nn.Conv2d, chunk_limit: int =
|
|
70
|
+
def chunked_conv(x: Tensor, conv_layer: nn.Conv2d, chunk_limit: int | None = None) -> Tensor:
|
|
71
71
|
"""
|
|
72
|
-
Workaround for WebGPU matmul bug: when output exceeds
|
|
72
|
+
Workaround for WebGPU matmul bug: when output exceeds chunk_limit elements,
|
|
73
73
|
process output channels in chunks to avoid 32-bit integer overflow.
|
|
74
|
+
|
|
75
|
+
Set CHUNK_LIMIT env var to override the default of 2^30 (~1GB).
|
|
74
76
|
"""
|
|
77
|
+
if chunk_limit is None:
|
|
78
|
+
chunk_limit = int(os.environ.get("CHUNK_LIMIT", 2**30))
|
|
75
79
|
from functools import reduce
|
|
76
80
|
spatial = int(reduce(lambda a, b: int(a) * int(b), x.shape[2:], 1))
|
|
77
81
|
out_channels = int(conv_layer.weight.shape[0])
|
|
@@ -92,6 +92,21 @@ def find_pth_files(model_name) -> Tuple[Path | Any, Path | Any]:
|
|
|
92
92
|
return json_fn, bin_fn
|
|
93
93
|
|
|
94
94
|
|
|
95
|
+
SAE_BASE_URL = "https://github.com/neuroneural/brainchop-models/raw/main/sae/"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def find_sae_files(model_name) -> Path:
|
|
99
|
+
"""Find or download SAE model weights."""
|
|
100
|
+
model_dir = AVAILABLE_MODELS[model_name]["folder"]
|
|
101
|
+
cache_dir = Path.home() / ".cache" / "brainchop" / "models" / model_dir
|
|
102
|
+
pth_fn = cache_dir / "model.pth"
|
|
103
|
+
|
|
104
|
+
if not pth_fn.exists():
|
|
105
|
+
download(f"{SAE_BASE_URL}{model_dir}/model.pth", pth_fn)
|
|
106
|
+
|
|
107
|
+
return pth_fn
|
|
108
|
+
|
|
109
|
+
|
|
95
110
|
def crop_to_cutoff(arr: np.ndarray, cutoff_percent: float = 2.0):
|
|
96
111
|
"""Crop volume to bounding box above percentile cutoff."""
|
|
97
112
|
if not isinstance(arr, np.ndarray) or arr.ndim != 3:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: brainchop
|
|
3
|
-
Version: 0.2
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: Portable and lightweight brain segmentation using tinygrad
|
|
5
5
|
Author-email: Mike Doan <spikedoanz@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -112,6 +112,12 @@ docker run --rm -it --device=nvidia.com/gpu=all -v [[output directory]]:/app bra
|
|
|
112
112
|
- numpy
|
|
113
113
|
- requests
|
|
114
114
|
|
|
115
|
+
to use the WEBGPU export backend, also install dawn
|
|
116
|
+
```
|
|
117
|
+
brew tap wpmed92/dawn
|
|
118
|
+
brew install dawn
|
|
119
|
+
```
|
|
120
|
+
|
|
115
121
|
## License
|
|
116
122
|
|
|
117
123
|
MIT License
|
|
@@ -7,6 +7,7 @@ brainchop/api.py
|
|
|
7
7
|
brainchop/cli.py
|
|
8
8
|
brainchop/convert_tfjs_to_pth.py
|
|
9
9
|
brainchop/export_model.py
|
|
10
|
+
brainchop/sae_model.py
|
|
10
11
|
brainchop/tiny_meshnet.py
|
|
11
12
|
brainchop/utils.py
|
|
12
13
|
brainchop.egg-info/PKG-INFO
|
|
@@ -16,9 +17,7 @@ brainchop.egg-info/entry_points.txt
|
|
|
16
17
|
brainchop.egg-info/requires.txt
|
|
17
18
|
brainchop.egg-info/top_level.txt
|
|
18
19
|
brainchop/niimath/__init__.py
|
|
19
|
-
tests/__init__.py
|
|
20
20
|
tests/test_api.py
|
|
21
21
|
tests/test_backend_comparison.py
|
|
22
22
|
tests/test_batching.py
|
|
23
|
-
tests/test_sequential_argmax.py
|
|
24
|
-
tests/visual.py
|
|
23
|
+
tests/test_sequential_argmax.py
|
brainchop-0.2/tests/__init__.py
DELETED
|
File without changes
|
brainchop-0.2/tests/visual.py
DELETED
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Convenience test for manual visual inspection of brainchop output.
|
|
3
|
-
Runs all models through the API and generates mrpeek commands for inspection.
|
|
4
|
-
"""
|
|
5
|
-
|
|
6
|
-
import hashlib
|
|
7
|
-
from pathlib import Path
|
|
8
|
-
from tinygrad.helpers import fetch, getenv
|
|
9
|
-
|
|
10
|
-
import brainchop as bc
|
|
11
|
-
|
|
12
|
-
CACHEDIR = Path.home() / ".cache" / "brainchop" / "output"
|
|
13
|
-
CACHEDIR.mkdir(parents=True, exist_ok=True)
|
|
14
|
-
|
|
15
|
-
_URLS = {
|
|
16
|
-
"t1_crop": "https://github.com/neuroneural/brainchop-models/raw/main/t1_crop.nii.gz"
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
_MODELS = sorted(bc.list_models().keys())
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def get_output_path(input_path: Path, model: str) -> Path:
|
|
23
|
-
"""Generate deterministic output path based on input and model."""
|
|
24
|
-
key = f"{input_path}_{model}"
|
|
25
|
-
hash_str = hashlib.md5(key.encode()).hexdigest()[:8]
|
|
26
|
-
return CACHEDIR / f"{hash_str}.nii.gz"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def get_mrpeek_cmd(path: Path) -> str:
|
|
30
|
-
return f"mrpeek -batch {path}"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
# List available models
|
|
34
|
-
print("available models:", _MODELS)
|
|
35
|
-
|
|
36
|
-
# Download test files
|
|
37
|
-
test_files = ["t1_crop"]
|
|
38
|
-
paths = [Path(fetch(_URLS[name], name + ".nii.gz")) for name in test_files]
|
|
39
|
-
|
|
40
|
-
# Print mrpeek commands for original files
|
|
41
|
-
print("=" * 80)
|
|
42
|
-
print("mrpeek commands for original files:")
|
|
43
|
-
for path in paths:
|
|
44
|
-
print(get_mrpeek_cmd(path))
|
|
45
|
-
|
|
46
|
-
# Generate output paths
|
|
47
|
-
output_paths = [(path, model, get_output_path(path, model)) for path in paths for model in _MODELS]
|
|
48
|
-
|
|
49
|
-
# Print expected output paths
|
|
50
|
-
print("=" * 80)
|
|
51
|
-
print("output files:")
|
|
52
|
-
for input_path, model, output_path in output_paths:
|
|
53
|
-
print(f" {model}: {output_path}")
|
|
54
|
-
|
|
55
|
-
# Print mrpeek commands for output files
|
|
56
|
-
print("=" * 80)
|
|
57
|
-
print("mrpeek commands for outputs:")
|
|
58
|
-
for _, _, output_path in output_paths:
|
|
59
|
-
print(get_mrpeek_cmd(output_path))
|
|
60
|
-
|
|
61
|
-
if getenv("DRYRUN"):
|
|
62
|
-
print("\nDRYRUN mode - not running inference")
|
|
63
|
-
exit(0)
|
|
64
|
-
|
|
65
|
-
# Run inference using API (no interactive prompts)
|
|
66
|
-
print("=" * 80)
|
|
67
|
-
print("running inference...")
|
|
68
|
-
for input_path, model, output_path in output_paths:
|
|
69
|
-
print(f"\n>>> {model}")
|
|
70
|
-
|
|
71
|
-
try:
|
|
72
|
-
# Load
|
|
73
|
-
vol = bc.load(str(input_path))
|
|
74
|
-
|
|
75
|
-
# Segment (beam=0 means no optimization, no prompts)
|
|
76
|
-
result = bc.segment(vol, model, beam=0)
|
|
77
|
-
|
|
78
|
-
# Save
|
|
79
|
-
bc.save(result, str(output_path))
|
|
80
|
-
print(f" saved: {output_path}")
|
|
81
|
-
except Exception as e:
|
|
82
|
-
print(f" FAILED: {e}")
|
|
83
|
-
|
|
84
|
-
print("=" * 80)
|
|
85
|
-
print("done! run mrpeek commands above to inspect outputs")
|
|
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
|