File size: 13,026 Bytes
015a42f
abdc2b0
015a42f
abdc2b0
015a42f
 
 
 
 
 
 
 
 
 
 
 
 
abdc2b0
 
015a42f
 
 
 
 
abdc2b0
015a42f
abdc2b0
015a42f
 
 
 
abdc2b0
 
015a42f
 
 
 
 
 
 
abdc2b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
015a42f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abdc2b0
015a42f
 
abdc2b0
015a42f
 
 
abdc2b0
 
015a42f
 
abdc2b0
015a42f
 
 
 
 
abdc2b0
015a42f
abdc2b0
015a42f
 
 
 
 
 
 
 
 
abdc2b0
015a42f
 
 
 
 
 
 
 
 
 
 
abdc2b0
015a42f
 
abdc2b0
 
015a42f
 
 
 
 
 
 
 
 
abdc2b0
015a42f
 
 
 
 
 
 
 
 
abdc2b0
 
 
015a42f
 
 
 
 
 
 
abdc2b0
015a42f
 
 
 
 
 
 
 
 
abdc2b0
 
015a42f
 
 
 
 
 
 
abdc2b0
015a42f
 
 
abdc2b0
 
 
 
 
015a42f
 
 
 
 
 
abdc2b0
 
 
 
015a42f
abdc2b0
 
015a42f
abdc2b0
 
 
015a42f
abdc2b0
015a42f
 
 
abdc2b0
 
 
 
 
 
 
 
015a42f
 
 
 
 
 
 
 
 
 
abdc2b0
015a42f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abdc2b0
015a42f
abdc2b0
015a42f
 
 
 
 
 
