summaryrefslogtreecommitdiff
path: root/src/mcp_sd15/pipeline_factory.py
blob: 12d95ba48564d4627107846a590f5b4d6b2ed7b6 (plain)
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
"""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:
                pipeline.vae = diffusers.AutoencoderKL.from_single_file(
                    str(vae_path),
                    torch_dtype=torch.float16,
                    local_files_only=True,
                    cache_dir=cache_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._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 _scheduler(self, scheduler: Any, diffusers: Any) -> Any:
        classes = {
            "dpmpp_2m": diffusers.DPMSolverMultistepScheduler,
            "ddim": diffusers.DDIMScheduler,
            "euler": diffusers.EulerDiscreteScheduler,
            "euler_a": diffusers.EulerAncestralDiscreteScheduler,
        }
        options = dict(scheduler.config)
        if self.config.generation.scheduler == "dpmpp_2m":
            options.update(algorithm_type="dpmsolver++", solver_order=2)
        return classes[self.config.generation.scheduler].from_config(options)