Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions napari_cellseg3d/_tests/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,62 @@ def test_post_processing():
assert results.shape == (2, 64, 64, 64)

worker.stats_csv(np.squeeze(labels))


def test_select_channel():
worker = InferenceWorker(worker_config=InferenceWorkerConfig())
multi = rand_gen.random((3, 4, 4, 4))
single = rand_gen.random((4, 4, 4))

assert worker.select_channel(multi) is multi # keep_channel unset

warnings = []
worker.warn_signal.connect(warnings.append)

worker.config.keep_channel = 1
np.testing.assert_array_equal(worker.select_channel(multi), multi[1])
assert worker.select_channel(None) is None
assert warnings == []

assert worker.select_channel(single) is single # no channel axis
assert len(warnings) == 1

worker.config.keep_channel = 3 # out of range: keep all channels
assert worker.select_channel(multi) is multi
assert worker.select_channel(multi) is multi
assert len(warnings) == 1 # warned once per worker

worker = InferenceWorker(worker_config=InferenceWorkerConfig(keep_channel=3))
worker.warn_signal.connect(warnings.append)
assert worker.select_channel(multi) is multi
assert len(warnings) == 2
assert "3 channels" in warnings[-1]


def test_inference_on_folder_keep_channel():
config = InferenceWorkerConfig(keep_channel=1)
config.images_filepaths = [str(Path(__file__).resolve().parent / "res/test.tif")]

class two_channels:
@staticmethod
def eval():
return True

def __call__(self, x):
x = torch.Tensor(x)
return torch.cat([x, 1 - x], dim=-4) # (N, 2, H, W, D)

class identity:
def __call__(self, x):
return torch.Tensor(x)

worker = InferenceWorker(worker_config=config)
worker.aniso_transform = identity()
image = torch.Tensor(rand_gen.random(size=(1, 1, 8, 8, 8)))
res = worker.inference_on_folder(
{"image": image},
0,
model=two_channels(),
post_process_transforms=identity(),
)
assert res.semantic_segmentation.shape == (8, 8, 8)
27 changes: 27 additions & 0 deletions napari_cellseg3d/_tests/test_model_wnet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import torch

from napari_cellseg3d.code_models.models.model_WNet import WNet_
from napari_cellseg3d.code_models.models.wnet.model import WNet


def test_num_classes_from_weights(tmp_path):
weights = tmp_path / "wnet_3_classes.pth"
torch.save(WNet(num_classes=3).state_dict(), weights)
assert WNet_.num_classes_from_weights(weights) == 3

model = WNet_(out_channels=3)
model.load_state_dict(torch.load(weights, weights_only=True), strict=True)


def test_num_classes_from_weights_unreadable(tmp_path):
assert WNet_.num_classes_from_weights(tmp_path / "missing.pth") is None
assert WNet_.num_classes_from_weights(tmp_path / "model.onnx") is None
no_key = tmp_path / "other.pth"
torch.save({"weight": torch.zeros(1)}, no_key)
assert WNet_.num_classes_from_weights(no_key) is None
garbage = tmp_path / "garbage.pth"
garbage.write_bytes(b"not a checkpoint")
assert WNet_.num_classes_from_weights(garbage) is None
pickled_model = tmp_path / "pickled_model.pth"
torch.save(torch.nn.Conv3d(1, 2, 1), pickled_model)
assert WNet_.num_classes_from_weights(pickled_model) is None
55 changes: 55 additions & 0 deletions napari_cellseg3d/_tests/test_plugin_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,58 @@ def test_inference(make_napari_viewer_proxy, qtbot):
# widget.worker.start()

assert widget.on_finish()


def test_keep_channel_choice(make_napari_viewer_proxy, tmp_path):
import torch

from napari_cellseg3d import interface as ui
from napari_cellseg3d.code_models.models.wnet.model import WNet