abdc2b0
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
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
302
303
304
305
"""
Steppe Space: generative 2x / chained 4x image upscaling in the FLUX.2 VAE (default) or Wan 2.1 VAE latent space.

image -> VAE encode -> Steppe 200M 1-step of that latent space (once for 2x, twice for 4x) -> 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
from dataclasses import dataclass  # noqa: E402
from typing import Callable  # 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 AutoencoderKLFlux2, AutoencoderKLWan  # noqa: E402
from PIL import Image  # noqa: E402
from steppe import LATENT_SPACES, SteppeUpscaler, UpscaleSettings, load_upscaler  # noqa: E402

MAX_INPUT_PIXELS = 1280 * 1024
MAX_SEED = 2**31 - 1
FACTORS = {"2x": 1, "4x (2x β†’ 2x)": 2}
FLUX_2 = "FLUX.2 VAE"
WAN_2_1 = "Wan 2.1 VAE"

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)."


@dataclass
class Backend:
    """
    A VAE latent space with its Steppe model.
    encode: pixels [1, 3, H, W] (values [-1...1], H and W multiples of `multiple`) -> latents as Steppe expects them
    decode: latents -> pixels [1, 3, H, W], values [-1...1]
    """

    upscaler: SteppeUpscaler
    encode: Callable[[torch.Tensor], torch.Tensor]
    decode: Callable[[torch.Tensor], torch.Tensor]
    multiple: int


def load_wan_2_1() -> Backend:
    """
    Wan 2.1 VAE: raw latents [1, 16, 1, H / 8, W / 8], fp32 VAE with tiling as in the first version of the Space.
    """
    upscaler = load_upscaler("steppe_wan_2_1_200M_1step.safetensors", dtype=torch.bfloat16)
    upscaler.model.to("cuda")
    repository = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
    vae = AutoencoderKLWan.from_pretrained(repository, subfolder="vae", torch_dtype=torch.float32).to("cuda").eval()
    vae.enable_tiling(1024, 1024, 896, 896)

    def encode(pixels: torch.Tensor) -> torch.Tensor:
        return vae.encode(pixels[:, :, None].float()).latent_dist.mode()

    def decode(latents: torch.Tensor) -> torch.Tensor:
        return vae.decode(latents.to("cuda", torch.float32)).sample[:, :, 0]

    return Backend(upscaler, encode, decode, 8)


def load_flux_2() -> Backend:
    """
    FLUX.2 VAE (Apache-2.0 copy in FLUX.2 [klein] 4B, identical for all FLUX.2 models): latents 2x2 packed to
    [1, 128, H / 16, W / 16] and batch norm normalized with the VAE's running statistics, as the diffusers FLUX.2
    pipelines and ComfyUI hand them over. bf16 VAE as in the benchmark. Decoded in one piece: the diffusers tiled
    decode costs ~3 dB PSNR with this VAE (per tile group norm / attention statistics). The largest output
    (5120 x 4096) needs ~45 GB, which ZeroGPU has; tiles of 2048 px are only a fallback when the memory runs out.
    """
    upscaler = load_upscaler("steppe_flux_2_200M_1step.safetensors", dtype=torch.bfloat16)
    upscaler.model.to("cuda")
    repository = "black-forest-labs/FLUX.2-klein-4B"
    vae = AutoencoderKLFlux2.from_pretrained(repository, subfolder="vae", torch_dtype=torch.bfloat16).to("cuda").eval()
    mean = vae.bn.running_mean.float()[None, :, None, None]
    std = torch.sqrt(vae.bn.running_var.float() + vae.config.batch_norm_eps)[None, :, None, None]
    space = LATENT_SPACES["flux_2"]

    def encode(pixels: torch.Tensor) -> torch.Tensor:
        latents = vae.encode(pixels.to(torch.bfloat16)).latent_dist.mode().float()
        return (space.pack(latents[:, :, None])[:, :, 0] - mean) / std

    def decode(latents: torch.Tensor) -> torch.Tensor:
        latents = space.unpack((latents.to("cuda", torch.float32) * std + mean)[:, :, None])[:, :, 0]
        latents = latents.to(torch.bfloat16)
        try:
            return vae.decode(latents).sample.float()
        except torch.OutOfMemoryError:
            torch.cuda.empty_cache()
            vae.enable_tiling()
            vae.tile_sample_min_size = 2048
            vae.tile_latent_min_size = 2048 // 8
            try:
                return vae.decode(latents).sample.float()
            finally:
                vae.disable_tiling()

    return Backend(upscaler, encode, decode, 16)


BACKENDS = {FLUX_2: load_flux_2(), WAN_2_1: load_wan_2_1()}


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, multiple: int) -> torch.Tensor:
    """
    returns:
        pixels: [1, 3, H_padded, W_padded], values: [-1...1], replicate padded to a multiple of `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] % multiple
    pad_width = -pixels.shape[3] % multiple
    if pad_height or pad_width:
        pixels = functional.pad(pixels, (0, pad_width, 0, pad_height), mode="replicate")
    return pixels


def to_image(pixels: torch.Tensor, width: int, height: int) -> Image.Image:
    """
    args:
        pixels: [1, 3, H, W], values: [-1...1]
    """
    array = ((pixels[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, 15 + 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,
    latent_space: str = FLUX_2,
) -> 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 FLUX.2 VAE
    or 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).
        latent_space: "FLUX.2 VAE" (default, best quality) or "Wan 2.1 VAE"; the VAE and Steppe model to use.

    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)
    if latent_space not in BACKENDS:
        raise gr.Error(f"Unknown latent space {latent_space!r}, choose one of: {', '.join(BACKENDS)}.")
    backend = BACKENDS[latent_space]
    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 = backend.encode(to_pixels(image, backend.multiple).to("cuda"))
        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 = backend.upscaler.upscale(latents, settings, device="cuda").to("cuda")
        pixels = backend.decode(latents)
    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, {latent_space}) in {elapsed:.1f} s, seed {seed}."
    return (bicubic, result), path, seed, status


def upscale_example(image: Image.Image, scale: str, latent_space: str):
    """Examples pass only image, scale and latent space; the other settings keep their defaults."""
    return upscale(image, scale, latent_space=latent_space)


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

INTRO = """
# Steppe: generative latent upscalers for FLUX.2 VAE and Wan 2.1 VAE

2x upscaling of VAE latents 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.

- **FLUX.2 VAE** (default, best quality): FLUX.2 [dev] / [klein], MOSS-Image, ...
- **Wan 2.1 VAE**: Wan 2.1, Wan 2.2 14B, Qwen-Image, Krea 2, ...

Models: [Steppe-Flux.2](https://huggingface.co/TensorForger/Steppe-Flux.2) Β·
[Steppe-Wan2.1](https://huggingface.co/TensorForger/Steppe-Wan2.1) Β·
[ComfyUI nodes](https://github.com/TensorForger/ComfyUI-Steppe)
"""
LATENT_SPACE_INFO = "VAE whose latent space is upscaled, with its Steppe model. FLUX.2 gives the best quality."

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

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")
                latent_space = gr.Radio(list(BACKENDS), value=FLUX_2, label="VAE latent space", info=LATENT_SPACE_INFO)
                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, latent_space],
            outputs=[comparison, download, seed, status],
            fn=upscale_example,
            cache_examples=True,
            cache_mode="lazy",
        )

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

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