Skip to content
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

Move encoders weights to HF-Hub #1035

Merged
merged 9 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from 7 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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies = [
'numpy>=1.19.3',
'pillow>=8',
'pretrainedmodels>=0.7.1',
'safetensors>=0.3.1',
'six>=1.5',
'timm>=0.9',
'torch>=1.8',
Expand Down
1 change: 1 addition & 0 deletions requirements/minimum.old
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ huggingface-hub==0.24.0
numpy==1.19.3
pillow==8.0.0
pretrainedmodels==0.7.1
safetensors==0.3.1
six==1.5.0
timm==0.9.0
torch==1.9.0
Expand Down
1 change: 1 addition & 0 deletions requirements/required.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ huggingface_hub==0.27.1
numpy==2.2.1
pillow==11.1.0
pretrainedmodels==0.7.4
safetensors==0.5.2
six==1.17.0
timm==1.0.13
torch==2.5.1
Expand Down
69 changes: 60 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
adamjstewart marked this conversation as resolved.
Show resolved Hide resolved


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,43 @@
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}"
)

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.
weights_path = None
try:
hf_hub_download(repo_id, filename="config.json", revision=revision)
weights_path = hf_hub_download(

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

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L123-L126

Added lines #L123 - L126 were not covered by tests
repo_id, filename="model.safetensors", revision=revision
)
encoder.load_state_dict(model_zoo.load_url(settings["url"]))
except Exception as e:
adamjstewart marked this conversation as resolved.
Show resolved Hide resolved
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#L129-L131

Added lines #L129 - 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

if weights_path is not None:
state_dict = load_file(weights_path, device="cpu")

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#L141-L142

Added lines #L141 - L142 were not covered by tests

# Load model weights
encoder.load_state_dict(state_dict)

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

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L145

Added line #L145 was not covered by tests

encoder.set_in_channels(in_channels, pretrained=weights is not None)
if output_stride != 32:
Expand All @@ -136,7 +169,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 184 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L183-L184

Added lines #L183 - L184 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 188 in segmentation_models_pytorch/encoders/__init__.py

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L188

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

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

View check run for this annotation

Codecov / codecov/patch

segmentation_models_pytorch/encoders/__init__.py#L190

Added line #L190 was not covered by tests

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