brainchop 0.2__tar.gz → 0.2.1__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.1}/LICENSE +1 -1
- {brainchop-0.2/brainchop.egg-info → brainchop-0.2.1}/PKG-INFO +1 -1
- {brainchop-0.2 → brainchop-0.2.1}/brainchop/api.py +121 -11
- brainchop-0.2.1/brainchop/sae_model.py +173 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop/utils.py +15 -0
- {brainchop-0.2 → brainchop-0.2.1/brainchop.egg-info}/PKG-INFO +1 -1
- {brainchop-0.2 → brainchop-0.2.1}/brainchop.egg-info/SOURCES.txt +2 -3
- {brainchop-0.2 → brainchop-0.2.1}/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.1}/MANIFEST.in +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/README.md +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop/__init__.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop/cli.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop/convert_tfjs_to_pth.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop/export_model.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop/niimath/__init__.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop/tiny_meshnet.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop.egg-info/dependency_links.txt +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop.egg-info/entry_points.txt +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop.egg-info/requires.txt +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/brainchop.egg-info/top_level.txt +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/setup.cfg +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/tests/test_api.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/tests/test_backend_comparison.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/tests/test_batching.py +0 -0
- {brainchop-0.2 → brainchop-0.2.1}/tests/test_sequential_argmax.py +0 -0
|
@@ -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
|
# =============================================================================
|
|
@@ -172,16 +174,98 @@ 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):
|
|
191
|
+
self._model = model
|
|
192
|
+
self.n_classes = model.n_classes
|
|
193
|
+
# Pre-create flip matrix for depth dimension (256)
|
|
194
|
+
self._flip_matrix = _create_flip_matrix(256)
|
|
195
|
+
|
|
196
|
+
def _flip_depth(self, x: Tensor) -> Tensor:
|
|
197
|
+
"""Flip tensor along depth axis using matrix multiplication."""
|
|
198
|
+
# x: (B, C, D, H, W) - flip along D (axis 2)
|
|
199
|
+
# Reshape to (B*C, D, H*W), apply permutation, reshape back
|
|
200
|
+
b, c, d, h, w = x.shape
|
|
201
|
+
x_reshaped = x.reshape(b * c, d, h * w) # (B*C, D, H*W)
|
|
202
|
+
# Permute depth: (B*C, D, H*W) @ (D, D) -> need to transpose for matmul
|
|
203
|
+
# x_reshaped is (B*C, D, H*W), we want to permute the D dimension
|
|
204
|
+
# So we do: P @ x_reshaped along the D axis
|
|
205
|
+
# Reshape to (B*C, H*W, D) for matmul, then back
|
|
206
|
+
x_t = x_reshaped.permute(0, 2, 1) # (B*C, H*W, D)
|
|
207
|
+
x_flipped_t = x_t @ self._flip_matrix # (B*C, H*W, D)
|
|
208
|
+
x_flipped = x_flipped_t.permute(0, 2, 1) # (B*C, D, H*W)
|
|
209
|
+
return x_flipped.reshape(b, c, d, h, w)
|
|
210
|
+
|
|
211
|
+
def _forward_no_argmax(self, x: Tensor) -> Tensor:
|
|
212
|
+
"""Forward pass through conv layers without final argmax."""
|
|
213
|
+
# Use forward_no_argmax if available (SAENet), otherwise iterate layers (MeshNet)
|
|
214
|
+
if hasattr(self._model, 'forward_no_argmax'):
|
|
215
|
+
return self._model.forward_no_argmax(x)
|
|
216
|
+
for layer in self._model.model:
|
|
217
|
+
if isinstance(layer, nn.Conv2d):
|
|
218
|
+
x = chunked_conv(x, layer)
|
|
219
|
+
else:
|
|
220
|
+
x = layer(x)
|
|
221
|
+
return x
|
|
222
|
+
|
|
223
|
+
def normalize(self, x: Tensor) -> Tensor:
|
|
224
|
+
"""Delegate normalization to underlying model."""
|
|
225
|
+
return self._model.normalize(x)
|
|
226
|
+
|
|
227
|
+
def __call__(self, x: Tensor) -> Tensor:
|
|
228
|
+
"""
|
|
229
|
+
Forward pass with flip ensemble (test-time augmentation).
|
|
230
|
+
|
|
231
|
+
Runs inference on both original and depth-flipped inputs,
|
|
232
|
+
sums the logits, then applies argmax.
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
x: Input tensor (B, 1, D, H, W)
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
Segmentation (B, D, H, W) after argmax
|
|
239
|
+
"""
|
|
240
|
+
# Force input into computation graph - add zero to create explicit dependency
|
|
241
|
+
x = x + Tensor.zeros(1)
|
|
242
|
+
|
|
243
|
+
# Forward on original
|
|
244
|
+
logits_orig = self._forward_no_argmax(x)
|
|
245
|
+
|
|
246
|
+
# Flip input on depth axis using permutation matrix
|
|
247
|
+
x_flipped = self._flip_depth(x)
|
|
248
|
+
logits_flipped = self._forward_no_argmax(x_flipped)
|
|
249
|
+
|
|
250
|
+
# Unflip the flipped output on depth axis
|
|
251
|
+
logits_unflipped = self._flip_depth(logits_flipped)
|
|
252
|
+
|
|
253
|
+
# Sum logits and argmax (use model's seq_conv_argmax for WebGPU compatibility)
|
|
254
|
+
summed = logits_orig + logits_unflipped
|
|
255
|
+
return self._model.seq_conv_argmax(summed)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _load_model(model: str, *, tta: bool = False):
|
|
176
259
|
"""
|
|
177
260
|
Load model by name or path.
|
|
178
261
|
|
|
179
262
|
Args:
|
|
180
263
|
model: Model name (e.g., "subcortical") or path to model directory
|
|
181
264
|
containing model.json and model.pth/model.bin
|
|
265
|
+
tta: If True, wrap model with test-time augmentation (flip ensemble)
|
|
182
266
|
"""
|
|
183
267
|
from pathlib import Path
|
|
184
|
-
from brainchop.utils import find_pth_files, AVAILABLE_MODELS, unwrap_path
|
|
268
|
+
from brainchop.utils import find_pth_files, find_sae_files, AVAILABLE_MODELS, unwrap_path
|
|
185
269
|
|
|
186
270
|
# Check if it's a path (absolute, relative, or file://)
|
|
187
271
|
if model.startswith("file://"):
|
|
@@ -206,14 +290,27 @@ def _load_model(model: str):
|
|
|
206
290
|
else:
|
|
207
291
|
raise FileNotFoundError(f"No model.pth or model.bin found in {model_path}")
|
|
208
292
|
|
|
209
|
-
|
|
293
|
+
m = load_meshnet(str(config_fn), str(weights_fn))
|
|
294
|
+
return TTAModel(m) if tta else m
|
|
210
295
|
|
|
211
296
|
# Otherwise treat as model name
|
|
212
297
|
if model not in AVAILABLE_MODELS:
|
|
213
298
|
raise ValueError(f"Unknown model: {model}. Available: {list(AVAILABLE_MODELS.keys())}")
|
|
214
299
|
|
|
300
|
+
model_info = AVAILABLE_MODELS[model]
|
|
301
|
+
|
|
302
|
+
# Check model type - SAE or MeshNet
|
|
303
|
+
if model_info.get("type") == "sae":
|
|
304
|
+
model_fn = find_sae_files(model)
|
|
305
|
+
n_classes = model_info.get("n_classes", 3)
|
|
306
|
+
permute = os.environ.get("SAE_PERMUTE", "0") == "1"
|
|
307
|
+
m = load_sae(unwrap_path(model_fn), n_classes=n_classes, permute=permute)
|
|
308
|
+
return TTAModel(m) if tta else m
|
|
309
|
+
|
|
310
|
+
# Default: MeshNet
|
|
215
311
|
config_fn, model_fn = find_pth_files(model)
|
|
216
|
-
|
|
312
|
+
m = load_meshnet(unwrap_path(config_fn), unwrap_path(model_fn))
|
|
313
|
+
return TTAModel(m) if tta else m
|
|
217
314
|
|
|
218
315
|
|
|
219
316
|
def optimize(model: str, *, beam: int = 2, batch_size: int = 1) -> None:
|
|
@@ -260,6 +357,7 @@ def segment(
|
|
|
260
357
|
shard_size: int = 1,
|
|
261
358
|
beam: int = 0,
|
|
262
359
|
return_raw: bool = False,
|
|
360
|
+
tta: bool = False,
|
|
263
361
|
): # type: ignore[return]
|
|
264
362
|
"""
|
|
265
363
|
Segment brain volume(s).
|
|
@@ -270,6 +368,7 @@ def segment(
|
|
|
270
368
|
shard_size: Batch size for processing multiple volumes
|
|
271
369
|
beam: BEAM optimization level (0 = use cached or none)
|
|
272
370
|
return_raw: If True, also return raw model output (pre-argmax) for export_classes
|
|
371
|
+
tta: If True, use test-time augmentation (flip ensemble)
|
|
273
372
|
|
|
274
373
|
Returns:
|
|
275
374
|
Segmented Volume(s) - single if input was single, list if input was list
|
|
@@ -312,7 +411,7 @@ def segment(
|
|
|
312
411
|
if beam > 0:
|
|
313
412
|
os.environ["BEAM"] = str(beam)
|
|
314
413
|
|
|
315
|
-
m = _load_model(model)
|
|
414
|
+
m = _load_model(model, tta=tta)
|
|
316
415
|
results: list[Volume] = []
|
|
317
416
|
raw_outputs: list[Tensor] = []
|
|
318
417
|
|
|
@@ -326,8 +425,12 @@ def segment(
|
|
|
326
425
|
if hasattr(m, "normalize"):
|
|
327
426
|
batched = m.normalize(batched)
|
|
328
427
|
|
|
329
|
-
raw_output = m(batched)
|
|
330
|
-
|
|
428
|
+
raw_output = m(batched)
|
|
429
|
+
# TTAModel returns raw logits (B, C, D, H, W), MeshNet returns argmaxed (B, D, H, W)
|
|
430
|
+
if len(raw_output.shape) == 5:
|
|
431
|
+
output = raw_output.argmax(axis=1) # (B, C, D, H, W) -> (B, D, H, W)
|
|
432
|
+
else:
|
|
433
|
+
output = raw_output # Already (B, D, H, W)
|
|
331
434
|
|
|
332
435
|
# Split batch and convert back to (X,Y,Z)
|
|
333
436
|
for j in range(output.shape[0]):
|
|
@@ -356,6 +459,7 @@ def export(
|
|
|
356
459
|
*,
|
|
357
460
|
target: str = "webgpu",
|
|
358
461
|
beam: int = 0,
|
|
462
|
+
tta: bool = False,
|
|
359
463
|
) -> tuple[str, str]:
|
|
360
464
|
"""
|
|
361
465
|
Export model to WebGPU or other target format.
|
|
@@ -365,6 +469,7 @@ def export(
|
|
|
365
469
|
output_dir: Directory to save exported files
|
|
366
470
|
target: Export target ("webgpu", "clang", "wasm")
|
|
367
471
|
beam: BEAM optimization level (0 = no optimization)
|
|
472
|
+
tta: If True, export with test-time augmentation (flip ensemble)
|
|
368
473
|
|
|
369
474
|
Returns:
|
|
370
475
|
Tuple of (js_path, weights_path)
|
|
@@ -377,6 +482,9 @@ def export(
|
|
|
377
482
|
|
|
378
483
|
# With BEAM optimization
|
|
379
484
|
>>> js_path, weights_path = export("tissue_fast", "/tmp/export", beam=2)
|
|
485
|
+
|
|
486
|
+
# With test-time augmentation
|
|
487
|
+
>>> js_path, weights_path = export("tissue_fast", "/tmp/export", tta=True)
|
|
380
488
|
```
|
|
381
489
|
"""
|
|
382
490
|
from tinygrad.nn.state import safe_save
|
|
@@ -387,6 +495,8 @@ def export(
|
|
|
387
495
|
|
|
388
496
|
# Get model name for output files
|
|
389
497
|
model_name = Path(model).name if "/" in model else model
|
|
498
|
+
if tta:
|
|
499
|
+
model_name = f"{model_name}_tta"
|
|
390
500
|
|
|
391
501
|
original_beam = os.environ.get("BEAM")
|
|
392
502
|
try:
|
|
@@ -394,10 +504,10 @@ def export(
|
|
|
394
504
|
os.environ["BEAM"] = str(beam)
|
|
395
505
|
|
|
396
506
|
# Load model
|
|
397
|
-
m = _load_model(model)
|
|
507
|
+
m = _load_model(model, tta=tta)
|
|
398
508
|
|
|
399
|
-
# Create dummy input
|
|
400
|
-
dummy_input = Tensor.
|
|
509
|
+
# Create dummy input - use randn to prevent JIT from treating as constant
|
|
510
|
+
dummy_input = Tensor.randn(1, 1, 256, 256, 256, dtype="float32")
|
|
401
511
|
|
|
402
512
|
# Export
|
|
403
513
|
prg, _input_sizes, _output_sizes, state = export_model(
|
|
@@ -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)
|
|
@@ -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:
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|