File size: 10,272 Bytes
73828b3
c97431f
73828b3
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b267904
 
 
 
 
 
 
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73828b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
"""Lazy model loading, warm-start, and GPU swap logic."""

import gc
import time

import torch

import state
from config.models import (
    ONEFORMER_MODEL_NAME,
    DEPTH_MODEL_NAME,
    GEOMETRY_MODEL,
    MOGE_MODEL_NAME,
    SAM2_MODEL_CFG,
    SAM2_CHECKPOINT,
    SAM2_MODEL_NAME,
    INTRINSIC_MODEL_VERSION,
)
from config.runtime import (
    ENABLE_MOGE_GEOMETRY,
    ENABLE_SAM_REFINEMENT,
    ENABLE_DEPTH_ESTIMATION,
    ENABLE_INTRINSIC_SHADING,
    ENABLE_SHADING_TRANSFER,
    WARM_START_MODELS,
)
from transformers import (
    AutoImageProcessor,
    AutoModelForDepthEstimation,
    OneFormerForUniversalSegmentation,
    OneFormerProcessor,
)


def _load_segmentation_model():
    if state.seg_processor is not None and state.seg_model is not None:
        return

    print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...", flush=True)
    state.seg_processor = OneFormerProcessor.from_pretrained(
        ONEFORMER_MODEL_NAME,
        local_files_only=state.hf_offline(),
    )
    state.seg_model = OneFormerForUniversalSegmentation.from_pretrained(
        ONEFORMER_MODEL_NAME,
        local_files_only=state.hf_offline(),
    ).to(state.device)
    state.seg_model.eval()
    print("OneFormer loaded.", flush=True)


def _load_intrinsic_model():
    if ENABLE_INTRINSIC_SHADING and state.intrinsic_models is None:
        try:
            print(f"Loading Intrinsic Image Decomposition model: {INTRINSIC_MODEL_VERSION} ...", flush=True)
            from intrinsic.pipeline import load_models
            state.intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(state.device))
            print("Intrinsic model loaded.", flush=True)
        except Exception as exc:
            print(f"Intrinsic model failed to load ({exc}). Falling back to luminance shading.", flush=True)


def _load_depth_model() -> bool:
    if not ENABLE_DEPTH_ESTIMATION:
        return False
    if state.depth_processor is not None and state.depth_model is not None:
        return True

    print(f"Loading depth model: {DEPTH_MODEL_NAME} ...", flush=True)
    state.depth_processor = AutoImageProcessor.from_pretrained(
        DEPTH_MODEL_NAME,
        local_files_only=state.hf_offline(),
    )
    state.depth_model = AutoModelForDepthEstimation.from_pretrained(
        DEPTH_MODEL_NAME,
        local_files_only=state.hf_offline(),
    ).to(state.device)
    state.depth_model.eval()
    print("Depth model loaded.", flush=True)
    return True


def _load_moge_model() -> bool:
    if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda":
        return False
    if state.moge_model is not None:
        return True

    print(f"Loading MoGe geometry model: {MOGE_MODEL_NAME} ...", flush=True)
    from moge.model.v2 import MoGeModel
    state.moge_model = MoGeModel.from_pretrained(MOGE_MODEL_NAME).to(state.device)
    state.moge_model.eval()
    print("MoGe geometry model loaded.", flush=True)
    return True


def _load_sam2_predictor():
    if not ENABLE_SAM_REFINEMENT:
        return None
    if state.sam2_predictor is not None:
        return state.sam2_predictor
    try:
        from sam2.sam2_image_predictor import SAM2ImagePredictor

        if SAM2_MODEL_CFG and SAM2_CHECKPOINT:
            from sam2.build_sam import build_sam2

            model = build_sam2(SAM2_MODEL_CFG, SAM2_CHECKPOINT, device=str(state.device))
            model.eval()
            state.sam2_predictor = SAM2ImagePredictor(model)
        else:
            state.sam2_predictor = SAM2ImagePredictor.from_pretrained(SAM2_MODEL_NAME)
            if hasattr(state.sam2_predictor, "model"):
                state.sam2_predictor.model.to(state.device)
                state.sam2_predictor.model.eval()
        print("SAM2 refinement model loaded.", flush=True)
        return state.sam2_predictor
    except Exception as exc:
        print(f"SAM2 refinement unavailable ({exc}).", flush=True)
        if state.device.type == "cuda":
            torch.cuda.empty_cache()
        return None


def warm_start_models():
    if not WARM_START_MODELS:
        print("Model warm start disabled; models will load on first use.", flush=True)
        return

    t_start = time.perf_counter()
    print(f"Warm-starting visualizer models on {state.device} ...", flush=True)

    # Try ONNX sessions first
    from config.runtime import ENABLE_ONNX_INFERENCE
    if ENABLE_ONNX_INFERENCE:
        from models.onnx_loader import load_seg_onnx_session, load_depth_onnx_session
        load_seg_onnx_session()
        load_depth_onnx_session()

    _load_segmentation_model()

    moge_loaded = False
    if ENABLE_MOGE_GEOMETRY and GEOMETRY_MODEL == "moge":
        try:
            moge_loaded = _load_moge_model()
        except Exception as exc:
            print(f"MoGe warm start skipped ({exc}); depth fallback may be used.", flush=True)
            if state.device.type == "cuda":
                torch.cuda.empty_cache()

    if ENABLE_DEPTH_ESTIMATION and not moge_loaded:
        try:
            _load_depth_model()
        except Exception as exc:
            print(f"Depth model warm start skipped ({exc}); depth will be retried on first use.", flush=True)
            if state.device.type == "cuda":
                torch.cuda.empty_cache()

    if ENABLE_SAM_REFINEMENT:
        _load_sam2_predictor()

    if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
        _load_intrinsic_model()

    print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True)


