brainchop 0.2.4__tar.gz → 0.2.5__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.4/brainchop.egg-info → brainchop-0.2.5}/PKG-INFO +1 -1
  2. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/api.py +15 -5
  3. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/sae_model.py +23 -1
  4. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/tiny_meshnet.py +41 -1
  5. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/utils.py +21 -0
  6. {brainchop-0.2.4 → brainchop-0.2.5/brainchop.egg-info}/PKG-INFO +1 -1
  7. {brainchop-0.2.4 → brainchop-0.2.5}/pyproject.toml +1 -1
  8. {brainchop-0.2.4 → brainchop-0.2.5}/LICENSE +0 -0
  9. {brainchop-0.2.4 → brainchop-0.2.5}/MANIFEST.in +0 -0
  10. {brainchop-0.2.4 → brainchop-0.2.5}/README.md +0 -0
  11. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/__init__.py +0 -0
  12. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/cli.py +0 -0
  13. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/convert_tfjs_to_pth.py +0 -0
  14. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/export_model.py +0 -0
  15. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop/niimath/__init__.py +0 -0
  16. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop.egg-info/SOURCES.txt +0 -0
  17. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop.egg-info/dependency_links.txt +0 -0
  18. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop.egg-info/entry_points.txt +0 -0
  19. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop.egg-info/requires.txt +0 -0
  20. {brainchop-0.2.4 → brainchop-0.2.5}/brainchop.egg-info/top_level.txt +0 -0
  21. {brainchop-0.2.4 → brainchop-0.2.5}/setup.cfg +0 -0
  22. {brainchop-0.2.4 → brainchop-0.2.5}/tests/test_api.py +0 -0
  23. {brainchop-0.2.4 → brainchop-0.2.5}/tests/test_backend_comparison.py +0 -0
  24. {brainchop-0.2.4 → brainchop-0.2.5}/tests/test_batching.py +0 -0
  25. {brainchop-0.2.4 → brainchop-0.2.5}/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.4
3
+ Version: 0.2.5
4
4
  Summary: Portable and lightweight brain segmentation using tinygrad
5
5
  Author-email: Mike Doan <spikedoanz@gmail.com>
6
6
  License: MIT
@@ -114,8 +114,11 @@ class Volume:
114
114
  352
