File size: 3,309 Bytes
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
"""The SDXL call itself.

Kept deliberately thin: everything that can be reasoned about without a GPU
lives in the sibling modules. What is here is the pipeline invocation, the
resolution arithmetic it demands, and the out-of-memory path.
"""

from __future__ import annotations

import time

import torch
from PIL import Image

import state


def get_processing_size(width: int, height: int, max_dimension: int) -> tuple[int, int]:
    """Fit within max_dimension, rounded to the multiple of 8 the VAE needs."""
    scale = min(1.0, max_dimension / max(width, height))
    sized = []
    for value in (int(round(width * scale)), int(round(height * scale))):
        sized.append(max(64, int(round(value / 8.0)) * 8))
    return sized[0], sized[1]


def describe_vram(tag: str) -> str:
    if not torch.cuda.is_available():
        return f"[VRAM {tag}] cpu"
    return (
        f"[VRAM {tag}] allocated={torch.cuda.memory_allocated() / 1024 ** 3:.2f} GB "
        f"reserved={torch.cuda.memory_reserved() / 1024 ** 3:.2f} GB "
        f"peak={torch.cuda.max_memory_allocated() / 1024 ** 3:.2f} GB"
    )


class RefinementOutOfMemory(RuntimeError):
    """CUDA ran out of memory during a diffusion pass."""


def run_diffusion_pass(
    pipe,
    image: Image.Image,
    mask_image: Image.Image,
    depth_image: Image.Image,
    prompt: str,
    negative_prompt: str,
    profile: dict,
    width: int,
    height: int,
    seed: int,
) -> Image.Image:
    """Run one inpainting pass and return the raw generated image.

    Note that `strength` gates how many of `steps` actually execute, so a
    profile at strength 0.09 costs about two steps, not twenty-four. That is
    why a conservative material is so much cheaper than an aggressive one.
    """
    generator = torch.Generator(device=str(state.device)).manual_seed(seed)
    started = time.perf_counter()

    if torch.cuda.is_available():
        torch.cuda.synchronize()

    try:
        with torch.inference_mode():
            generated = pipe(
                prompt=prompt,
                negative_prompt=negative_prompt,
                image=image,
                mask_image=mask_image,
                control_image=depth_image,
                strength=profile["diffusion_strength"],
                guidance_scale=profile["guidance"],
                controlnet_conditioning_scale=profile["controlnet"],
                control_guidance_start=0.0,
                control_guidance_end=0.65,
                num_inference_steps=profile["steps"],
                height=height,
                width=width,
                generator=generator,
            ).images[0]
    except torch.cuda.OutOfMemoryError as exc:
        torch.cuda.empty_cache()
        raise RefinementOutOfMemory(
            f"CUDA out of memory at {width}x{height}. Lower refine.max_dimension "
            f"(try 768), or set refine.cpu_offload = true to trade speed for VRAM."
        ) from exc

    if torch.cuda.is_available():
        torch.cuda.synchronize()

    print(
        f"[REFINE] diffusion pass {width}x{height} "
        f"strength={profile['diffusion_strength']} steps={profile['steps']} "
        f"took {time.perf_counter() - started:.2f}s",
        flush=True,
    )
    print(describe_vram("after pass"), flush=True)
    return generated