brainchop 0.2.1__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.1/brainchop.egg-info → brainchop-0.2.3}/PKG-INFO +7 -1
  2. {brainchop-0.2.1 → brainchop-0.2.3}/README.md +6 -0
  3. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/__init__.py +8 -0
  4. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/api.py +136 -27
  5. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/export_model.py +20 -7
  6. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/sae_model.py +32 -5
  7. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/tiny_meshnet.py +64 -17
  8. {brainchop-0.2.1 → brainchop-0.2.3/brainchop.egg-info}/PKG-INFO +7 -1
  9. {brainchop-0.2.1 → brainchop-0.2.3}/pyproject.toml +1 -1
  10. {brainchop-0.2.1 → brainchop-0.2.3}/LICENSE +0 -0
  11. {brainchop-0.2.1 → brainchop-0.2.3}/MANIFEST.in +0 -0
  12. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/cli.py +0 -0
  13. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/convert_tfjs_to_pth.py +0 -0
  14. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/niimath/__init__.py +0 -0
  15. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop/utils.py +0 -0
  16. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop.egg-info/SOURCES.txt +0 -0
  17. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop.egg-info/dependency_links.txt +0 -0
  18. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop.egg-info/entry_points.txt +0 -0
  19. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop.egg-info/requires.txt +0 -0
  20. {brainchop-0.2.1 → brainchop-0.2.3}/brainchop.egg-info/top_level.txt +0 -0
  21. {brainchop-0.2.1 → brainchop-0.2.3}/setup.cfg +0 -0
  22. {brainchop-0.2.1 → brainchop-0.2.3}/tests/test_api.py +0 -0
  23. {brainchop-0.2.1 → brainchop-0.2.3}/tests/test_backend_comparison.py +0 -0
  24. {brainchop-0.2.1 → brainchop-0.2.3}/tests/test_batching.py +0 -0
  25. {brainchop-0.2.1 → 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.1
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
@@ -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"]
@@ -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
  """
@@ -146,7 +157,7 @@ def load(path: str, *, crop: float | None = None, ct: bool = False, comply: bool
146
157
  data, header = conform(os.path.abspath(path), ct=ct, comply=comply)
147
158
  if crop is not None:
148
159
  data, _ = crop_to_cutoff(data, crop)
149
- return Volume(Tensor(data), header)
160
+ return Volume(Tensor(data.copy()), header)
150
161
 
151
162
 
152
163
  def save(volume: Volume, path: str) -> None:
@@ -187,27 +198,62 @@ def _create_flip_matrix(size: int) -> Tensor:
187
198
  class TTAModel:
188
199
  """Test-Time Augmentation wrapper using flip ensemble."""
189
200
 
190
- def __init__(self, model):
201
+ def __init__(self, model, flip_axis: str = "sagittal"):
202
+ """
203
+ Initialize TTA wrapper.
204
+
205
+ Args:
206
+ model: The underlying segmentation model
207
+ flip_axis: Which axis to flip for TTA:
208
+ - "sagittal" (default): flip along D axis (left-right)
209
+ - "coronal": flip along H axis (front-back)
210
+ - "axial": flip along W axis (top-bottom)
211
+ """
191
212
  self._model = model
192
213
  self.n_classes = model.n_classes
193
- # Pre-create flip matrix for depth dimension (256)
214
+ self._flip_axis = flip_axis
215
+ # Pre-create flip matrix for all dimensions (256)
194
216
  self._flip_matrix = _create_flip_matrix(256)
195
217
 
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
218
+ def _flip_sagittal(self, x: Tensor) -> Tensor:
219
+ """Flip tensor along depth/sagittal axis (D, axis 2)."""
220
+ # x: (B, C, D, H, W) - flip along D
200
221
  b, c, d, h, w = x.shape
201
222
  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
223
  x_t = x_reshaped.permute(0, 2, 1) # (B*C, H*W, D)
207
224
  x_flipped_t = x_t @ self._flip_matrix # (B*C, H*W, D)
208
225
  x_flipped = x_flipped_t.permute(0, 2, 1) # (B*C, D, H*W)
209
226
  return x_flipped.reshape(b, c, d, h, w)
210
227
 
228
+ def _flip_coronal(self, x: Tensor) -> Tensor:
229
+ """Flip tensor along height/coronal axis (H, axis 3)."""
230
+ # x: (B, C, D, H, W) - flip along H
231
+ b, c, d, h, w = x.shape
232
+ x_reshaped = x.reshape(b * c * d, h, w) # (B*C*D, H, W)
233
+ x_t = x_reshaped.permute(0, 2, 1) # (B*C*D, W, H)
234
+ x_flipped_t = x_t @ self._flip_matrix # (B*C*D, W, H)
235
+ x_flipped = x_flipped_t.permute(0, 2, 1) # (B*C*D, H, W)
236
+ return x_flipped.reshape(b, c, d, h, w)
237
+
238
+ def _flip_axial(self, x: Tensor) -> Tensor:
239
+ """Flip tensor along width/axial axis (W, axis 4)."""
240
+ # x: (B, C, D, H, W) - flip along W
241
+ b, c, d, h, w = x.shape
242
+ x_reshaped = x.reshape(b * c * d * h, w) # (B*C*D*H, W)
243
+ x_flipped = x_reshaped @ self._flip_matrix # (B*C*D*H, W)
244
+ return x_flipped.reshape(b, c, d, h, w)
245
+
246
+ def _flip(self, x: Tensor) -> Tensor:
247
+ """Flip tensor along the configured axis."""
248
+ if self._flip_axis == "sagittal":
249
+ return self._flip_sagittal(x)
250
+ elif self._flip_axis == "coronal":
251
+ return self._flip_coronal(x)
252
+ elif self._flip_axis == "axial":
253
+ return self._flip_axial(x)
254
+ else:
255
+ raise ValueError(f"Unknown flip axis: {self._flip_axis}")
256
+
211
257
  def _forward_no_argmax(self, x: Tensor) -> Tensor:
212
258
  """Forward pass through conv layers without final argmax."""
213
259
  # Use forward_no_argmax if available (SAENet), otherwise iterate layers (MeshNet)
@@ -228,7 +274,7 @@ class TTAModel:
228
274
  """
229
275
  Forward pass with flip ensemble (test-time augmentation).
230
276
 
231
- Runs inference on both original and depth-flipped inputs,
277
+ Runs inference on both original and flipped inputs,
232
278
  sums the logits, then applies argmax.
233
279
 
234
280
  Args:
@@ -243,19 +289,17 @@ class TTAModel:
243
289
  # Forward on original
244
290
  logits_orig = self._forward_no_argmax(x)
245
291
 
246
- # Flip input on depth axis using permutation matrix
247
- x_flipped = self._flip_depth(x)
292
+ # Flip input, run inference, then unflip output
293
+ x_flipped = self._flip(x)
248
294
  logits_flipped = self._forward_no_argmax(x_flipped)
295
+ logits_unflipped = self._flip(logits_flipped)
249
296
 
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)
297
+ # Sum logits and argmax (logits already computed, use non-fused path)
254
298
  summed = logits_orig + logits_unflipped
