Skip to content

Move encoders weights to HF-Hub #1035

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from 5 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
66 changes: 57 additions & 9 deletions segmentation_models_pytorch/encoders/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import json
import timm
import copy
import warnings
import functools
import torch.utils.model_zoo as model_zoo
from torch.utils.model_zoo import load_url
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file


from .resnet import resnet_encoders
from .dpn import dpn_encoders
Expand All @@ -22,6 +26,7 @@
from .timm_universal import TimmUniversalEncoder

from ._preprocessing import preprocess_input
from ._legacy_pretrained_settings import pretrained_settings

__all__ = [
"encoders",
Expand Down Expand Up @@ -101,15 +106,40 @@
encoder = EncoderClass(**params)

if weights is not None:
try:
settings = encoders[name]["pretrained_settings"][weights]
except KeyError:
if weights not in encoders[name]["pretrained_settings"]:
available_weights = list(encoders[name]["pretrained_settings"].keys())

Check warning on line 110 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L109-L110

Added lines #L109 - L110 were not covered by tests
raise KeyError(
"Wrong pretrained weights `{}` for encoder `{}`. Available options are: {}".format(
weights, name, list(encoders[name]["pretrained_settings"].keys())
)
f"Wrong pretrained weights `{weights}` for encoder `{name}`. "
f"Available options are: {available_weights}"
)
encoder.load_state_dict(model_zoo.load_url(settings["url"]))

settings = encoders[name]["pretrained_settings"][weights]
repo_id = settings["repo_id"]
revision = settings["revision"]

Check warning on line 118 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L116-L118

Added lines #L116 - L118 were not covered by tests

# First, try to load from HF-Hub, but as far as I know not all countries have
# access to the Hub (e.g. China), so we try to load from the original url if
# the first attempt fails.
try:
hf_hub_download(repo_id, filename="config.json", revision=revision)
model_path = hf_hub_download(

Check warning on line 125 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L123-L125

Added lines #L123 - L125 were not covered by tests
repo_id, filename="model.safetensors", revision=revision
)
state_dict = load_file(model_path, device="cpu")
except Exception as e:
if name in pretrained_settings and weights in pretrained_settings[name]:
message = (

Check warning on line 131 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L128-L131

Added lines #L128 - L131 were not covered by tests
f"Error loading {name} `{weights}` weights from Hugging Face Hub, "
"trying loading from original url..."
)
warnings.warn(message, UserWarning)
url = pretrained_settings[name][weights]["url"]
state_dict = load_url(url, map_location="cpu")

Check warning on line 137 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L135-L137

Added lines #L135 - L137 were not covered by tests
else:
raise e

Check warning on line 139 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L139

Added line #L139 was not covered by tests

# Load model weights
encoder.load_state_dict(state_dict)

Check warning on line 142 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L142

Added line #L142 was not covered by tests

encoder.set_in_channels(in_channels, pretrained=weights is not None)
if output_stride != 32:
Expand All @@ -136,7 +166,25 @@
raise ValueError(
"Available pretrained options {}".format(all_settings.keys())
)
settings = all_settings[pretrained]

repo_id = all_settings[pretrained]["repo_id"]
revision = all_settings[pretrained]["revision"]

# Load config and model
try:
config_path = hf_hub_download(
repo_id, filename="config.json", revision=revision
)
with open(config_path, "r") as f:
settings = json.load(f)
except Exception as e:
if (

Check warning on line 181 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L180-L181

Added lines #L180 - L181 were not covered by tests
encoder_name in pretrained_settings
and pretrained in pretrained_settings[encoder_name]
):
settings = pretrained_settings[encoder_name][pretrained]

Check warning on line 185 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L185

Added line #L185 was not covered by tests
else:
raise e

Check warning on line 187 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L187

Added line #L187 was not covered by tests

formatted_settings = {}
formatted_settings["input_space"] = settings.get("input_space", "RGB")
Expand Down
Loading
Loading