1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
|
"""Lazy Diffusers construction kept outside the MCP layer."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from .config import AppConfig
from .errors import ConfigError
class PipelineFactory:
"""Build SD1.x pipelines in FP16 without network access."""
def __init__(self, config: AppConfig) -> None:
self.config = config
@staticmethod
def _runtime() -> tuple[Any, Any]:
try:
import diffusers
import torch
except ImportError as exc:
raise ConfigError(f"inference dependency is unavailable: {exc}") from exc
if not torch.cuda.is_available():
raise ConfigError("CUDA GPU is required but torch.cuda.is_available() is false")
return torch, diffusers
def create_base(self) -> Any:
torch, diffusers = self._runtime()
cache_dir = str(self.config.model.root / "huggingface")
try:
pipeline = diffusers.StableDiffusionPipeline.from_single_file(
str(self.config.model.checkpoint_path()),
torch_dtype=torch.float16,
local_files_only=True,
cache_dir=cache_dir,
)
vae_path = self.config.model.vae_path()
if vae_path is not None:
# from_single_file needs a Diffusers config directory to avoid
# network access. Reuse the VAE config that the base pipeline
# already resolved from the local huggingface cache.
vae_config_dir = self._vae_config_dir(cache_dir)
pipeline.vae = diffusers.AutoencoderKL.from_single_file(
str(vae_path),
torch_dtype=torch.float16,
local_files_only=True,
cache_dir=cache_dir,
config=vae_config_dir,
)
if getattr(pipeline, "vae", None) is None:
raise ConfigError(
"the checkpoint does not provide a VAE and no external VAE was loaded"
)
adapter_names: list[str] = []
adapter_weights: list[float] = []
for index, (item, path) in enumerate(
zip(self.config.model.loras, self.config.model.lora_paths(), strict=True)
):
name = f"configured_lora_{index}"
pipeline.load_lora_weights(
str(path.parent),
weight_name=path.name,
adapter_name=name,
local_files_only=True,
)
adapter_names.append(name)
adapter_weights.append(item.weight)
if adapter_names:
pipeline.set_adapters(adapter_names, adapter_weights=adapter_weights)
pipeline.scheduler = self._create_scheduler(pipeline.scheduler, diffusers)
pipeline.set_progress_bar_config(disable=True)
return pipeline.to("cuda")
except ConfigError:
raise
except Exception as exc:
raise ConfigError(f"failed to load SD1.x model configuration: {exc}") from exc
def create_controlnet(self, path: Path) -> Any:
torch, diffusers = self._runtime()
try:
return diffusers.ControlNetModel.from_single_file(
str(path),
torch_dtype=torch.float16,
local_files_only=True,
cache_dir=str(self.config.model.root / "huggingface"),
).to("cuda")
except Exception as exc:
raise ConfigError(f"failed to load ControlNet model {path}: {exc}") from exc
@staticmethod
def create_guided_pipeline(base: Any, controlnet: Any) -> Any:
from diffusers.pipelines.controlnet.pipeline_controlnet import (
StableDiffusionControlNetPipeline,
)
components: dict[str, Any] = dict(
vae=base.vae,
text_encoder=base.text_encoder,
tokenizer=base.tokenizer,
unet=base.unet,
controlnet=controlnet,
scheduler=base.scheduler,
safety_checker=base.safety_checker,
feature_extractor=base.feature_extractor,
requires_safety_checker=getattr(base, "requires_safety_checker", False),
)
if getattr(base, "image_encoder", None) is not None:
components["image_encoder"] = base.image_encoder
pipeline = StableDiffusionControlNetPipeline(**components)
pipeline.set_progress_bar_config(disable=True)
return pipeline.to("cuda")
@staticmethod
def create_inpaint_pipeline(base: Any, controlnet: Any) -> Any:
from diffusers.pipelines.controlnet.pipeline_controlnet_inpaint import (
StableDiffusionControlNetInpaintPipeline,
)
components: dict[str, Any] = dict(
vae=base.vae,
text_encoder=base.text_encoder,
tokenizer=base.tokenizer,
unet=base.unet,
controlnet=controlnet,
scheduler=base.scheduler,
safety_checker=base.safety_checker,
feature_extractor=base.feature_extractor,
requires_safety_checker=getattr(base, "requires_safety_checker", False),
)
if getattr(base, "image_encoder", None) is not None:
components["image_encoder"] = base.image_encoder
pipeline = StableDiffusionControlNetInpaintPipeline(**components)
pipeline.set_progress_bar_config(disable=True)
return pipeline.to("cuda")
def _create_scheduler(self, current: Any, diffusers: Any) -> Any:
name = self.config.generation.scheduler
if name == "dpmpp_2m_karras":
return diffusers.DPMSolverMultistepScheduler.from_config(
current.config,
algorithm_type="dpmsolver++",
solver_order=2,
use_karras_sigmas=True,
)
if name == "dpmpp_2m_sde_karras":
return diffusers.DPMSolverMultistepScheduler.from_config(
current.config,
algorithm_type="sde-dpmsolver++",
solver_order=2,
use_karras_sigmas=True,
)
if name == "ddim_trailing":
return diffusers.DDIMScheduler.from_config(
current.config,
timestep_spacing="trailing",
)
classes = {
"euler_a": diffusers.EulerAncestralDiscreteScheduler,
"ddim": diffusers.DDIMScheduler,
"lcm": diffusers.LCMScheduler,
}
try:
scheduler_class = classes[name]
except KeyError as exc:
raise ConfigError(f"unsupported scheduler: {name}") from exc
return scheduler_class.from_config(current.config)
@staticmethod
def _vae_config_dir(cache_dir: str) -> str:
"""Find the VAE config.json inside the local huggingface cache."""
snapshots = (
Path(cache_dir) / "models--stable-diffusion-v1-5--stable-diffusion-v1-5" / "snapshots"
)
if not snapshots.is_dir():
raise ConfigError(
"cannot locate VAE config: huggingface cache snapshots directory not found"
)
for snapshot in snapshots.iterdir():
vae_dir = snapshot / "vae"
if (vae_dir / "config.json").is_file():
return str(vae_dir)
raise ConfigError("cannot locate VAE config.json in the local huggingface cache")
|