# --- GPU swapping between the CV models and SDXL ---------------------------
# OneFormer, MoGe and Depth-Anything together hold roughly 3.5 GB in fp32;
# SDXL plus its depth ControlNet holds roughly 9.5 GB in fp16. On a 16 GB card
# the two sets do not co-reside with room left for SDXL's activations. They do
# not need to: refinement only ever runs after a conversion has finished, so
# the CV models are idle at exactly the moment SDXL wants the GPU.
#
# Reloading is cheap to arrange because every _load_* function above already
# guards on "is not None", so the next conversion warm-starts them back with
# no extra plumbing.

_CV_MODEL_ATTRIBUTES = (
    "seg_processor",
    "seg_model",
    "depth_processor",
    "depth_model",
    "moge_model",
    "sam2_predictor",
    "intrinsic_models",
)


def _release(*attributes: str) -> list[str]:
    released = [name for name in attributes if getattr(state, name, None) is not None]
    for name in released:
        setattr(state, name, None)
    gc.collect()
    if state.device.type == "cuda":
        torch.cuda.empty_cache()
    return released


def unload_cv_models() -> list[str]:
    """Free the segmentation/geometry/depth models so SDXL can have the GPU."""
    released = _release(*_CV_MODEL_ATTRIBUTES)
    if released:
        print(f"[REFINE] Unloaded CV models to free GPU: {', '.join(released)}", flush=True)
    return released


def unload_diffusion_pipeline() -> list[str]:
    """Free SDXL so the CV models can have the GPU back."""
    released = _release("diffusion_pipe", "diffusion_controlnet")
    if released:
        print("[REFINE] Unloaded SDXL pipeline.", flush=True)
    return released


def _from_pretrained_with_fp16_fallback(loader, model_name: str, **kwargs):
    """Prefer the fp16 weight variant, falling back to the default weights.

    Not every mirror publishes an fp16 variant, and the failure surfaces as
    OSError or ValueError rather than something more specific.
    """
    if state.device.type == "cuda":
        try:
            return loader.from_pretrained(model_name, variant="fp16", **kwargs)
        except (OSError, ValueError):
            pass
    return loader.from_pretrained(model_name, **kwargs)


def load_diffusion_pipeline():
    """Load SDXL inpainting + depth ControlNet, or return the cached pipeline."""
    if state.diffusion_pipe is not None:
        return state.diffusion_pipe

    from diffusers import (
        ControlNetModel,
        DPMSolverMultistepScheduler,
        StableDiffusionXLControlNetInpaintPipeline,
    )
    from config.refine import (
        REFINE_BASE_MODEL,
        REFINE_CONTROLNET_MODEL,
        REFINE_CPU_OFFLOAD,
    )

    t_start = time.perf_counter()
    dtype = torch.float16 if state.device.type == "cuda" else torch.float32
    shared = {
        "torch_dtype": dtype,
        "use_safetensors": True,
        "low_cpu_mem_usage": True,
        "local_files_only": state.hf_offline(),
    }

    print(f"Loading ControlNet: {REFINE_CONTROLNET_MODEL} ...", flush=True)
    controlnet = _from_pretrained_with_fp16_fallback(
        ControlNetModel, REFINE_CONTROLNET_MODEL, **shared,
    )

    print(f"Loading SDXL inpainting: {REFINE_BASE_MODEL} ...", flush=True)
    pipe = _from_pretrained_with_fp16_fallback(
        StableDiffusionXLControlNetInpaintPipeline,
        REFINE_BASE_MODEL,
        controlnet=controlnet,
        **shared,
    )

    pipe.scheduler = DPMSolverMultistepScheduler.from_config(
        pipe.scheduler.config, use_karras_sigmas=True,
    )

    # Slicing and tiling trade a little speed for a lot of VAE peak memory,
    # which is where a full-resolution decode would otherwise spike.
    if hasattr(pipe.vae, "enable_slicing"):
        pipe.vae.enable_slicing()
    if hasattr(pipe.vae, "enable_tiling"):
        pipe.vae.enable_tiling()

    try:
        pipe.enable_xformers_memory_efficient_attention()
        print("xFormers attention enabled.", flush=True)
    except Exception:
        print("xFormers not available; using default attention.", flush=True)

    if REFINE_CPU_OFFLOAD and state.device.type == "cuda":
        pipe.enable_model_cpu_offload()
        print("SDXL CPU offload enabled (lower VRAM, slower).", flush=True)
    else:
        pipe = pipe.to(state.device)
        if state.device.type == "cuda":
            for module in (pipe.unet, pipe.controlnet):
                try:
                    module.to(memory_format=torch.channels_last)
                except Exception:
                    pass

    state.diffusion_controlnet = controlnet
    state.diffusion_pipe = pipe
    print(f"[TIMING] SDXL pipeline load took {time.perf_counter() - t_start:.3f} seconds", flush=True)
    return pipe