brainchop 0.2.1__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.
Files changed (25) hide show
  1. {brainchop-0.2.1/brainchop.egg-info → brainchop-0.2.2}/PKG-INFO +7 -1
  2. {brainchop-0.2.1 → brainchop-0.2.2}/README.md +6 -0
  3. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/__init__.py +8 -0
  4. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/api.py +99 -25
  5. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/export_model.py +20 -7
  6. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/tiny_meshnet.py +6 -2
  7. {brainchop-0.2.1 → brainchop-0.2.2/brainchop.egg-info}/PKG-INFO +7 -1
  8. {brainchop-0.2.1 → brainchop-0.2.2}/pyproject.toml +1 -1
  9. {brainchop-0.2.1 → brainchop-0.2.2}/LICENSE +0 -0
  10. {brainchop-0.2.1 → brainchop-0.2.2}/MANIFEST.in +0 -0
  11. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/cli.py +0 -0
  12. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/convert_tfjs_to_pth.py +0 -0
  13. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/niimath/__init__.py +0 -0
  14. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/sae_model.py +0 -0
  15. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop/utils.py +0 -0
  16. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop.egg-info/SOURCES.txt +0 -0
  17. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop.egg-info/dependency_links.txt +0 -0
  18. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop.egg-info/entry_points.txt +0 -0
  19. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop.egg-info/requires.txt +0 -0
  20. {brainchop-0.2.1 → brainchop-0.2.2}/brainchop.egg-info/top_level.txt +0 -0
  21. {brainchop-0.2.1 → brainchop-0.2.2}/setup.cfg +0 -0
  22. {brainchop-0.2.1 → brainchop-0.2.2}/tests/test_api.py +0 -0
  23. {brainchop-0.2.1 → brainchop-0.2.2}/tests/test_backend_comparison.py +0 -0
  24. {brainchop-0.2.1 → brainchop-0.2.2}/tests/test_batching.py +0 -0
  25. {brainchop-0.2.1 → 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.1
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"]
@@ -146,7 +146,7 @@ def load(path: str, *, crop: float | None = None, ct: bool = False, comply: bool
146
146
  data, header = conform(os.path.abspath(path), ct=ct, comply=comply)
147
147
  if crop is not None:
148
148
  data, _ = crop_to_cutoff(data, crop)
149
- return Volume(Tensor(data), header)
149
+ return Volume(Tensor(data.copy()), header)
150
150
 
151
151
 
152
152
  def save(volume: Volume, path: str) -> None:
@@ -187,27 +187,62 @@ def _create_flip_matrix(size: int) -> Tensor:
187
187
  class TTAModel:
188
188
  """Test-Time Augmentation wrapper using flip ensemble."""
189
189
 
190
- def __init__(self, model):
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
+ """
191
201
  self._model = model
192
202
  self.n_classes = model.n_classes
193
- # Pre-create flip matrix for depth dimension (256)
203
+ self._flip_axis = flip_axis
204
+ # Pre-create flip matrix for all dimensions (256)
194
205
  self._flip_matrix = _create_flip_matrix(256)
195
206
 
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
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
200
210
  b, c, d, h, w = x.shape
201
211
  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
212
  x_t = x_reshaped.permute(0, 2, 1) # (B*C, H*W, D)
207
213
  x_flipped_t = x_t @ self._flip_matrix # (B*C, H*W, D)
208
214
  x_flipped = x_flipped_t.permute(0, 2, 1) # (B*C, D, H*W)
209
215
  return x_flipped.reshape(b, c, d, h, w)
210
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
+
211
246
  def _forward_no_argmax(self, x: Tensor) -> Tensor:
212
247
  """Forward pass through conv layers without final argmax."""
213
248
  # Use forward_no_argmax if available (SAENet), otherwise iterate layers (MeshNet)
@@ -228,7 +263,7 @@ class TTAModel:
228
263
  """
229
264
  Forward pass with flip ensemble (test-time augmentation).
230
265
 
231
- Runs inference on both original and depth-flipped inputs,
266
+ Runs inference on both original and flipped inputs,
232
267
  sums the logits, then applies argmax.
233
268
 
234
269
  Args:
@@ -243,19 +278,17 @@ class TTAModel:
243
278
  # Forward on original
244
279
  logits_orig = self._forward_no_argmax(x)
245
280
 
246
- # Flip input on depth axis using permutation matrix
247
- x_flipped = self._flip_depth(x)
281
+ # Flip input, run inference, then unflip output
282
+ x_flipped = self._flip(x)
248
283
  logits_flipped = self._forward_no_argmax(x_flipped)
284
+ logits_unflipped = self._flip(logits_flipped)
249
285
 
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)
286
+ # Sum logits and argmax
254
287
  summed = logits_orig + logits_unflipped
255
288
  return self._model.seq_conv_argmax(summed)
256
289
 
257
290
 
258
- def _load_model(model: str, *, tta: bool = False):
291
+ def _load_model(model: str, *, tta: bool = False, flip_axis: str = "sagittal"):
259
292
  """
260
293
  Load model by name or path.
261
294
 
@@ -263,6 +296,7 @@ def _load_model(model: str, *, tta: bool = False):
263
296
  model: Model name (e.g., "subcortical") or path to model directory
264
297
  containing model.json and model.pth/model.bin
265
298
  tta: If True, wrap model with test-time augmentation (flip ensemble)
299
+ flip_axis: Which axis to flip for TTA ("sagittal", "coronal", "axial")
266
300
  """
267
301
  from pathlib import Path
268
302
  from brainchop.utils import find_pth_files, find_sae_files, AVAILABLE_MODELS, unwrap_path
@@ -291,7 +325,7 @@ def _load_model(model: str, *, tta: bool = False):
291
325
  raise FileNotFoundError(f"No model.pth or model.bin found in {model_path}")
292
326
 
293
327
  m = load_meshnet(str(config_fn), str(weights_fn))
294
- return TTAModel(m) if tta else m
328
+ return TTAModel(m, flip_axis=flip_axis) if tta else m
295
329
 
296
330
  # Otherwise treat as model name
297
331
  if model not in AVAILABLE_MODELS:
@@ -305,12 +339,12 @@ def _load_model(model: str, *, tta: bool = False):
305
339
  n_classes = model_info.get("n_classes", 3)
306
340
  permute = os.environ.get("SAE_PERMUTE", "0") == "1"
307
341
  m = load_sae(unwrap_path(model_fn), n_classes=n_classes, permute=permute)
308
- return TTAModel(m) if tta else m
342
+ return TTAModel(m, flip_axis=flip_axis) if tta else m
309
343
 
310
344
  # Default: MeshNet
311
345
  config_fn, model_fn = find_pth_files(model)
312
346
  m = load_meshnet(unwrap_path(config_fn), unwrap_path(model_fn))
313
- return TTAModel(m) if tta else m
347
+ return TTAModel(m, flip_axis=flip_axis) if tta else m
314
348
 
315
349
 
316
350
  def optimize(model: str, *, beam: int = 2, batch_size: int = 1) -> None:
@@ -460,6 +494,8 @@ def export(
460
494
  target: str = "webgpu",
461
495
  beam: int = 0,
462
496
  tta: bool = False,
497
+ flip_axis: str = "sagittal",
498
+ force: bool = False,
463
499
  ) -> tuple[str, str]:
464
500
  """
465
501
  Export model to WebGPU or other target format.
@@ -470,6 +506,8 @@ def export(
470
506
  target: Export target ("webgpu", "clang", "wasm")
471
507
  beam: BEAM optimization level (0 = no optimization)
472
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
473
511
 
474
512
  Returns:
475
513
  Tuple of (js_path, weights_path)
@@ -483,20 +521,56 @@ def export(
483
521
  # With BEAM optimization
484
522
  >>> js_path, weights_path = export("tissue_fast", "/tmp/export", beam=2)
485
523
 
486
- # With test-time augmentation
524
+ # With test-time augmentation (sagittal flip)
487
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")
488
529
  ```
489
530
  """
490
531
  from tinygrad.nn.state import safe_save
491
532
  from brainchop.export_model import export_model
492
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
+
493
564
  output_path = Path(output_dir)
494
565
  output_path.mkdir(parents=True, exist_ok=True)
495
566
 
496
567
  # Get model name for output files
497
568
  model_name = Path(model).name if "/" in model else model
498
569
  if tta:
499
- model_name = f"{model_name}_tta"
570
+ if flip_axis == "sagittal":
571
+ model_name = f"{model_name}_tta"
572
+ else:
573
+ model_name = f"{model_name}_tta_{flip_axis}"
500
574
 
501
575
  original_beam = os.environ.get("BEAM")
502
576
  try:
@@ -504,7 +578,7 @@ def export(
504
578
  os.environ["BEAM"] = str(beam)
505
579
 
506
580
  # Load model
507
- m = _load_model(model, tta=tta)
581
+ m = _load_model(model, tta=tta, flip_axis=flip_axis)
508
582
 
509
583
  # Create dummy input - use randn to prevent JIT from treating as constant
510
584
  dummy_input = Tensor.randn(1, 1, 256, 256, 256, dtype="float32")
@@ -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
- 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) ])
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
- const commandEncoder = device.createCommandEncoder();
241
+ let commandEncoder = device.createCommandEncoder();
227
242
  {input_writers}
228
243
  {kernel_calls}
229
244
  {outbuf_copies}
230
- const gpuCommands = commandEncoder.finish();
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
- # NOTE: CPU_COUNT=1, since export does not support threading
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()}
@@ -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 = 2**30) -> Tensor:
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 2^30 elements,
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])
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brainchop
3
- Version: 0.2.1
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "brainchop"
7
- version = "0.2.1"
7
+ version = "0.2.2"
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