255
- return self._model.seq_conv_argmax(summed)
299
+ return self._model.seq_conv_argmax.argmax_only(summed)
256
300
 
257
301
 
258
- def _load_model(model: str, *, tta: bool = False):
302
+ def _load_model(model: str, *, tta: bool = False, flip_axis: str = "sagittal"):
259
303
  """
260
304
  Load model by name or path.
261
305
 
@@ -263,6 +307,7 @@ def _load_model(model: str, *, tta: bool = False):
263
307
  model: Model name (e.g., "subcortical") or path to model directory
264
308
  containing model.json and model.pth/model.bin
265
309
  tta: If True, wrap model with test-time augmentation (flip ensemble)
310
+ flip_axis: Which axis to flip for TTA ("sagittal", "coronal", "axial")
266
311
  """
267
312
  from pathlib import Path
268
313
  from brainchop.utils import find_pth_files, find_sae_files, AVAILABLE_MODELS, unwrap_path
@@ -291,7 +336,7 @@ def _load_model(model: str, *, tta: bool = False):
291
336
  raise FileNotFoundError(f"No model.pth or model.bin found in {model_path}")
292
337
 
293
338
  m = load_meshnet(str(config_fn), str(weights_fn))
294
- return TTAModel(m) if tta else m
339
+ return TTAModel(m, flip_axis=flip_axis) if tta else m
295
340
 
