File size: 8,838 Bytes
015a42f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cec087
015a42f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Steppe Space: generative 2x / chained 4x image upscaling in the Wan 2.1 VAE latent space.

image -> Wan 2.1 VAE encode -> Steppe 200M 1-step (once for 2x, twice for 4x) -> Wan 2.1 VAE decode.
The latents are upscaled directly; no extra denoising pass of a diffusion model is needed.
"""

import os

os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

import spaces  # noqa: E402  (must be imported before torch)

import math  # noqa: E402
import random  # noqa: E402
import tempfile  # noqa: E402
import time  # noqa: E402

import gradio as gr  # noqa: E402
import numpy as np  # noqa: E402
import torch  # noqa: E402
import torch.nn.functional as functional  # noqa: E402
from diffusers import AutoencoderKLWan  # noqa: E402
from PIL import Image  # noqa: E402
from steppe import UpscaleSettings, load_upscaler  # noqa: E402

MODEL_FILE = "steppe_wan_2_1_200M_1step.safetensors"
VAE_REPOSITORY = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
MAX_INPUT_PIXELS = 1280 * 1024
MAX_SEED = 2**31 - 1
VAE_MULTIPLE = 8
VAE_TILE = 1024
VAE_TILE_STRIDE = 896
FACTORS = {"2x": 1, "4x (2x β†’ 2x)": 2}

HFF_INFO = (
    "Target sharpness / fine detail of the result, [0...1]. -1 = no hff, the model decides itself."
)
GUIDANCE_INFO = "Distilled guidance (trained on 1-3, no extra cost). 1 = off (default, safe and stable), 2 also works well."
NOISE_SCALE_INFO = "Initial noise temperature. -1 = trained default (1.0)."

upscaler = load_upscaler(MODEL_FILE, dtype=torch.bfloat16)
upscaler.model.to("cuda")
vae = AutoencoderKLWan.from_pretrained(VAE_REPOSITORY, subfolder="vae", torch_dtype=torch.float32).to("cuda").eval()
vae.enable_tiling(VAE_TILE, VAE_TILE, VAE_TILE_STRIDE, VAE_TILE_STRIDE)


def limit_size(image: Image.Image) -> tuple[Image.Image, str]:
    """
    returns:
        image downscaled to at most MAX_INPUT_PIXELS (aspect ratio kept), note for the user ("" if unchanged)
    """
    pixels = image.width * image.height
    if pixels <= MAX_INPUT_PIXELS:
        return image, ""
    scale = math.sqrt(MAX_INPUT_PIXELS / pixels)
    size = (max(1, int(image.width * scale)), max(1, int(image.height * scale)))
    note = f"Input downscaled from {image.width}Γ—{image.height} to {size[0]}Γ—{size[1]} (demo limit {MAX_INPUT_PIXELS / 1e6:.1f} MP). "
    return image.resize(size, Image.LANCZOS), note


def to_pixels(image: Image.Image) -> torch.Tensor:
    """
    returns:
        pixels: [1, 3, 1, H_padded, W_padded], values: [-1...1], replicate padded to a multiple of VAE_MULTIPLE
    """
    array = torch.from_numpy(np.asarray(image, dtype=np.float32) / 127.5 - 1.0)
    pixels = array.permute(2, 0, 1)[None]
    pad_height = -pixels.shape[2] % VAE_MULTIPLE
    pad_width = -pixels.shape[3] % VAE_MULTIPLE
    if pad_height or pad_width:
        pixels = functional.pad(pixels, (0, pad_width, 0, pad_height), mode="replicate")
    return pixels[:, :, None]


def to_image(pixels: torch.Tensor, width: int, height: int) -> Image.Image:
    """
    args:
        pixels: [1, 3, 1, H, W], values: [-1...1]
    """
    array = ((pixels[0, :, 0, :height, :width].float().clamp(-1, 1) + 1.0) * 127.5).round().to(torch.uint8)
    return Image.fromarray(array.permute(1, 2, 0).cpu().numpy())


def estimate_duration(image=None, scale="2x", *args, **kwargs) -> int:
    if image is None:
        return 20
    pixels = min(image.width * image.height, MAX_INPUT_PIXELS)
    passes = FACTORS.get(scale, 1)
    output_megapixels = pixels * 4**passes / 1e6
    return int(min(60, 10 + output_megapixels))


@spaces.GPU(duration=estimate_duration)
def upscale(
    image: Image.Image,
    scale: str = "2x",
    hff: float = 0.9,
    guidance: float = 1.0,
    seed: int = 0,
    randomize_seed: bool = True,
    noise_scale: float = -1.0,
) -> tuple[tuple[Image.Image, Image.Image], str, int, str]:
    """
    Upscales an image 2x or 4x (two chained 2x passes) with the Steppe generative latent upscaler in the Wan 2.1 VAE
    latent space (encode, upscale the latents in one step, decode).

    Args:
        image: input image (RGB). Larger than 1.3 MP is downscaled first.
        scale: "2x" or "4x (2x β†’ 2x)".
        hff: target sharpness / fine detail in [0, 1]; -1 lets the model decide.
        guidance: distilled guidance, 1 = off (default), 2 also works well.
        seed: random seed of the generative upscaler (the second 4x pass uses seed + 1).
        randomize_seed: pick a random seed instead of `seed`.
        noise_scale: initial noise temperature, -1 = trained default (1.0).

    Returns:
        (bicubic, steppe) image pair, path of the full resolution PNG, the used seed, status text.
    """
    if image is None:
        raise gr.Error("Upload an image first.")
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    seed = int(seed)
    passes = FACTORS[scale]
    factor = 2**passes
    started = time.perf_counter()

    image, note = limit_size(image.convert("RGB"))
    width, height = image.size
    with torch.inference_mode():
        latents = vae.encode(to_pixels(image).to("cuda")).latent_dist.mode()
        for index in range(passes):
            settings = UpscaleSettings(
                spatial=True,
                temporal=False,
                hff=None if hff < 0 else float(hff),
                guidance=float(guidance),
                noise_scale=None if noise_scale < 0 else float(noise_scale),
                seed=seed + index,
            )
            latents = upscaler.upscale(latents, settings, device="cuda").to("cuda")
        pixels = vae.decode(latents).sample
    result = to_image(pixels, width * factor, height * factor)
    del latents, pixels

    bicubic = image.resize(result.size, Image.BICUBIC)
    path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    result.save(path)
    elapsed = time.perf_counter() - started
    status = f"{note}{width}Γ—{height} β†’ {result.width}Γ—{result.height} ({factor}x) in {elapsed:.1f} s, seed {seed}."
    return (bicubic, result), path, seed, status


CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""

INTRO = """
# Steppe: generative latent upscaler for Wan 2.1 VAE