115
115
  ```
116
116
  """
117
- data: Tensor # (256, 256, 256) uint8
118
- header: bytes # 352-byte NIfTI header
117
+ data: Tensor # (256, 256, 256) uint8, or the cropped sub-volume when crop is used
118
+ header: bytes # 352-byte NIfTI header (always describes the 256^3 space)
119
+ # Bounding box (x_min,x_max,y_min,y_max,z_min,z_max) when loaded with crop=,
120
+ # so the model output can be padded back to 256^3 before labeling/saving.
121
+ crop_coords: tuple | None = None
119
122
 
120
123
 
121
124
  def list_models() -> dict[str, str]:
@@ -136,9 +139,10 @@ def _load_single(path: str | Path, *, crop: float | None = None, ct: bool = Fals
136
139
  from brainchop.utils import crop_to_cutoff
137
140
 
138
141
  data, header = conform(os.path.abspath(path), ct=ct, comply=comply)
142
+ coords = None
139
143
  if crop is not None:
140
- data, _ = crop_to_cutoff(data, crop)
141
- return Volume(Tensor(data.copy()), header)
144
+ data, coords = crop_to_cutoff(data, crop)
145
+ return Volume(Tensor(data.copy()), header, crop_coords=coords)
142
146
 
143
147
 
144
148
  def load(
@@ -524,7 +528,13 @@ def segment(
524
528
  for j in range(output.shape[0]):
525
529
  out = output[j].permute(2, 1, 0).cast("uint8") # (D,H,W) -> (X,Y,Z)
526
530
  header = shard[j].header
527
- out_np, _ = bwlabel(header, out.numpy())
531
+ out_np = out.numpy()
532
+ # If the input was cropped, pad the label volume back to 256^3 so
533
+ # it matches the header before connected-component labeling/saving.
534
+ if shard[j].crop_coords is not None:
535
+ from brainchop.utils import pad_to_original_size
536
+ out_np = pad_to_original_size(out_np, shard[j].crop_coords)
537
+ out_np, _ = bwlabel(header, out_np)
528
538
  results.append(Volume(Tensor(out_np), header))
529
539
  if return_raw:
530
540
  raw_outputs.append(raw_output[j:j+1])
@@ -7,7 +7,9 @@ This module provides SAENet, an encoder-decoder architecture with:
7
7
  - SiLU activation
8
8
  """
9
9
 
10
- from tinygrad import Tensor
10
+ import os
11
+
12
+ from tinygrad import Tensor, dtypes
11
13
  from tinygrad.nn.state import torch_load
12
14
 
13
15
  from brainchop.tiny_meshnet import qnormalize, SequentialConvArgmax
@@ -86,6 +88,14 @@ class SAENet:
86
88
  """
87
89
  self.layers = []
88
90
  self.n_classes = n_classes
91
+ # fp16: when FP16 is set, store weights as f16 and (in the forward pass)
92
+ # keep activations f16 too. The conv/conv_transpose accumulators still run
93
+ # in f32 (tinygrad sum_acc_dtype: half -> float), so this is the same
94
+ # overflow-safe mixed precision as MeshNet -- see the comment in
95
+ # brainchop/tiny_meshnet.py MeshNet.__call__ for the full rationale. Without
96
+ # it, an "fp16" export keeps activations in f32 and runs no faster (often
97
+ # slower) than fp32 on GPUs without 2:1 f16 throughput.
98
+ self.fp16 = bool(os.environ.get("FP16"))
89
99
 
90
100
  for idx in LAYER_INDICES:
91
101
  # Move weights from DISK to compute device via numpy roundtrip
@@ -103,6 +113,10 @@ class SAENet:
103
113
  if permute:
104
114
  weight = _permute_weights(weight, is_conv_transpose=(layer_type == "convT"))
105
115
 
116
+ if self.fp16:
117
+ weight = weight.cast(dtypes.float16).realize()
118
+ bias = bias.cast(dtypes.float16).realize()
119
+
106
120
  self.layers.append((layer_type, idx, weight, bias))
107
121
 
108
122
  # Build a dummy nn.Conv2d to hold the final layer's weights for fused argmax
@@ -147,6 +161,10 @@ class SAENet:
147
161
  if layer_type != "convT":
148
162
  x = x.silu()
149
163
 
164
+ # Keep the materialized activation in f16 (accumulators stayed f32).
165
+ if self.fp16:
166
+ x = x.cast(dtypes.float16)
167
+
150
168
  # Final layer: 1x1x1 conv, no activation, no padding
151
169
  _, idx, weight, bias = self.layers[-1]
152
170
  kernel_size = weight.shape[2]
@@ -171,6 +189,10 @@ class SAENet:
171
189
  if layer_type != "convT":
172
190
  x = x.silu()
173
191
 
192
+ # Keep the materialized activation in f16 (accumulators stayed f32).
193
+ if self.fp16:
194
+ x = x.cast(dtypes.float16)
195
+
174
196
  return x
175
197
 
176
198
  def __call__(self, x: Tensor, fuse_chunk=None) -> Tensor:
@@ -1,6 +1,6 @@
1
1
  import os
2
2
  from tinygrad.tensor import Tensor
3
- from tinygrad import nn
3
+ from tinygrad import nn, dtypes
4
4
  from tinygrad.nn.state import torch_load, safe_load, load_state_dict
5
5
  import json
6
6
  import numpy as np
@@ -70,6 +70,18 @@ class SequentialConvArgmax:
70
70
 
71
71
  def _chunked_argmax(self, x: Tensor, chunk_size: int) -> Tensor:
72
72
  """Conv + argmax in chunks of chunk_size channels."""
73
+ # Realize the backbone output ONCE before chunking. x is the (lazy)
74
+ # output of the full conv stack; each chunk below reads it to compute a
75
+ # slice of the final 1x1 classifier conv. In eager CLI execution the
76
+ # first chunk's .realize() already materializes x and later chunks reuse
77
+ # it, but export_model() captures x as a lazy graph -- without this
78
+ # boundary every chunk branch re-traces the entire backbone, so the
79
+ # exported WebGPU/WebGL runner recomputes the whole network once per
80
+ # chunk (e.g. 104 classes / chunk 24 = 5x the conv passes, 5x inference
81
+ # and 5x BEAM/export time). Forcing one realization keeps peak memory
82
+ # identical (one backbone activation + one chunk) while computing the
83
+ # backbone exactly once.
84
+ x = x.realize()
73
85
  # First chunk
74
86
  end = min(chunk_size, self.out_channels)
75
87
  logits = self._conv_channels(x, 0, end).realize()
@@ -269,11 +281,39 @@ class MeshNet:
269
281
  return qnormalize(x) # TODO: interpret normalization from config file
270
282
 
271
283
  def __call__(self, x, fuse_chunk=None):
284
+ # True fp16 activations. When the model is half precision, cast each
285
+ # layer's OUTPUT back to f16 so the materialized activation buffers are
286
+ # f16 (24*256^3 = 0.8 GiB) instead of f32 (1.6 GiB). The cast folds into
287
+ # the producing kernel's store (no extra pass), halving the dominant
288
+ # (bandwidth-bound) GroupNorm traffic -> the intended ~2x speedup on GPUs
289
+ # without 2:1 f16 throughput (e.g. Apple Silicon).
290
+ #
291
+ # CRITICAL fp16 correctness fix: GroupNorm computes variance by SQUARING
292
+ # its input elementwise. tinygrad upcasts the reduction *accumulator* to
293
+ # f32 (sum_acc_dtype: half -> float), but the per-element square is done in
294
+ # the input dtype FIRST -- so with an f16 input, any conv output > ~256
295
+ # overflows (256^2 > 65504) to +inf before the f32 accumulator ever sees
296
+ # it, poisoning the per-channel variance and producing garbage output.
297
+ # High-capacity models reach far past this: the 24ch synth DK-atlas hits
298
+ # ~940 at layer 1 (-> 72k inf voxels); the shipped 24ch model peaks ~375
299
+ # (only ~97 inf) which is why it merely "mostly" worked. We keep the square
300
+ # safe one of two ways (see export_meshnet_webgpu.py --fp16-norm):
301
+ # * default: upcast the GroupNorm input to f32 -> safe for ANY weights, but
302
+ # the reduction runs in f32 (~1.5-2x slower on 2:1 f16:f32 GPUs, e.g. Apple).
303
+ # * MESHNET_FAST_F16_GN=1: GroupNorm fully in f16 (fast); ONLY safe when conv
304
+ # weights were rescaled so conv outputs stay < ~256 (lossless, via the
305
+ # export's rescaling pass exploiting GroupNorm scale-invariance).
306
+ fp16 = isinstance(self.model[0], nn.Conv2d) and self.model[0].weight.dtype == dtypes.float16
307
+ fast_f16_gn = os.environ.get("MESHNET_FAST_F16_GN") == "1"
272
308
  for layer in self.model[:-1]: # all layers except final conv
273
309
  if isinstance(layer, nn.Conv2d):
274
310
  x = chunked_conv(x, layer)
275
311
  else:
312
+ if fp16 and not fast_f16_gn and isinstance(layer, nn.GroupNorm):
313
+ x = x.cast(dtypes.float32) # f32 variance: avoid f16 square overflow
276
314
  x = layer(x)
315
+ if fp16:
316
+ x = x.cast(dtypes.float16)
277
317
  assert self.seq_conv_argmax is not None
278
318
  return self.seq_conv_argmax(x, chunk_size=fuse_chunk)
279
319
 
@@ -129,3 +129,24 @@ def crop_to_cutoff(arr: np.ndarray, cutoff_percent: float = 2.0):
129
129
 
130
130
  cropped_arr = arr[x_min : x_max + 1, y_min : y_max + 1, z_min : z_max + 1]
131
131
  return cropped_arr, (x_min, x_max, y_min, y_max, z_min, z_max)
132
+
133
+
134
+ def pad_to_original_size(
135
+ cropped_arr: np.ndarray, coords: tuple, original_shape: tuple = (256, 256, 256)
136
+ ):
137
+ """Inverse of crop_to_cutoff: place a cropped volume back into a zero-filled
138
+ original_shape volume at its bounding-box coordinates. Needed so the label
139
+ output and the (256^3) NIfTI header agree before bwlabel/save."""
140
+ x_min, x_max, y_min, y_max, z_min, z_max = coords
141
+
142
+ padded_arr = np.zeros(original_shape, dtype=cropped_arr.dtype)
143
+ if cropped_arr.size == 0:
144
+ return padded_arr
145
+
146
+ x_size = x_max - x_min + 1
147
+ y_size = y_max - y_min + 1
148
+ z_size = z_max - z_min + 1
149
+ if x_size > 0 and y_size > 0 and z_size > 0:
150
+ padded_arr[x_min : x_max + 1, y_min : y_max + 1, z_min : z_max + 1] = cropped_arr
151
+
152
+ return padded_arr
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brainchop
3
- Version: 0.2.4
3
+ Version: 0.2.5
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.4"
7
+ version = "0.2.5"
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