Repository navigation
Expand file tree
/
Copy pathunet3d_clean.py
More file actions
710 lines (569 loc) · 25.4 KB
/
Copy pathunet3d_clean.py
File metadata and controls
710 lines (569 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# unet3d.py
"""
3D U-Net implementation for image deconvolution using JAX and Equinox.
This module implements a 3D U-Net architecture for volumetric image restoration,
specifically designed for deconvolution tasks. It includes custom loss functions
(MAE + SSIM), training routines, and utility functions.
"""
import os
import jax
import jax.numpy as jnp
import equinox as eqx
import optax
import tifffile
import numpy as np
from utils import plot_loss, data_loader, log_to_file, plot_loss, log_to_file, visualize_3d_slices_save
from tqdm import tqdm
from jax import lax
# Configure JAX to use 32-bit precision for better performance
jax.config.update("jax_enable_x64", False)
# =============================================================================
# LOSS FUNCTIONS
# =============================================================================
def mse_loss(pred, target):
"""
Mean Squared Error loss for comparing predicted and target volumes.
"""
return jnp.mean((pred - target) ** 2)
def mean_absolute_error(pred, target):
"""
Mean Absolute Error (L1 loss) between predicted and target volumes.
"""
return jnp.mean(jnp.abs(pred - target))
def gaussian_kernel1d(sigma, size):
"""
Generate a 1D Gaussian kernel for smoothing operations.
"""
radius = size // 2
x = jnp.arange(-radius, radius + 1)
kernel = jnp.exp(-0.5 * (x / sigma) ** 2)
kernel /= jnp.sum(kernel) # Normalize to sum to 1
return kernel
def gaussian_blur_3d(x, sigma=1.5, size=None):
"""
Apply 3D Gaussian blur using separable convolutions.
Performs efficient 3D Gaussian filtering by applying 1D convolutions
sequentially along each spatial dimension (depth, height, width).
Args:
x: Input 5D tensor with shape (N, C, D, H, W)
sigma: Standard deviation of Gaussian kernel
size: Kernel size (auto-computed if None)
Returns:
Blurred 5D tensor with same shape as input
"""
if size is None:
size = int(2 * np.ceil(3 * float(sigma)) + 1)
kernel = gaussian_kernel1d(sigma, size)
# Reshape kernel for each spatial dimension
kx = kernel.reshape(1, 1, 1, 1, -1) # Width dimension
ky = kernel.reshape(1, 1, 1, -1, 1) # Height dimension
kz = kernel.reshape(1, 1, -1, 1, 1) # Depth dimension
# Apply separable convolutions along D, H, W axes
x = lax.conv_general_dilated(x, kz, (1, 1, 1), 'SAME', dimension_numbers=('NCDHW', 'OIDHW', 'NCDHW'))
x = lax.conv_general_dilated(x, ky, (1, 1, 1), 'SAME', dimension_numbers=('NCDHW', 'OIDHW', 'NCDHW'))
x = lax.conv_general_dilated(x, kx, (1, 1, 1), 'SAME', dimension_numbers=('NCDHW', 'OIDHW', 'NCDHW'))
return x
def ssim_loss(pred, target, data_range=1.0, k1=0.01, k2=0.03, sigma=1.3):
"""
Compute differentiable SSIM (Structural Similarity Index) loss.
SSIM measures structural similarity between images by comparing
local patterns of pixel intensities. Lower sigma = more edge sensitivity.
Args:
pred: Predicted volume
target: Ground truth volume
data_range: Range of the data (usually 1.0 for normalized data)
k1, k2: SSIM algorithm parameters for numerical stability
sigma: Gaussian blur sigma for local statistics computation
Returns:
SSIM loss (1 - SSIM) where 0 is perfect similarity
"""
# Constants to avoid division by zero
C1 = (k1 * data_range) ** 2
C2 = (k2 * data_range) ** 2
# Compute local means using Gaussian blur
mu_x = gaussian_blur_3d(pred, sigma)
mu_y = gaussian_blur_3d(target, sigma)
# Compute local variances and covariance
sigma_x = gaussian_blur_3d(pred ** 2, sigma) - mu_x ** 2
sigma_y = gaussian_blur_3d(target ** 2, sigma) - mu_y ** 2
sigma_xy = gaussian_blur_3d(pred * target, sigma) - mu_x * mu_y
# SSIM formula: luminance * contrast * structure
numerator = (2 * mu_x * mu_y + C1) * (2 * sigma_xy + C2)
denominator = (mu_x ** 2 + mu_y ** 2 + C1) * (sigma_x + sigma_y + C2)
ssim_map = numerator / denominator
return 1.0 - jnp.mean(ssim_map) # Convert to loss (lower is better)
def loss_notflex(model: eqx.Module, x: jax.Array, y: jax.Array, key, train: bool = True, return_components: bool = False):
"""
Legacy loss function with fixed MAE + SSIM combination.
Args:
model: U-Net model
x: Input degraded volumes
y: Target ground truth volumes
key: JAX random key
train: Whether in training mode
return_components: Whether to return individual loss components
Returns:
Total loss, or (total_loss, (mae, ssim)) if return_components=True
"""
b_model = jax.vmap(model, in_axes=(0, None, None))
pred = b_model(x, key, train)
mae = mean_absolute_error(pred, y)
ssim = ssim_loss(pred, y)
total_loss = mae + ssim
if return_components:
return total_loss, (mae, ssim)
return total_loss
def loss(model: eqx.Module, x: jax.Array, y: jax.Array, key, train: bool = True, return_components: bool = False, use_ssim: bool = True, ssim_weight: float = 1.0):
"""
Flexible loss function with configurable MAE + weighted SSIM.
Args:
model: U-Net model
x: Input degraded volumes
y: Target ground truth volumes
key: JAX random key
train: Whether in training mode
return_components: Whether to return individual loss components
use_ssim: Whether to include SSIM in the loss
ssim_weight: Weight for SSIM component
Returns:
Total loss, or (total_loss, (mae, ssim)) if return_components=True
"""
b_model = jax.vmap(model, in_axes=(0, None, None))
pred = b_model(x, key, train)
mae = mean_absolute_error(pred, y)
ssim = ssim_loss(pred, y) if use_ssim else 0.0
total_loss = mae + (ssim_weight * ssim if use_ssim else 0)
if return_components:
return total_loss, (mae, ssim)
return total_loss
# =============================================================================
# TRAINING FUNCTIONS
# =============================================================================
@eqx.filter_jit
def train_step(model, optimizer_state, degraded_batch, ground_truth_batch, optimizer, key, use_ssim=False, ssim_weight=1.0):
"""
Single training step with gradient computation and model update.
Args:
model: Current model state
optimizer_state: Current optimizer state
degraded_batch: Batch of degraded input volumes
ground_truth_batch: Batch of target volumes
optimizer: Optax optimizer
key: JAX random key
use_ssim: Whether to use SSIM in loss
ssim_weight: Weight for SSIM component
Returns:
Updated model, optimizer_state, loss_value, mae, ssim
"""
def loss_fn(model):
return loss(model, degraded_batch, ground_truth_batch, key, train=True, return_components=True, use_ssim=use_ssim, ssim_weight=ssim_weight)
# Compute loss and gradients (only for differentiable parts)
(loss_value, (mae, ssim)), grads = eqx.filter_value_and_grad(loss_fn, has_aux=True)(model)
# Update model parameters
updates, optimizer_state = optimizer.update(grads, optimizer_state, model)
model = eqx.apply_updates(model, updates)
return model, optimizer_state, loss_value, mae, ssim
def train_step_notflex(model, optimizer_state, degraded_batch, ground_truth_batch, optimizer, key):
"""
Legacy training step with fixed loss function.
Args:
model: Current model state
optimizer_state: Current optimizer state
degraded_batch: Batch of degraded input volumes
ground_truth_batch: Batch of target volumes
optimizer: Optax optimizer
key: JAX random key
Returns:
Updated model, optimizer_state, loss_value, mae, ssim
"""
def loss_fn(model):
return loss(model, degraded_batch, ground_truth_batch, key, train=True, return_components=True)
# Compute loss and gradients (only for differentiable parts)
(loss_value, (mae, ssim)), grads = eqx.filter_value_and_grad(loss_fn, has_aux=True)(model)
# Update model parameters
updates, optimizer_state = optimizer.update(grads, optimizer_state, model)
model = eqx.apply_updates(model, updates)
return model, optimizer_state, loss_value, mae, ssim
def train(model, optimizer, optimizer_state, train_gt, train_sim, test_gt, test_sim, batch_size, num_epochs, save_dir="./", psf_file='/home/dcorrea/deconvolution/data/tubes/Gaussian_low0.5_nonoise/psf_gaussian_low_sig38.5nm.npy', checkpoint_every=5, use_ssim=False, ssim_weight=1.0):
"""
Main training loop with validation, checkpointing, and visualization.
Args:
model: Initial model to train
optimizer: Optax optimizer
optimizer_state: Initial optimizer state
train_gt: Training ground truth data
train_sim: Training degraded data
test_gt: Test ground truth data
test_sim: Test degraded data
batch_size: Batch size for training
num_epochs: Number of training epochs
save_dir: Directory to save outputs
psf_file: Path to PSF file for visualization
checkpoint_every: Save model every N epochs
use_ssim: Whether to use SSIM in loss
ssim_weight: Weight for SSIM component
Returns:
Trained model and training history dictionary
"""
def save_model_checkpoint(model, epoch):
"""Save model checkpoint to disk."""
path = os.path.join(save_dir, f"model_epoch_{epoch+1}.eqx")
eqx.tree_serialise_leaves(path, model)
log_to_file(f"Checkpoint saved: {path}", os.path.join(save_dir, "train_debug.log"))
# Initialize training history tracking
train_losses, test_losses = [], []
train_mae_list, test_mae_list = [], []
train_ssim_list, test_ssim_list = [], []
key = jax.random.PRNGKey(0)
# Main training loop
for epoch in range(num_epochs):
key, subkey = jax.random.split(key)
train_gen = data_loader(train_gt, train_sim, batch_size, subkey, shuffle=True)
# Training phase
epoch_loss = 0.0
epoch_mae = 0.0
epoch_ssim = 0.0
step_count = 0
for gt_batch, degraded_batch in train_gen:
key, subkey2 = jax.random.split(key)
model, optimizer_state, loss, mae, ssim = train_step(model, optimizer_state, degraded_batch, gt_batch, optimizer, subkey2, use_ssim, ssim_weight)
# Debug gradients every other epoch
if (epoch % 2) == 0:
debug_gradients(model, degraded_batch, gt_batch, key, epoch=epoch, log_path=os.path.join(save_dir, "train_debug.log"))
# Accumulate losses
epoch_loss += loss
epoch_mae += mae
epoch_ssim += ssim
step_count += 1
# Compute average training losses
avg_loss = epoch_loss / step_count
avg_mae = epoch_mae / step_count
avg_ssim = epoch_ssim / step_count
train_losses.append(avg_loss)
train_mae_list.append(avg_mae)
train_ssim_list.append(1 - avg_ssim) # Convert to SSIM score
# Validation phase
test_loss = 0.0
test_mae = 0.0
test_ssim = 0.0
test_gen = data_loader(test_gt, test_sim, batch_size, shuffle=False)
test_step_count = 0
for gt_batch, degraded_batch in test_gen:
# Forward pass without training
b_model = jax.vmap(model, in_axes=(0, None, None))
pred = b_model(degraded_batch, key, False)
# Compute test losses
mae = mean_absolute_error(pred, gt_batch)
ssim = ssim_loss(pred, gt_batch) if use_ssim else 0.0
loss = mae + (ssim_weight * ssim if use_ssim else 0.0)
test_loss += loss
test_mae += mae
test_ssim += ssim if use_ssim else 0.0
test_step_count += 1
# Save visualizations at checkpoints
if ((checkpoint_every > 0 and epoch % checkpoint_every == 0) or epoch == num_epochs - 1) and test_step_count == 1:
visualize_3d_slices_save(
gt_batch, degraded_batch, pred,
psf_file=psf_file,
save_dir=save_dir,
basename=f"epoch_{epoch+1}"
)
# Compute average test losses
avg_test_loss = test_loss / test_step_count
avg_test_mae = test_mae / test_step_count
avg_test_ssim = test_ssim / test_step_count
test_losses.append(avg_test_loss)
test_mae_list.append(avg_test_mae)
test_ssim_list.append(1 - avg_test_ssim) # Convert to SSIM score
# Log training progress
log_to_file(
f"Epoch {epoch+1}/{num_epochs} - Train: {avg_loss:.6f} (MAE: {avg_mae:.6f}, SSIM: {1 - avg_ssim:.6f}) - "
f"Test: {avg_test_loss:.6f} (MAE: {avg_test_mae:.6f}, SSIM: {1 - avg_test_ssim:.6f})",
os.path.join(save_dir, "train_debug.log")
)
# Plot loss curves
plot_loss(
train_total_loss=train_losses,
test_total_loss=test_losses,
train_mae=train_mae_list,
test_mae=test_mae_list,
train_ssim=train_ssim_list,
test_ssim=test_ssim_list,
save_path=os.path.join(save_dir, f"loss_epoch_{epoch+1}.png")
)
# Save model checkpoints
if (checkpoint_every > 0 and (epoch + 1) % checkpoint_every == 0):
save_model_checkpoint(model, epoch)
return (
model,
{
"train_mae": train_mae_list,
"train_ssim": train_ssim_list,
"test_mae": test_mae_list,
"test_ssim": test_ssim_list,
"train_total": train_losses,
"test_total": test_losses,
},
)
# =============================================================================
# DEBUGGING AND UTILITY FUNCTIONS
# =============================================================================
def debug_gradients_show(model, degraded_batch, gt_batch, key):
"""
Debug function to display gradient statistics in console.
"""
def loss_fn(m):
return loss(m, degraded_batch, gt_batch, key, train=True)
loss_val, grads = eqx.filter_value_and_grad(loss_fn)(model)
# Compute gradient statistics
all_grads = [jnp.abs(g).max() for g in jax.tree_util.tree_leaves(grads) if g is not None]
all_grads = jnp.array(all_grads)
max_grad = jnp.max(all_grads)
print("Loss:", loss_val)
print("Max gradient value:", max_grad)
return loss_val, max_grad
def debug_gradients(model, degraded_batch, gt_batch, key, epoch=None, log_path="train_debug.log"):
"""
Log gradient statistics to file for training monitoring.
"""
def loss_fn(m):
return loss(m, degraded_batch, gt_batch, key, train=True)
loss_val, grads = eqx.filter_value_and_grad(loss_fn)(model)
# Compute gradient statistics across all parameters
grad_leaves = [g for g in jax.tree_util.tree_leaves(grads) if g is not None]
max_grad = jnp.max(jnp.array([jnp.abs(g).max() for g in grad_leaves]))
mean_grad = jnp.mean(jnp.array([jnp.abs(g).mean() for g in grad_leaves]))
# Log gradient information
log_lines = [
f"Epoch: {epoch}" if epoch is not None else "Gradient debug:",
f"Loss: {loss_val:.6f}",
f"Max gradient: {max_grad:.6f}",
f"Mean gradient: {mean_grad:.6f}",
"-----"
]
log_to_file("\n".join(log_lines), log_path=log_path)
return loss_val, max_grad, mean_grad
def predict(model, volume, key=jax.random.PRNGKey(123)):
"""
Make prediction on a single volume using trained model.
Args:
model: Trained model
volume: Input volume to process
key: JAX random key
Returns:
Predicted volume
"""
return model(volume, key, train=False)
def max_pool3d(x):
"""
3D max pooling operation with 2x2x2 pooling windows.
Applies max pooling over spatial dimensions (D, H, W) while preserving
batch and channel dimensions. Used in the downsampling path of U-Net.
Args:
x: Input tensor with shape (C, D, H, W)
Returns:
Max-pooled tensor with spatial dimensions halved
"""
return jax.lax.reduce_window(
x, # Input tensor
-jnp.inf, # Initial value (negative infinity for max operation)
jax.lax.max, # Reduction operation (max)
window_dimensions=(1, 2, 2, 2), # Pool over spatial dims only
window_strides=(1, 2, 2, 2), # Stride 2 in spatial dimensions
padding="SAME" # Padding mode
)
# =============================================================================
# U-NET ARCHITECTURE COMPONENTS
# =============================================================================
class DoubleConv3D(eqx.Module):
"""
Double convolution block: Conv3D -> ReLU -> Conv3D -> ReLU.
This is the basic building block of the U-Net architecture.
Each block consists of two 3x3x3 convolutions with ReLU activation.
"""
conv1: eqx.nn.Conv3d
conv2: eqx.nn.Conv3d
def __init__(self, in_channels: int, out_channels: int, key, mid_channel=None):
"""
Initialize double convolution block.
Args:
in_channels: Number of input channels
out_channels: Number of output channels
key: JAX random key for weight initialization
mid_channel: Optional intermediate channel count (defaults to out_channels)
"""
if not mid_channel:
mid_channel = out_channels
# Split key for independent initialization of both layers
k1, k2 = jax.random.split(key)
self.conv1 = eqx.nn.Conv3d(in_channels, mid_channel, kernel_size=(3,3,3), stride=1, padding="SAME", key=k1)
self.conv2 = eqx.nn.Conv3d(mid_channel, out_channels, kernel_size=(3,3,3), stride=1, padding="SAME", key=k2)
def __call__(self, x):
"""
Forward pass through double convolution block.
"""
x = jax.nn.relu(self.conv1(x))
x = jax.nn.relu(self.conv2(x))
return x
class Down3D(eqx.Module):
"""
Downsampling block for U-Net encoder path.
Performs max pooling followed by double convolution to reduce
spatial resolution while increasing feature channels.
"""
double_conv: DoubleConv3D
def __init__(self, in_channels: int, out_channels: int, key):
"""
Initialize downsampling block.
Args:
in_channels: Number of input channels
out_channels: Number of output channels
key: JAX random key for weight initialization
"""
self.double_conv = DoubleConv3D(in_channels, out_channels, key=key)
def __call__(self, x):
"""
Forward pass: max pool then double convolution.
"""
x = max_pool3d(x) # Reduce spatial dimensions by factor of 2
x = self.double_conv(x) # Process with double convolution
return x
class Up3D(eqx.Module):
"""
Upsampling block for U-Net decoder path.
Upsamples feature maps and combines them with skip connections
from the encoder path to recover spatial details.
"""
bilinear: bool
up_conv: eqx.nn.ConvTranspose3d = None # Only used if bilinear is False
double_conv: DoubleConv3D
def __init__(self, in_channels: int, out_channels: int, bilinear: bool, key):
"""
Initialize upsampling block.
Args:
in_channels: Number of input channels
out_channels: Number of output channels
bilinear: If True, use trilinear interpolation; if False, use learned transposed conv
key: JAX random key for weight initialization
"""
self.bilinear = bilinear
k1, k2 = jax.random.split(key)
if not bilinear:
# Learned upsampling with transposed convolution
self.up_conv = eqx.nn.ConvTranspose3d(in_channels, in_channels // 2, kernel_size=2, stride=2, key=k1)
self.double_conv = DoubleConv3D(in_channels, out_channels, key=k2)
else:
# Non-learned upsampling with trilinear interpolation
self.up_conv = None
self.double_conv = DoubleConv3D(in_channels, out_channels, k2, in_channels//2)
def __call__(self, x, x_skip):
"""
Forward pass: upsample and combine with skip connection.
"""
if self.bilinear:
# Upsample using trilinear interpolation
new_shape = (x.shape[0], x.shape[1]*2, x.shape[2]*2, x.shape[3]*2)
x = jax.image.resize(x, new_shape, method="trilinear")
else:
# Upsample using learned transposed convolution
x = self.up_conv(x)
# Concatenate skip connection with upsampled features along channel axis
x = jnp.concatenate([x_skip, x], axis=0)
# Process combined features with double convolution
x = self.double_conv(x)
return x
class OutConv3D(eqx.Module):
"""
Output convolution block for final prediction.
Applies a 1x1x1 convolution to map features to the desired
number of output channels (typically 1 for single-channel output).
"""
conv: eqx.nn.Conv3d
def __init__(self, in_channels: int, out_channels: int, key):
"""
Initialize output convolution.
Args:
in_channels: Number of input channels
out_channels: Number of output channels
key: JAX random key for weight initialization
"""
self.conv = eqx.nn.Conv3d(in_channels, out_channels, kernel_size=1, stride=1, padding="SAME", key=key)
def __call__(self, x):
"""
Forward pass through output convolution.
"""
return self.conv(x)
class UNet3D(eqx.Module):
"""
3D U-Net architecture for volumetric image restoration.
Implements a 3D U-Net with:
- 2 downsampling stages (encoder)
- Bottleneck with dropout (p=0.5)
- 2 upsampling stages (decoder) with skip connections
- Additional decoder dropout (p=0.2)
- Final output convolution
"""
inc: DoubleConv3D # Initial convolution block
down1: Down3D # First downsampling block
down2: Down3D # Second downsampling block
bottleneck_dropout: eqx.nn.Dropout # Bottleneck regularization
up1: Up3D # First upsampling block
up2: Up3D # Second upsampling block
decoder_dropout: eqx.nn.Dropout # Decoder regularization
outc: OutConv3D # Final output convolution
bilinear: bool # Upsampling mode flag
def __init__(self, n_channels: int, n_classes: int, bilinear: bool, key, init_channels: int = 64):
"""
Initialize 3D U-Net architecture.
Args:
n_channels: Number of input channels
n_classes: Number of output channels/classes
bilinear: If True, use trilinear interpolation for upsampling
key: JAX random key for weight initialization
init_channels: Base number of channels (must be power of 2)
"""
assert (init_channels & (init_channels - 1) == 0), "init_channels must be a power of 2"
# Generate keys for all submodules
keys = jax.random.split(key, 6)
self.bilinear = bilinear
# Define channel progression
c1 = init_channels # 64
c2 = init_channels * 2 # 128
c3 = init_channels * 4 # 256
factor = 2 if bilinear else 1
# Encoder path
self.inc = DoubleConv3D(n_channels, c1, key=keys[0])
self.down1 = Down3D(c1, c2, key=keys[1])
self.down2 = Down3D(c2, c3 // factor, key=keys[2])
# Bottleneck with dropout for regularization
self.bottleneck_dropout = eqx.nn.Dropout(p=0.5)
# Decoder path
self.up1 = Up3D(c3, c2//factor, bilinear, key=keys[3])
self.up2 = Up3D(c2, c1, bilinear, key=keys[4])
self.decoder_dropout = eqx.nn.Dropout(p=0.2)
# Final output layer
self.outc = OutConv3D(c1, n_classes, key=keys[5])
def __call__(self, x, key, train: bool = True):
"""
Forward pass through 3D U-Net.
Args:
x: Input tensor with shape (C, D, H, W)
key: JAX random key for dropout
train: Whether in training mode (affects dropout)
Returns:
Predicted output tensor with same spatial dimensions as input
"""
# Encoder path - progressively downsample and increase channels
x1 = self.inc(x) # Initial convolution
x2 = self.down1(x1) # First downsampling
x3 = self.down2(x2) # Second downsampling
# Bottleneck with dropout for regularization
key1, key2 = jax.random.split(key)
x3 = self.bottleneck_dropout(x3, key=key1, inference=not train)
# Decoder path - progressively upsample with skip connections
x = self.up1(x3, x2) # First upsampling + skip connection from x2
x = self.up2(x, x1) # Second upsampling + skip connection from x1
# Final dropout and output
x = self.decoder_dropout(x, key=key2, inference=not train)
logits = self.outc(x) # Final prediction
return logits