# fresh widget, not the singleton instance closed by test_inference
ui.QWidgetSingleton._instances.pop(Inferer, None)
viewer = make_napari_viewer_proxy()
widget = Inferer(viewer)

widget.model_choice.setCurrentText("SegResNet")
assert widget.keep_channel_choice.isHidden()
assert widget._set_worker_config().keep_channel is None

widget.model_choice.setCurrentText("WNet3D")
assert not widget.keep_channel_choice.isHidden()
assert widget.channel_choice_container.isHidden()
assert widget.channel_choice.count() == 2

widget.keep_channel_choice.setChecked(True)
assert not widget.channel_choice_container.isHidden()
assert widget.channel_choice.currentIndex() == 1 # pretrained foreground
worker_config = widget._set_worker_config()
assert worker_config.keep_channel == 1
assert worker_config.model_info.num_classes == 2

weights = tmp_path / "wnet_3_classes.pth"
torch.save(WNet(num_classes=3).state_dict(), weights)
widget.weights_config.path = str(weights)
widget.custom_weights_choice.setChecked(True)
assert widget.channel_choice.count() == 3
assert widget.channel_choice.currentIndex() == 1 # kept when still valid
widget.channel_choice.setCurrentIndex(2)
worker_config = widget._set_worker_config()
assert worker_config.keep_channel == 2
assert worker_config.model_info.num_classes == 3

widget.weights_config.path = str(tmp_path / "wnet.onnx")
widget._update_wnet_num_classes()
assert not widget.keep_channel_choice.isEnabled()
assert not widget.keep_channel_choice.isChecked()
assert widget.channel_choice_container.isHidden()
assert widget._set_worker_config().keep_channel is None

widget.custom_weights_choice.setChecked(False)
assert widget.keep_channel_choice.isEnabled()
widget.keep_channel_choice.setChecked(True)
assert widget.channel_choice.count() == 2
assert widget.channel_choice.currentIndex() == 1 # pretrained foreground

widget.keep_channel_choice.setChecked(False)
assert widget._set_worker_config().keep_channel is None
30 changes: 30 additions & 0 deletions napari_cellseg3d/code_models/models/model_WNet.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,20 @@
.. important:: Used for inference only. For training the base class is used.
"""

import pickle
from pathlib import Path
from typing import Optional

import torch

# local
from napari_cellseg3d.code_models.models.wnet.model import WNet_encoder
from napari_cellseg3d.utils import LOGGER as logger
from napari_cellseg3d.utils import remap_image

NUM_CLASSES_KEY = "encoder.out_b.module.8.bias"
"""State-dict key of the encoder's final conv bias, whose length is the number of classes."""