2x upscaling of Wan 2.1 VAE latents (Wan 2.1, Wan 2.2 14B, Qwen-Image, ...) in a single step; the result is decoded
directly by the VAE, no extra diffusion pass. Here: image β†’ VAE encode β†’ Steppe 200M 1-step β†’ VAE decode.
4x chains two 2x passes in latent space.

[Model](https://huggingface.co/TensorForger/Steppe-Wan2.1) Β· [ComfyUI nodes](https://github.com/TensorForger/ComfyUI-Steppe)
"""

EXAMPLES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples")
EXAMPLES = [
    [os.path.join(EXAMPLES_DIRECTORY, name), scale]
    for name, scale in (
        ("cat.png", "4x (2x β†’ 2x)"),
        ("anime.png", "4x (2x β†’ 2x)"),
        ("portrait.png", "2x"),
        ("cloth.png", "4x (2x β†’ 2x)"),
        ("leaves.png", "2x"),
    )
]

with gr.Blocks(title="Steppe latent upscaler") as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(INTRO)
        with gr.Row():
            with gr.Column(scale=2):
                input_image = gr.Image(label="Input image", type="pil", image_mode="RGB", height=420)
                scale = gr.Radio(list(FACTORS), value="2x", label="Upscale")
                run = gr.Button("Upscale", variant="primary")
                with gr.Accordion("Settings", open=False):
                    hff = gr.Slider(-1.0, 1.0, value=0.9, step=0.01, label="hff", info=HFF_INFO)
                    guidance = gr.Slider(1.0, 30.0, value=1.0, step=0.1, label="guidance", info=GUIDANCE_INFO)
                    with gr.Row():
                        seed = gr.Number(label="seed", value=0, precision=0, minimum=0, maximum=MAX_SEED)
                        randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
                    noise_scale = gr.Slider(-1.0, 2.0, value=-1.0, step=0.01, label="noise_scale", info=NOISE_SCALE_INFO)
            with gr.Column(scale=3):
                comparison = gr.ImageSlider(label="Bicubic ↔ Steppe", type="pil", format="webp", height=560)
                status = gr.Markdown()
                download = gr.File(label="Full resolution PNG")

        gr.Examples(
            examples=EXAMPLES,
            inputs=[input_image, scale],
            outputs=[comparison, download, seed, status],
            fn=upscale,
            cache_examples=True,
            cache_mode="lazy",
        )

    run.click(
        upscale,
        inputs=[input_image, scale, hff, guidance, seed, randomize_seed, noise_scale],
        outputs=[comparison, download, seed, status],
        api_name="upscale",
    )

if __name__ == "__main__":
    demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)