296
341
  # Otherwise treat as model name
297
342
  if model not in AVAILABLE_MODELS:
@@ -305,12 +350,12 @@ def _load_model(model: str, *, tta: bool = False):
305
350
  n_classes = model_info.get("n_classes", 3)
306
351
  permute = os.environ.get("SAE_PERMUTE", "0") == "1"
307
352
  m = load_sae(unwrap_path(model_fn), n_classes=n_classes, permute=permute)
308
- return TTAModel(m) if tta else m
353
+ return TTAModel(m, flip_axis=flip_axis) if tta else m
309
354
 
310
355
  # Default: MeshNet
311
356
  config_fn, model_fn = find_pth_files(model)
312
357
  m = load_meshnet(unwrap_path(config_fn), unwrap_path(model_fn))
313
- return TTAModel(m) if tta else m
358
+ return TTAModel(m, flip_axis=flip_axis) if tta else m
314
359
 
315
360
 
316
361
  def optimize(model: str, *, beam: int = 2, batch_size: int = 1) -> None:
@@ -350,6 +395,30 @@ def optimize(model: str, *, beam: int = 2, batch_size: int = 1) -> None:
350
395
  del os.environ["BEAM"]
351
396
 
352
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
+
353
422
  def segment(
354
423
  volume: Volume | list[Volume],
355
424
  model: str,
@@ -425,7 +494,7 @@ def segment(
425
494
  if hasattr(m, "normalize"):
426
495
  batched = m.normalize(batched)
427
496
 
428
- raw_output = m(batched)
497
+ raw_output = _run_with_fuse_chunk(m, batched, model_name, tta=tta)
429
498
  # TTAModel returns raw logits (B, C, D, H, W), MeshNet returns argmaxed (B, D, H, W)
430
499
  if len(raw_output.shape) == 5:
431
500
  output = raw_output.argmax(axis=1) # (B, C, D, H, W) -> (B, D, H, W)
@@ -460,6 +529,8 @@ def export(
460
529
  target: str = "webgpu",
461
530
  beam: int = 0,
462
531
  tta: bool = False,
532
+ flip_axis: str = "sagittal",
533
+ force: bool = False,
463
534
  ) -> tuple[str, str]:
464
535
  """
465
536
  Export model to WebGPU or other target format.
@@ -470,6 +541,8 @@ def export(
470
541
  target: Export target ("webgpu", "clang", "wasm")
471
542
  beam: BEAM optimization level (0 = no optimization)
472
543
  tta: If True, export with test-time augmentation (flip ensemble)
544
+ flip_axis: Which axis to flip for TTA ("sagittal", "coronal", "axial")
545
+ force: If True, skip memory safety checks
473
546
 
474
547
  Returns:
475
548
  Tuple of (js_path, weights_path)
@@ -483,20 +556,56 @@ def export(
483
556
  # With BEAM optimization
484
557
  >>> js_path, weights_path = export("tissue_fast", "/tmp/export", beam=2)
485
558
 
486
- # With test-time augmentation
559
+ # With test-time augmentation (sagittal flip)
487
560
  >>> js_path, weights_path = export("tissue_fast", "/tmp/export", tta=True)
561
+
562
+ # With coronal TTA
563
+ >>> js_path, weights_path = export("tissue_fast", "/tmp/export", tta=True, flip_axis="coronal")
488
564
  ```
489
565
  """
490
566
  from tinygrad.nn.state import safe_save
491
567
  from brainchop.export_model import export_model
492
568
 
569
+ # Memory safety guard: small chunk limits can cause OOM
570
+ chunk_limit = int(os.environ.get("CHUNK_LIMIT", 0))
571
+ min_safe_chunk = 256 * 1024 * 1024 # 256MB
572
+ if chunk_limit > 0 and chunk_limit < min_safe_chunk and not force:
573
+ chunk_mb = chunk_limit // (1024 * 1024)
574
+ raise RuntimeError(
575
+ f"CHUNK_LIMIT={chunk_mb}MB is too small and may cause OOM. "
576
+ f"Use CHUNK_LIMIT >= 256MB or set force=True to override."
577
+ )
578
+
579
+ # Check available system memory - block if free memory is below threshold
580
+ require_free_gb = int(os.environ.get("REQUIRE_FREE_GB", 0))
581
+ if require_free_gb > 0:
582
+ import subprocess
583
+ result = subprocess.run(
584
+ ["vm_stat"], capture_output=True, text=True
585
+ )
586
+ # Parse free pages from vm_stat output
587
+ for line in result.stdout.split("\n"):
588
+ if "Pages free:" in line:
589
+ free_pages = int(line.split(":")[1].strip().rstrip("."))
590
+ # macOS page size is typically 16KB
591
+ free_gb = (free_pages * 16384) / (1024 ** 3)
592
+ if free_gb < require_free_gb:
593
+ raise RuntimeError(
594
+ f"Only {free_gb:.1f}GB free memory, need {require_free_gb}GB. "
595
+ f"Close other apps or set force=True to override."
596
+ )
597
+ break
598
+
493
599
  output_path = Path(output_dir)
494
600
  output_path.mkdir(parents=True, exist_ok=True)
495
601
 
496
602
  # Get model name for output files
497
603
  model_name = Path(model).name if "/" in model else model
498
604
  if tta:
499
- model_name = f"{model_name}_tta"
605
+ if flip_axis == "sagittal":
606
+ model_name = f"{model_name}_tta"
607
+ else:
608
+ model_name = f"{model_name}_tta_{flip_axis}"
500
609
 
501
610
  original_beam = os.environ.get("BEAM")
502
611
  try:
@@ -504,7 +613,7 @@ def export(
504
613
  os.environ["BEAM"] = str(beam)
505
614
 
506
615
  # Load model
507
- m = _load_model(model, tta=tta)
616
+ m = _load_model(model, tta=tta, flip_axis=flip_axis)
508
617
 
509
618
  # Create dummy input - use randn to prevent JIT from treating as constant
510
619
  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()}
@@ -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,34 +44,80 @@ 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
+ )
54
65
 
55
- def __call__(self, x: Tensor) -> Tensor:
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
92
+
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
 
69
111
 
70
- def chunked_conv(x: Tensor, conv_layer: nn.Conv2d, chunk_limit: int = 2**30) -> Tensor:
112
+ def chunked_conv(x: Tensor, conv_layer: nn.Conv2d, chunk_limit: int | None = None) -> Tensor:
71
113
  """
72
- Workaround for WebGPU matmul bug: when output exceeds 2^30 elements,
114
+ Workaround for WebGPU matmul bug: when output exceeds chunk_limit elements,
73
115
  process output channels in chunks to avoid 32-bit integer overflow.
116
+
117
+ Set CHUNK_LIMIT env var to override the default of 2^30 (~1GB).
74
118
  """
119
+ if chunk_limit is None:
120
+ chunk_limit = int(os.environ.get("CHUNK_LIMIT", 2**30))
75
121
  from functools import reduce
76
122
  spatial = int(reduce(lambda a, b: int(a) * int(b), x.shape[2:], 1))
77
123
  out_channels = int(conv_layer.weight.shape[0])
@@ -207,20 +253,21 @@ class MeshNet:
207
253
  self.seq_conv_argmax: SequentialConvArgmax | None = None
208
254
 
209
255
  def init_seq_conv_argmax(self):
210
- """Initialize SequentialConvArgmax for memory-efficient argmax."""
211
- 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)
212
259
 
213
260
  def normalize(self, x):
214
261
  return qnormalize(x) # TODO: interpret normalization from config file
215
262
 
216
- def __call__(self, x):
217
- 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
218
265
  if isinstance(layer, nn.Conv2d):
219
266
  x = chunked_conv(x, layer)
220
267
  else:
221
268
  x = layer(x)
222
269
  assert self.seq_conv_argmax is not None
223
- return self.seq_conv_argmax(x)
270
+ return self.seq_conv_argmax(x, chunk_size=fuse_chunk)
224
271
 
225
272
  def half(self):
226
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.1
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
@@ -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.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