class WNet_(WNet_encoder):
"""W-Net wrapper for napari_cellseg3d.
Expand All @@ -16,6 +26,8 @@ class WNet_(WNet_encoder):

weights_file = "wnet_latest.pth"
default_threshold = 0.6
default_channel = 1
"""Foreground channel of the pretrained weights."""

def __init__(
self,
Expand Down Expand Up @@ -46,6 +58,24 @@ def forward(self, x):
norm_x = remap_image(x)
return super().forward(norm_x)

@staticmethod
def num_classes_from_weights(weights_path) -> Optional[int]:
"""Number of encoder output classes stored in a .pth weights file, or None if it cannot be read."""
if Path(weights_path).suffix != ".pth":
return None
try:
state_dict = torch.load(weights_path, map_location="cpu", weights_only=True)
return int(state_dict[NUM_CLASSES_KEY].shape[0])
except (
OSError,
RuntimeError,
KeyError,
AttributeError,
pickle.UnpicklingError,
) as e:
logger.debug(f"Could not read number of classes from {weights_path}: {e}")
return None

def load_state_dict(self, state_dict, strict=True):
"""Load the model state dict for inference, without the decoder weights."""
encoder_checkpoint = state_dict.copy()
Expand Down
44 changes: 40 additions & 4 deletions napari_cellseg3d/code_models/worker_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def __init__(
self.error_signal = self._signals.error_signal

self.config = worker_config
self._keep_channel_warned = False

"""These attributes are all arguments of :py:func:~inference, please see that for reference"""

Expand Down Expand Up @@ -169,6 +170,8 @@ def log_parameters(self):
self.log("Parameters summary :")

self.log(f"Model is : {config.model_info.name}")
if config.keep_channel is not None:
self.log(f"Keeping only channel {config.keep_channel}")
if config.post_process_config.thresholding.enabled:
self.log(
f"Thresholding is enabled at {config.post_process_config.thresholding.threshold_value}"
Expand Down Expand Up @@ -644,14 +647,16 @@ def inference_on_folder(self, inf_data, i, model, post_process_transforms):
logger.debug(
f"Output shape {out.shape[-3:]} does not match input shape {inputs_shape_corrected[-3:]} on HWD dims even after rotation"
)
out_all_channels = out
out = self.select_channel(out)
self.save_image(out, i=i)
instance_labels, stats = self.get_instance_result(out, i=i)
if self.config.use_crf:
crf_in = inputs.detach().cpu().numpy()
try:
crf_results = self.run_crf(
crf_in,
out,
out_all_channels,
aniso_transform=self.aniso_transform,
image_id=i,
)
Expand All @@ -675,6 +680,32 @@ def inference_on_folder(self, inf_data, i, model, post_process_transforms):
i=i,
)

def select_channel(self, array):
"""Keeps only channel :py:attr:`config.keep_channel` of a (C, H, W, D) array.

Returned unchanged if ``keep_channel`` is unset, the array has no channel axis,
or the channel does not exist; the latter two warn once per worker.
"""
channel = self.config.keep_channel
if channel is None or array is None:
return array
if len(array.shape) != 4:
self._warn_channel_once(
f"Channel {channel} requested but the output has no channel axis (shape {array.shape}); keeping the output as is"
)
return array
if not 0 <= channel < array.shape[0]:
self._warn_channel_once(
f"Channel {channel} requested but the output has {array.shape[0]} channels; keeping all channels"
)
return array
return array[channel]

def _warn_channel_once(self, message):
if not self._keep_channel_warned:
self._keep_channel_warned = True
self.warn(message)

def run_crf(self, image, labels, aniso_transform, image_id=0):
"""Runs CRF on the image and labels."""
try:
Expand All @@ -691,6 +722,7 @@ def run_crf(self, image, labels, aniso_transform, image_id=0):
crf_results = crf_with_config(
image, labels, config=self.config.crf_config, log=self.log
)
crf_results = self.select_channel(crf_results)
self.save_image(
crf_results,
i=image_id,
Expand Down Expand Up @@ -739,14 +771,16 @@ def inference_on_layer(self, image, model, post_process_transforms):
logger.debug(
f"Output shape {out.shape[-3:]} does not match input shape {layer_shape_corrected[-3:]} on HWD dims even after rotation"
)
out_all_channels = out
out = self.select_channel(out)
self.save_image(out, from_layer=True)

instance_labels, stats = self.get_instance_result(
semantic_labels=out, from_layer=True
)

crf_results = (
self.run_crf(image, out, aniso_transform=self.aniso_transform)
self.run_crf(image, out_all_channels, aniso_transform=self.aniso_transform)
if self.config.use_crf
else None
)
Expand Down Expand Up @@ -818,10 +852,12 @@ def inference(self):
model = ONNXModelWrapper(weights_config.path)
else: # assume is .pth
self.log("Instantiating model...")
model_kwargs = {}
if model_name == "WNet3D":
model_kwargs["out_channels"] = self.config.model_info.num_classes
model = model_class(
input_img_size=[dims, dims, dims],
# device=self.config.device,
# num_classes=self.config.model_info.num_classes,
**model_kwargs,
)
try:
model = model.to(self.config.device)
Expand Down
Loading
Loading