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
8 changes: 6 additions & 2 deletions docs/source/guides/inference_module_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,12 @@ Interface and functionalities

.. note::
Pre-trained weights are downloaded automatically when first needed. By default they are stored inside the installed package.
To store them elsewhere, set the ``CELLSEG3D_WEIGHTS_DIR`` environment variable to the desired folder before launching napari,
e.g. ``export CELLSEG3D_WEIGHTS_DIR=~/cellseg3d/weights``.
To store them elsewhere, set the ``CELLSEG3D_WEIGHTS_DIR`` environment variable to the desired folder before launching napari:

* Linux/macOS: ``export CELLSEG3D_WEIGHTS_DIR=~/cellseg3d/weights``
* Windows (PowerShell): ``$env:CELLSEG3D_WEIGHTS_DIR = "$HOME\cellseg3d\weights"``

Weights already downloaded to the previous location are not moved.

* **Inference parameters**:

Expand Down
4 changes: 1 addition & 3 deletions napari_cellseg3d/_tests/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

from napari_cellseg3d.code_models.worker_inference import InferenceWorker
from napari_cellseg3d.code_models.workers_utils import (
PRETRAINED_WEIGHTS_DIR,
InferenceResult,
ONNXModelWrapper,
WeightsDownloader,
Expand All @@ -19,8 +18,7 @@

def test_onnx_inference(make_napari_viewer_proxy):
downloader = WeightsDownloader()
downloader.download_weights("WNet_ONNX", "wnet.onnx")
path = str(Path(PRETRAINED_WEIGHTS_DIR).resolve() / "wnet.onnx")
path = str(downloader.download_weights("WNet_ONNX", "wnet.onnx"))
assert Path(path).is_file()
dims = 64
batch = 1
Expand Down
6 changes: 3 additions & 3 deletions napari_cellseg3d/_tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,16 +110,16 @@ def on_yield(result):

def test_pretrained_weights_compatibility():
from napari_cellseg3d.code_models.workers_utils import WeightsDownloader
from napari_cellseg3d.config import MODEL_LIST, PRETRAINED_WEIGHTS_DIR
from napari_cellseg3d.config import MODEL_LIST

for model_name in MODEL_LIST:
file_name = MODEL_LIST[model_name].weights_file
WeightsDownloader().download_weights(model_name, file_name)
weights_path = WeightsDownloader().download_weights(model_name, file_name)
model = MODEL_LIST[model_name](input_img_size=[64, 64, 64])
try:
model.load_state_dict(
torch.load(
str(Path(PRETRAINED_WEIGHTS_DIR) / file_name),
str(weights_path),
map_location="cpu",
),
strict=True,
Expand Down
55 changes: 44 additions & 11 deletions napari_cellseg3d/_tests/test_weight_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

import pytest

from napari_cellseg3d.code_models.workers_utils import (
PRETRAINED_WEIGHTS_DIR,
WeightsDownloader,
from napari_cellseg3d.code_models.workers_utils import WeightsDownloader
from napari_cellseg3d.utils import (
PACKAGE_PRETRAINED_DIR,
WEIGHTS_DIR_ENV_VAR,
get_pretrained_weights_dir,
)


Expand All @@ -14,21 +16,52 @@
)
def test_weight_download():
downloader = WeightsDownloader()
downloader.download_weights("test", "test.pth")
result_path = PRETRAINED_WEIGHTS_DIR / "test.pth"
result_path = downloader.download_weights("test", "test.pth")

assert result_path == get_pretrained_weights_dir() / "test.pth"
assert result_path.is_file()


def test_weights_dir_env_var(monkeypatch, tmp_path):
from napari_cellseg3d.utils import (
PRETRAINED_URLS_DIR,
WEIGHTS_DIR_ENV_VAR,
get_pretrained_weights_dir,
@pytest.mark.skipif(
os.getenv("CI") == "true",
reason="This test causes CI to freeze",
)
def test_weight_download_custom_dir(monkeypatch, tmp_path):
weights_dir = tmp_path / "not_yet_created"
monkeypatch.setenv(WEIGHTS_DIR_ENV_VAR, str(weights_dir))

result_path = WeightsDownloader().download_weights("test", "test.pth")

assert result_path == weights_dir.resolve() / "test.pth"
assert result_path.is_file()
# URL list stays in the package
assert not (weights_dir / "pretrained_model_urls.json").exists()


def test_existing_weights_in_custom_dir_skip_download(monkeypatch, tmp_path):
monkeypatch.setenv(WEIGHTS_DIR_ENV_VAR, str(tmp_path))
existing = tmp_path / "test.pth"
existing.touch()

assert (
WeightsDownloader().download_weights("test", "test.pth") == existing.resolve()
)


def test_deprecated_config_weights_dir(monkeypatch, tmp_path):
monkeypatch.setenv(WEIGHTS_DIR_ENV_VAR, str(tmp_path))
with pytest.deprecated_call():
from napari_cellseg3d.config import PRETRAINED_WEIGHTS_DIR

assert str(tmp_path.resolve()) == PRETRAINED_WEIGHTS_DIR


def test_weights_dir_env_var(monkeypatch, tmp_path):
monkeypatch.delenv(WEIGHTS_DIR_ENV_VAR, raising=False)
assert get_pretrained_weights_dir() == PRETRAINED_URLS_DIR
assert get_pretrained_weights_dir() == PACKAGE_PRETRAINED_DIR

monkeypatch.setenv(WEIGHTS_DIR_ENV_VAR, "")
assert get_pretrained_weights_dir() == PACKAGE_PRETRAINED_DIR

monkeypatch.setenv(WEIGHTS_DIR_ENV_VAR, str(tmp_path))
assert get_pretrained_weights_dir() == tmp_path.resolve()
4 changes: 2 additions & 2 deletions napari_cellseg3d/code_models/models/model_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ def forward(self, x):
model = TestModel()
model.train()
model.zero_grad()
from napari_cellseg3d.config import PRETRAINED_WEIGHTS_DIR
from napari_cellseg3d.utils import get_pretrained_weights_dir

torch.save(
model.state_dict(),
PRETRAINED_WEIGHTS_DIR + f"/{TestModel.weights_file}",
get_pretrained_weights_dir() / TestModel.weights_file,
)
10 changes: 4 additions & 6 deletions napari_cellseg3d/code_models/worker_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
volume_stats,
)
from napari_cellseg3d.code_models.workers_utils import (
PRETRAINED_WEIGHTS_DIR,
InferenceResult,
LogSignal,
ONNXModelWrapper,
Expand Down Expand Up @@ -871,12 +870,11 @@ def inference(self):
if weights_config.use_custom:
weights = weights_config.path
else:
self.downloader.download_weights(
model_name,
model_class.weights_file,
)
weights = str(
PRETRAINED_WEIGHTS_DIR / Path(model_class.weights_file)
self.downloader.download_weights(
model_name,
model_class.weights_file,
)
)
try:
missing = (
Expand Down
13 changes: 7 additions & 6 deletions napari_cellseg3d/code_models/worker_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@
from napari_cellseg3d.code_models.models.wnet.model import WNet
from napari_cellseg3d.code_models.models.wnet.soft_Ncuts import SoftNCutsLoss
from napari_cellseg3d.code_models.workers_utils import (
PRETRAINED_WEIGHTS_DIR,
LogSignal,
QuantileNormalizationd,
RemapTensor,
Expand All @@ -78,7 +77,7 @@
)
WANDB_INSTALLED = False

logger.debug(f"PRETRAINED WEIGHT DIR LOCATION : {PRETRAINED_WEIGHTS_DIR}")
logger.debug(f"PRETRAINED WEIGHT DIR LOCATION : {utils.get_pretrained_weights_dir()}")

"""
Writing something to log messages from outside the main thread needs specific care,
Expand Down Expand Up @@ -501,8 +500,9 @@ def train(self, provided_model=None, provided_optimizer=None, provided_loss=None
)

weights_file = WNet_.weights_file
self.downloader.download_weights("WNet3D", weights_file)
weights = str(PRETRAINED_WEIGHTS_DIR / Path(weights_file))
weights = str(
self.downloader.download_weights("WNet3D", weights_file)
)
self.config.weights_info.path = weights

if self.config.weights_info.use_custom:
Expand Down Expand Up @@ -1404,8 +1404,9 @@ def get_patch_loader_func(num_samples):
if weights_config.use_custom or weights_config.use_pretrained:
if weights_config.use_pretrained:
weights_file = model_class.weights_file
self.downloader.download_weights(model_name, weights_file)
weights = str(PRETRAINED_WEIGHTS_DIR / Path(weights_file))
weights = str(
self.downloader.download_weights(model_name, weights_file)
)
weights_config.path = weights
elif weights_config.use_custom:
weights = str(Path(weights_config.path))
Expand Down
14 changes: 8 additions & 6 deletions napari_cellseg3d/code_models/workers_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@
if TYPE_CHECKING:
from napari_cellseg3d.code_models.instance_segmentation import ImageStats

PRETRAINED_WEIGHTS_DIR = utils.get_pretrained_weights_dir()


class WeightsDownloader:
"""A utility class the downloads the weights of a model when needed."""
Expand All @@ -34,14 +32,17 @@ def __init__(self, log_widget: t.Optional[ui.Log] = None):
"""
self.log_widget = log_widget

def download_weights(self, model_name: str, model_weights_filename: str):
def download_weights(self, model_name: str, model_weights_filename: str) -> Path:
"""Downloads a specific pretrained model.

This code is adapted from DeepLabCut with permission from MWMathis.

Args:
model_name (str): name of the model to download
model_weights_filename (str): name of the .pth file expected for the model

Returns:
Path: path to the weights file, in utils.get_pretrained_weights_dir()
"""
import json
import tarfile
Expand All @@ -51,9 +52,9 @@ def show_progress(_, block_size, __): # count, block_size, total_size
pbar.update(block_size)

logger.info("*" * 20)
pretrained_folder_path = PRETRAINED_WEIGHTS_DIR
pretrained_folder_path = utils.get_pretrained_weights_dir()
pretrained_folder_path.mkdir(parents=True, exist_ok=True)
json_path = utils.PRETRAINED_URLS_DIR / Path("pretrained_model_urls.json")
json_path = utils.PACKAGE_PRETRAINED_DIR / Path("pretrained_model_urls.json")

check_path = pretrained_folder_path / Path(model_weights_filename)

Expand All @@ -62,7 +63,7 @@ def show_progress(_, block_size, __): # count, block_size, total_size
if self.log_widget is not None:
self.log_widget.print_and_log(message, printing=False)
logger.info(message)
return
return check_path

with Path.open(json_path) as f:
neturls = json.load(f)
Expand Down Expand Up @@ -111,6 +112,7 @@ def safe_extract(tar, path=".", members=None, *, numeric_owner=False):
raise ValueError(
f"Unknown model: {model_name}. Should be one of {', '.join(neturls)}"
)
return check_path


class LogSignal(WorkerBaseSignals):
Expand Down
18 changes: 16 additions & 2 deletions napari_cellseg3d/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Module to store configuration parameters for napari_cellseg3d."""

import datetime
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Optional
Expand Down Expand Up @@ -32,7 +33,18 @@
# "test" : DO NOT USE, reserved for testing
}

Comment thread
C-Achard marked this conversation as resolved.
Resolved
PRETRAINED_WEIGHTS_DIR = str(get_pretrained_weights_dir())

def __getattr__(name):
"""Provides `PRETRAINED_WEIGHTS_DIR`, deprecated; use `utils.get_pretrained_weights_dir()`."""
if name == "PRETRAINED_WEIGHTS_DIR":
warnings.warn(
"napari_cellseg3d.config.PRETRAINED_WEIGHTS_DIR is deprecated, "
"use napari_cellseg3d.utils.get_pretrained_weights_dir() instead",
DeprecationWarning,
stacklevel=2,
)
return str(get_pretrained_weights_dir())
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


################
Expand Down Expand Up @@ -132,7 +144,9 @@ class WeightsInfo:
use_pretrained (Optional[bool]): whether to use pretrained weights
"""

path: Optional[str] = PRETRAINED_WEIGHTS_DIR
path: Optional[str] = field(
default_factory=lambda: str(get_pretrained_weights_dir())
)
use_pretrained: Optional[bool] = False
use_custom: Optional[bool] = False

Expand Down
5 changes: 1 addition & 4 deletions napari_cellseg3d/dev_scripts/colab_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,13 @@
# local
from napari_cellseg3d import config, utils
from napari_cellseg3d.code_models.worker_training import WNetTrainingWorker
from napari_cellseg3d.code_models.workers_utils import (
PRETRAINED_WEIGHTS_DIR,
)

if TYPE_CHECKING:
from monai.data import DataLoader

logger = utils.LOGGER
VERBOSE_SCHEDULER = True
logger.debug(f"PRETRAINED WEIGHT DIR LOCATION : {PRETRAINED_WEIGHTS_DIR}")
logger.debug(f"PRETRAINED WEIGHT DIR LOCATION : {utils.get_pretrained_weights_dir()}")


class LogFixture:
Expand Down
7 changes: 4 additions & 3 deletions napari_cellseg3d/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
rand_gen = Generator(PCG64(12345))

WEIGHTS_DIR_ENV_VAR = "CELLSEG3D_WEIGHTS_DIR"
# Bundled folder holding pretrained_model_urls.json (default download location)
PRETRAINED_URLS_DIR = (
# Package folder: holds pretrained_model_urls.json; default weights location
PACKAGE_PRETRAINED_DIR = (
Path(__file__).parent.resolve() / "code_models" / "models" / "pretrained"
)

Expand All @@ -41,11 +41,12 @@ def get_pretrained_weights_dir() -> Path:

Uses the path set in the CELLSEG3D_WEIGHTS_DIR environment variable if defined,
otherwise the pretrained folder inside the installed package.
Read on each call, so the variable may be set after import.
"""
custom_dir = os.environ.get(WEIGHTS_DIR_ENV_VAR)
if custom_dir:
return Path(custom_dir).expanduser().resolve()
return PRETRAINED_URLS_DIR
return PACKAGE_PRETRAINED_DIR


####################
Expand Down
1 change: 0 additions & 1 deletion notebooks/Colab_WNet3D_training.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@
"from pathlib import Path\n",
"\n",
"from napari_cellseg3d.config import (\n",
" PRETRAINED_WEIGHTS_DIR,\n",
" WandBConfig,\n",
" WeightsInfo,\n",
" WNetTrainingWorkerConfig,\n",
Expand Down
Loading