brainchop 0.2.2__tar.gz → 0.2.3__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.
Files changed (25) hide show
  1. {brainchop-0.2.2/brainchop.egg-info → brainchop-0.2.3}/PKG-INFO +1 -1
  2. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/api.py +38 -3
  3. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/sae_model.py +32 -5
  4. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/tiny_meshnet.py +58 -15
  5. {brainchop-0.2.2 → brainchop-0.2.3/brainchop.egg-info}/PKG-INFO +1 -1
  6. {brainchop-0.2.2 → brainchop-0.2.3}/pyproject.toml +1 -1
  7. {brainchop-0.2.2 → brainchop-0.2.3}/LICENSE +0 -0
  8. {brainchop-0.2.2 → brainchop-0.2.3}/MANIFEST.in +0 -0
  9. {brainchop-0.2.2 → brainchop-0.2.3}/README.md +0 -0
  10. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/__init__.py +0 -0
  11. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/cli.py +0 -0
  12. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/convert_tfjs_to_pth.py +0 -0
  13. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/export_model.py +0 -0
  14. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/niimath/__init__.py +0 -0
  15. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop/utils.py +0 -0
  16. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop.egg-info/SOURCES.txt +0 -0
  17. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop.egg-info/dependency_links.txt +0 -0
  18. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop.egg-info/entry_points.txt +0 -0
  19. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop.egg-info/requires.txt +0 -0
  20. {brainchop-0.2.2 → brainchop-0.2.3}/brainchop.egg-info/top_level.txt +0 -0
  21. {brainchop-0.2.2 → brainchop-0.2.3}/setup.cfg +0 -0
  22. {brainchop-0.2.2 → brainchop-0.2.3}/tests/test_api.py +0 -0
  23. {brainchop-0.2.2 → brainchop-0.2.3}/tests/test_backend_comparison.py +0 -0
  24. {brainchop-0.2.2 → brainchop-0.2.3}/tests/test_batching.py +0 -0
  25. {brainchop-0.2.2 → brainchop-0.2.3}/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.2
3
+ Version: 0.2.3
4
4
  Summary: Portable and lightweight brain segmentation using tinygrad
5
5
  Author-email: Mike Doan <spikedoanz@gmail.com>
6
6
  License: MIT
@@ -83,6 +83,17 @@ def _is_first_run(model_name: str, batch_size: int) -> bool:
83
83
  return not any(e["BS"] == batch_size for e in cache_data["beams"])
84
84
 
85
85
 
86
+ def _save_fuse_chunk(model_name: str, chunk_size: int) -> None:
87
+ """Save FUSE_CHUNK to model cache."""
88
+ cache_dir = _get_cache_dir(model_name)
89
+ cache_dir.mkdir(parents=True, exist_ok=True)
90
+ cache_file = cache_dir / "optimizations.json"
91
+ cache_data = _load_optimization_cache(model_name)
92
+ cache_data["fuse_chunk"] = chunk_size
93
+ with open(cache_file, "w") as f:
94
+ json.dump(cache_data, f, indent=2)
95
+
96
+
86
97
  @dataclass
87
98
  class Volume:
