Skip to content

Commit bea02cc

Browse files
committed
update
1 parent d06750a commit bea02cc

File tree

3 files changed

+67
-45
lines changed

3 files changed

+67
-45
lines changed

src/diffusers/loaders/single_file_utils.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,14 @@ def is_valid_url(url):
387387
return False
388388

389389

390+
def _validate_single_file_path(pretrained_model_name_or_path):
391+
if os.path.isfile(pretrained_model_name_or_path):
392+
return True
393+
394+
repo_id, weight_name = _extract_repo_id_and_weights_name(pretrained_model_name_or_path)
395+
return bool(repo_id and weight_name)
396+
397+
390398
def _extract_repo_id_and_weights_name(pretrained_model_name_or_path):
391399
if not is_valid_url(pretrained_model_name_or_path):
392400
raise ValueError("Invalid `pretrained_model_name_or_path` provided. Please set it to a valid URL.")
@@ -398,7 +406,6 @@ def _extract_repo_id_and_weights_name(pretrained_model_name_or_path):
398406
pretrained_model_name_or_path = pretrained_model_name_or_path.replace(prefix, "")
399407
match = re.match(pattern, pretrained_model_name_or_path)
400408
if not match:
401-
logger.warning("Unable to identify the repo_id and weights_name from the provided URL.")
402409
return repo_id, weights_name
403410

404411
repo_id = f"{match.group(1)}/{match.group(2)}"

src/diffusers/modular_pipelines/modular_pipeline.py

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from typing import Any, Dict, List, Optional, Tuple, Union
2323

2424
import torch
25-
from huggingface_hub import create_repo
25+
from huggingface_hub import create_pretrained_model_name_or_path
2626
from huggingface_hub.utils import validate_hf_hub_args
2727
from tqdm.auto import tqdm
2828
from typing_extensions import Self
@@ -325,7 +325,7 @@ def from_pretrained(
325325
)
326326
if not (has_remote_code and trust_remote_code):
327327
raise ValueError(
328-
"Selected model repository does not happear to have any custom code or does not have a valid `config.json` file."
328+
"Selected model pretrained_model_name_or_pathsitory does not happear to have any custom code or does not have a valid `config.json` file."
329329
)
330330

331331
class_ref = config["auto_map"][cls.__name__]
@@ -366,7 +366,7 @@ def init_pipeline(
366366
collection: Optional[str] = None,
367367
) -> "ModularPipeline":
368368
"""
369-
create a ModularPipeline, optionally accept modular_repo to load from hub.
369+
create a ModularPipeline, optionally accept modular_pretrained_model_name_or_path to load from hub.
370370
"""
371371
pipeline_class_name = MODULAR_PIPELINE_MAPPING.get(self.model_name, ModularPipeline.__name__)
372372
diffusers_module = importlib.import_module("diffusers")
@@ -1481,7 +1481,7 @@ def __init__(
14811481
pretrained_model_name_or_path: Path to a pretrained pipeline configuration. Can be None if the pipeline
14821482
does not require any additional loading config. If provided, will first try to load component specs
14831483
(only for from_pretrained components) and config values from `modular_model_index.json`, then
1484-
fallback to `model_index.json` for compatibility with standard non-modular repositories.
1484+
fallback to `model_index.json` for compatibility with standard non-modular pretrained_model_name_or_pathsitories.
14851485
components_manager:
14861486
Optional ComponentsManager for managing multiple component cross different pipelines and apply
14871487
offloading strategies.
@@ -1494,7 +1494,7 @@ def __init__(
14941494
pipeline = ModularPipeline(blocks=my_custom_blocks)
14951495
14961496
# Initialize from pretrained configuration
1497-
pipeline = ModularPipeline(blocks=my_blocks, pretrained_model_name_or_path="my-repo/modular-pipeline")
1497+
pipeline = ModularPipeline(blocks=my_blocks, pretrained_model_name_or_path="my-pretrained_model_name_or_path/modular-pipeline")
14981498
14991499
# Initialize with components manager
15001500
pipeline = ModularPipeline(
@@ -1528,7 +1528,7 @@ def __init__(
15281528
self._component_specs = {spec.name: deepcopy(spec) for spec in self.blocks.expected_components}
15291529
self._config_specs = {spec.name: deepcopy(spec) for spec in self.blocks.expected_configs}
15301530

1531-
# update component_specs and config_specs from modular_repo
1531+
# update component_specs and config_specs from modular_pretrained_model_name_or_path
15321532
if pretrained_model_name_or_path is not None:
15331533
cache_dir = kwargs.pop("cache_dir", None)
15341534
force_download = kwargs.pop("force_download", False)
@@ -1573,7 +1573,7 @@ def __init__(
15731573

15741574
config_dict = DiffusionPipeline.load_config(pretrained_model_name_or_path, **load_config_kwargs)
15751575
except EnvironmentError as e:
1576-
logger.debug(f" model_index.json not found in the repo: {e}")
1576+
logger.debug(f" model_index.json not found in the pretrained_model_name_or_path: {e}")
15771577
config_dict = None
15781578

15791579
# update component_specs and config_specs based on model_index.json
@@ -1582,7 +1582,7 @@ def __init__(
15821582
if name in self._component_specs and isinstance(value, (tuple, list)) and len(value) == 2:
15831583
library, class_name = value
15841584
component_spec_dict = {
1585-
"repo": pretrained_model_name_or_path,
1585+
"pretrained_model_name_or_path": pretrained_model_name_or_path,
15861586
"subfolder": name,
15871587
"type_hint": (library, class_name),
15881588
}
@@ -1633,13 +1633,13 @@ def from_pretrained(
16331633
**kwargs,
16341634
):
16351635
"""
1636-
Load a ModularPipeline from a huggingface hub repo.
1636+
Load a ModularPipeline from a huggingface hub pretrained_model_name_or_path.
16371637
16381638
Args:
16391639
pretrained_model_name_or_path (`str` or `os.PathLike`, optional):
16401640
Path to a pretrained pipeline configuration. It will first try to load config from
16411641
`modular_model_index.json`, then fallback to `model_index.json` for compatibility with standard
1642-
non-modular repositories. If the repo does not contain any pipeline config, it will be set to None
1642+
non-modular pretrained_model_name_or_pathsitories. If the pretrained_model_name_or_path does not contain any pipeline config, it will be set to None
16431643
during initialization.
16441644
trust_remote_code (`bool`, optional):
16451645
Whether to trust remote code when loading the pipeline, need to be set to True if you want to create
@@ -1679,7 +1679,7 @@ def from_pretrained(
16791679
# try to load modular_model_index.json
16801680
config_dict = cls.load_config(pretrained_model_name_or_path, **load_config_kwargs)
16811681
except EnvironmentError as e:
1682-
logger.debug(f" modular_model_index.json not found in the repo: {e}")
1682+
logger.debug(f" modular_model_index.json not found in the pretrained_model_name_or_path: {e}")
16831683
config_dict = None
16841684

16851685
if config_dict is not None:
@@ -1692,7 +1692,7 @@ def from_pretrained(
16921692

16931693
config_dict = DiffusionPipeline.load_config(pretrained_model_name_or_path, **load_config_kwargs)
16941694
except EnvironmentError as e:
1695-
logger.debug(f" model_index.json not found in the repo: {e}")
1695+
logger.debug(f" model_index.json not found in the pretrained_model_name_or_path: {e}")
16961696

16971697
if config_dict is not None:
16981698
logger.debug(" try to determine the modular pipeline class from model_index.json")
@@ -1731,11 +1731,15 @@ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub:
17311731
private = kwargs.pop("private", None)
17321732
create_pr = kwargs.pop("create_pr", False)
17331733
token = kwargs.pop("token", None)
1734-
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
1735-
repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
1734+
pretrained_model_name_or_path_id = kwargs.pop(
1735+
"pretrained_model_name_or_path_id", save_directory.split(os.path.sep)[-1]
1736+
)
1737+
pretrained_model_name_or_path_id = create_pretrained_model_name_or_path(
1738+
pretrained_model_name_or_path_id, exist_ok=True, private=private, token=token
1739+
).pretrained_model_name_or_path_id
17361740

17371741
# Create a new empty model card and eventually tag it
1738-
model_card = load_or_create_model_card(repo_id, token=token, is_pipeline=True)
1742+
model_card = load_or_create_model_card(pretrained_model_name_or_path_id, token=token, is_pipeline=True)
17391743
model_card = populate_model_card(model_card)
17401744
model_card.save(os.path.join(save_directory, "README.md"))
17411745

@@ -1745,7 +1749,7 @@ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub:
17451749
if push_to_hub:
17461750
self._upload_folder(
17471751
save_directory,
1748-
repo_id,
1752+
pretrained_model_name_or_path_id,
17491753
token=token,
17501754
commit_message=commit_message,
17511755
create_pr=create_pr,
@@ -1809,7 +1813,7 @@ def register_components(self, **kwargs):
18091813
library, class_name = None, None
18101814

18111815
# extract the loading spec from the updated component spec that'll be used as part of modular_model_index.json config
1812-
# e.g. {"repo": "stabilityai/stable-diffusion-2-1",
1816+
# e.g. {"pretrained_model_name_or_path": "stabilityai/stable-diffusion-2-1",
18131817
# "type_hint": ("diffusers", "UNet2DConditionModel"),
18141818
# "subfolder": "unet",
18151819
# "variant": None,
@@ -2113,7 +2117,7 @@ def load_components(self, names: Optional[Union[List[str], str]] = None, **kwarg
21132117
**kwargs: additional kwargs to be passed to `from_pretrained()`.Can be:
21142118
- a single value to be applied to all components to be loaded, e.g. torch_dtype=torch.bfloat16
21152119
- a dict, e.g. torch_dtype={"unet": torch.bfloat16, "default": torch.float32}
2116-
- if potentially override ComponentSpec if passed a different loading field in kwargs, e.g. `repo`,
2120+
- if potentially override ComponentSpec if passed a different loading field in kwargs, e.g. `pretrained_model_name_or_path`,
21172121
`variant`, `revision`, etc.
21182122
"""
21192123

@@ -2377,10 +2381,10 @@ def _component_spec_to_dict(component_spec: ComponentSpec) -> Any:
23772381
- "type_hint": Tuple[str, str]
23782382
Library name and class name of the component. (e.g. ("diffusers", "UNet2DConditionModel"))
23792383
- All loading fields defined by `component_spec.loading_fields()`, typically:
2380-
- "repo": Optional[str]
2381-
The model repository (e.g., "stabilityai/stable-diffusion-xl").
2384+
- "pretrained_model_name_or_path": Optional[str]
2385+
The model pretrained_model_name_or_pathsitory (e.g., "stabilityai/stable-diffusion-xl").
23822386
- "subfolder": Optional[str]
2383-
A subfolder within the repo where this component lives.
2387+
A subfolder within the pretrained_model_name_or_path where this component lives.
23842388
- "variant": Optional[str]
23852389
An optional variant identifier for the model.
23862390
- "revision": Optional[str]
@@ -2397,11 +2401,11 @@ def _component_spec_to_dict(component_spec: ComponentSpec) -> Any:
23972401
Example:
23982402
>>> from diffusers.pipelines.modular_pipeline_utils import ComponentSpec >>> from diffusers import
23992403
UNet2DConditionModel >>> spec = ComponentSpec(
2400-
... name="unet", ... type_hint=UNet2DConditionModel, ... config=None, ... repo="path/to/repo", ...
2404+
... name="unet", ... type_hint=UNet2DConditionModel, ... config=None, ... pretrained_model_name_or_path="path/to/pretrained_model_name_or_path", ...
24012405
subfolder="subfolder", ... variant=None, ... revision=None, ...
24022406
default_creation_method="from_pretrained",
24032407
... ) >>> ModularPipeline._component_spec_to_dict(spec) {
2404-
"type_hint": ("diffusers", "UNet2DConditionModel"), "repo": "path/to/repo", "subfolder": "subfolder",
2408+
"type_hint": ("diffusers", "UNet2DConditionModel"), "pretrained_model_name_or_path": "path/to/pretrained_model_name_or_path", "subfolder": "subfolder",
24052409
"variant": None, "revision": None,
24062410
}
24072411
"""
@@ -2431,10 +2435,10 @@ def _dict_to_component_spec(
24312435
- "type_hint": Tuple[str, str]
24322436
Library name and class name of the component. (e.g. ("diffusers", "UNet2DConditionModel"))
24332437
- All loading fields defined by `component_spec.loading_fields()`, typically:
2434-
- "repo": Optional[str]
2435-
The model repository (e.g., "stabilityai/stable-diffusion-xl").
2438+
- "pretrained_model_name_or_path": Optional[str]
2439+
The model pretrained_model_name_or_pathsitory (e.g., "stabilityai/stable-diffusion-xl").
24362440
- "subfolder": Optional[str]
2437-
A subfolder within the repo where this component lives.
2441+
A subfolder within the pretrained_model_name_or_path where this component lives.
24382442
- "variant": Optional[str]
24392443
An optional variant identifier for the model.
24402444
- "revision": Optional[str]
@@ -2451,10 +2455,10 @@ def _dict_to_component_spec(
24512455
ComponentSpec: A reconstructed ComponentSpec object.
24522456
24532457
Example:
2454-
>>> spec_dict = { ... "type_hint": ("diffusers", "UNet2DConditionModel"), ... "repo":
2458+
>>> spec_dict = { ... "type_hint": ("diffusers", "UNet2DConditionModel"), ... "pretrained_model_name_or_path":
24552459
"stabilityai/stable-diffusion-xl", ... "subfolder": "unet", ... "variant": None, ... "revision": None, ...
24562460
} >>> ModularPipeline._dict_to_component_spec("unet", spec_dict) ComponentSpec(
2457-
name="unet", type_hint=UNet2DConditionModel, config=None, repo="stabilityai/stable-diffusion-xl",
2461+
name="unet", type_hint=UNet2DConditionModel, config=None, pretrained_model_name_or_path="stabilityai/stable-diffusion-xl",
24582462
subfolder="unet", variant=None, revision=None, default_creation_method="from_pretrained"
24592463
)
24602464
"""

0 commit comments

Comments
 (0)