88
99
  """
@@ -283,9 +294,9 @@ class TTAModel:
283
294
  logits_flipped = self._forward_no_argmax(x_flipped)
284
295
  logits_unflipped = self._flip(logits_flipped)
285
296
 
286
- # Sum logits and argmax
297
+ # Sum logits and argmax (logits already computed, use non-fused path)
287
298
  summed = logits_orig + logits_unflipped
288
- return self._model.seq_conv_argmax(summed)
299
+ return self._model.seq_conv_argmax.argmax_only(summed)
289
300
 
290
301
 
291
302
  def _load_model(model: str, *, tta: bool = False, flip_axis: str = "sagittal"):
@@ -384,6 +395,30 @@ def optimize(model: str, *, beam: int = 2, batch_size: int = 1) -> None:
384
395
  del os.environ["BEAM"]
385
396
 
386
397
 
398
+ def _run_with_fuse_chunk(m, batched, model_name: str, tta: bool = False):
399
+ """Run model, auto-probing FUSE_CHUNK on MemoryError. Priority: envvar > cache > auto."""
400
+ if tta:
401
+ return m(batched)
402
+
403
+ n_classes = m.n_classes
404
+ env_val = os.environ.get("FUSE_CHUNK")
405
+ chunk = int(env_val) if env_val is not None else \
406
+ _load_optimization_cache(model_name).get("fuse_chunk") or n_classes
407
+
408
+ while chunk >= 1:
409
+ try:
410
+ result = m(batched, fuse_chunk=chunk)
411
+ if chunk < n_classes and env_val is None:
412
+ print(f"brainchop :: FUSE_CHUNK={chunk} (auto-detected for '{model_name}', set FUSE_CHUNK to override)")
413
+ _save_fuse_chunk(model_name, chunk)
414
+ return result
415
+ except MemoryError:
416
+ if chunk == 1:
417
+ raise
418
+ chunk = max(1, chunk // 2)
419
+ print(f"brainchop :: OOM at FUSE_CHUNK={chunk * 2}, retrying with FUSE_CHUNK={chunk}...")
420
+
421
+
387
422
  def segment(
388
423
  volume: Volume | list[Volume],
389
424
  model: str,
@@ -459,7 +494,7 @@ def segment(
459
494
  if hasattr(m, "normalize"):
460
495
  batched = m.normalize(batched)
461
496
 
462
- raw_output = m(batched)
497
+ raw_output = _run_with_fuse_chunk(m, batched, model_name, tta=tta)
463
498
  # TTAModel returns raw logits (B, C, D, H, W), MeshNet returns argmaxed (B, D, H, W)
464
499
  if len(raw_output.shape) == 5:
465
500
  output = raw_output.argmax(axis=1) # (B, C, D, H, W) -> (B, D, H, W)
@@ -105,7 +105,16 @@ class SAENet:
105
105
 
106
106
  self.layers.append((layer_type, idx, weight, bias))
107
107
 
108
- self.seq_conv_argmax = SequentialConvArgmax(self.n_classes)
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 __call__(self, x: Tensor) -> Tensor:
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.forward_no_argmax(x)
160
- # Memory-efficient argmax
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
- Sequential argmax - trades speed for memory by processing channels iteratively.
48
- ~10-15x slower than native argmax but bounds peak memory.
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, chunk_size: int = 16):
56
+ def __init__(self, out_channels: int, final_conv: nn.Conv2d):
52
57
  self.out_channels = out_channels
53
- self.chunk_size = chunk_size
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
- def __call__(self, x: Tensor) -> Tensor:
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
 
@@ -211,20 +253,21 @@ class MeshNet:
211
253
  self.seq_conv_argmax: SequentialConvArgmax | None = None
212
254
 
213
255
  def init_seq_conv_argmax(self):
214
- """Initialize SequentialConvArgmax for memory-efficient argmax."""
215
- self.seq_conv_argmax = SequentialConvArgmax(self.n_classes)
256
+ """Initialize SequentialConvArgmax with the final conv layer fused in."""
257
+ final_conv = self.model[-1] # last layer is always nn.Conv2d
258
+ self.seq_conv_argmax = SequentialConvArgmax(self.n_classes, final_conv)
216
259
 
217
260
  def normalize(self, x):
218
261
  return qnormalize(x) # TODO: interpret normalization from config file
219
262
 
220
- def __call__(self, x):
221
- for layer in self.model:
263
+ def __call__(self, x, fuse_chunk=None):
264
+ for layer in self.model[:-1]: # all layers except final conv
222
265
  if isinstance(layer, nn.Conv2d):
223
266
  x = chunked_conv(x, layer)
224
267
  else:
225
268
  x = layer(x)
226
269
  assert self.seq_conv_argmax is not None
227
- return self.seq_conv_argmax(x)
270
+ return self.seq_conv_argmax(x, chunk_size=fuse_chunk)
228
271
 
229
272
  def half(self):
230
273
  """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.2
3
+ Version: 0.2.3
4
4
  Summary: Portable and lightweight brain segmentation using tinygrad
5
5
  Author-email: Mike Doan <spikedoanz@gmail.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "brainchop"
7
- version = "0.2.2"
7
+ version = "0.2.3"
8
8
  description = "Portable and lightweight brain segmentation using tinygrad"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes