TensorForger commited on
Commit
015a42f
·
verified ·
1 Parent(s): 4f4702e

Steppe Wan 2.1 image upscaling demo (200M 1-step, 2x / chained 4x)

Browse files
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/anime.png filter=lfs diff=lfs merge=lfs -text
37
+ examples/cat.png filter=lfs diff=lfs merge=lfs -text
38
+ examples/cloth.png filter=lfs diff=lfs merge=lfs -text
39
+ examples/leaves.png filter=lfs diff=lfs merge=lfs -text
40
+ examples/portrait.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,38 @@
1
  ---
2
- title: Steppe
3
- emoji: 👁
4
- colorFrom: gray
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
 
 
 
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Steppe Latent Upscaler
3
+ emoji: 🌾
4
+ colorFrom: yellow
5
+ colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
+ python_version: "3.12"
10
+ short_description: Generative 2x / 4x upscaling in Wan 2.1 VAE latent space
11
+ license: mit
12
+ models:
13
+ - TensorForger/Steppe-Wan2.1
14
+ - Wan-AI/Wan2.1-T2V-1.3B-Diffusers
15
+ tags:
16
+ - image-upscaling
17
+ - super-resolution
18
+ - latent-upscaler
19
+ - wan
20
  ---
21
 
22
+ # Steppe latent upscaler (Wan 2.1 VAE)
23
+
24
+ Demo of [Steppe-Wan2.1](https://huggingface.co/TensorForger/Steppe-Wan2.1): a generative 2x latent upscaler for the
25
+ Wan 2.1 VAE (Wan 2.1, Wan 2.2 14B, Qwen-Image, ...). The image is encoded with the Wan 2.1 VAE, upscaled in latent
26
+ space by the 200M single step model and decoded directly by the VAE. 4x chains two 2x passes in latent space.
27
+
28
+ Images only; for video (spatial and 2x frame rate) and the other models use the
29
+ [ComfyUI nodes](https://github.com/TensorForger/ComfyUI-Steppe).
30
+
31
+ Settings (same as the `Steppe Upscale Latent` node):
32
+
33
+ - **hff**: target sharpness / fine detail [0...1]; -1 = the model decides itself. Default 0.9.
34
+ - **guidance**: distilled guidance, 1 = off (default), 2 also works well.
35
+ - **seed**: noise seed (the second 4x pass uses seed + 1).
36
+ - **noise_scale**: initial noise temperature, -1 = trained default (1.0).
37
+
38
+ Example images were generated with Krea 2. License: MIT (Wan 2.1 VAE: Apache-2.0).
__pycache__/app.cpython-312.pyc ADDED
Binary file (13.4 kB). View file
 
app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Steppe Space: generative 2x / chained 4x image upscaling in the Wan 2.1 VAE latent space.
3
+
4
+ image -> Wan 2.1 VAE encode -> Steppe 200M 1-step (once for 2x, twice for 4x) -> Wan 2.1 VAE decode.
5
+ The latents are upscaled directly; no extra denoising pass of a diffusion model is needed.
6
+ """
7
+
8
+ import os
9
+
10
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
11
+
12
+ import spaces # noqa: E402 (must be imported before torch)
13
+
14
+ import math # noqa: E402
15
+ import random # noqa: E402
16
+ import tempfile # noqa: E402
17
+ import time # noqa: E402
18
+
19
+ import gradio as gr # noqa: E402
20
+ import numpy as np # noqa: E402
21
+ import torch # noqa: E402
22
+ import torch.nn.functional as functional # noqa: E402
23
+ from diffusers import AutoencoderKLWan # noqa: E402
24
+ from PIL import Image # noqa: E402
25
+ from steppe import UpscaleSettings, load_upscaler # noqa: E402
26
+
27
+ MODEL_FILE = "steppe_wan_2_1_200M_1step.safetensors"
28
+ VAE_REPOSITORY = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
29
+ MAX_INPUT_PIXELS = 1280 * 1024
30
+ MAX_SEED = 2**31 - 1
31
+ VAE_MULTIPLE = 8
32
+ VAE_TILE = 1024
33
+ VAE_TILE_STRIDE = 896
34
+ FACTORS = {"2x": 1, "4x (2x → 2x)": 2}
35
+
36
+ HFF_INFO = (
37
+ "Target sharpness / fine detail of the result, [0...1]. -1 = no hff, the model decides itself."
38
+ )
39
+ GUIDANCE_INFO = "Distilled guidance (trained on 1-3, no extra cost). 1 = off (default, safe and stable), 2 also works well."
40
+ NOISE_SCALE_INFO = "Initial noise temperature. -1 = trained default (1.0)."
41
+
42
+ upscaler = load_upscaler(MODEL_FILE, dtype=torch.bfloat16)
43
+ upscaler.model.to("cuda")
44
+ vae = AutoencoderKLWan.from_pretrained(VAE_REPOSITORY, subfolder="vae", torch_dtype=torch.float32).to("cuda").eval()
45
+ vae.enable_tiling(VAE_TILE, VAE_TILE, VAE_TILE_STRIDE, VAE_TILE_STRIDE)
46
+
47
+
48
+ def limit_size(image: Image.Image) -> tuple[Image.Image, str]:
49
+ """
50
+ returns:
51
+ image downscaled to at most MAX_INPUT_PIXELS (aspect ratio kept), note for the user ("" if unchanged)
52
+ """
53
+ pixels = image.width * image.height
54
+ if pixels <= MAX_INPUT_PIXELS:
55
+ return image, ""
56
+ scale = math.sqrt(MAX_INPUT_PIXELS / pixels)
57
+ size = (max(1, int(image.width * scale)), max(1, int(image.height * scale)))
58
+ note = f"Input downscaled from {image.width}×{image.height} to {size[0]}×{size[1]} (demo limit {MAX_INPUT_PIXELS / 1e6:.1f} MP). "
59
+ return image.resize(size, Image.LANCZOS), note
60
+
61
+
62
+ def to_pixels(image: Image.Image) -> torch.Tensor:
63
+ """
64
+ returns:
65
+ pixels: [1, 3, 1, H_padded, W_padded], values: [-1...1], replicate padded to a multiple of VAE_MULTIPLE
66
+ """
67
+ array = torch.from_numpy(np.asarray(image, dtype=np.float32) / 127.5 - 1.0)
68
+ pixels = array.permute(2, 0, 1)[None]
69
+ pad_height = -pixels.shape[2] % VAE_MULTIPLE
70
+ pad_width = -pixels.shape[3] % VAE_MULTIPLE
71
+ if pad_height or pad_width:
72
+ pixels = functional.pad(pixels, (0, pad_width, 0, pad_height), mode="replicate")
73
+ return pixels[:, :, None]
74
+
75
+
76
+ def to_image(pixels: torch.Tensor, width: int, height: int) -> Image.Image:
77
+ """
78
+ args:
79
+ pixels: [1, 3, 1, H, W], values: [-1...1]
80
+ """
81
+ array = ((pixels[0, :, 0, :height, :width].float().clamp(-1, 1) + 1.0) * 127.5).round().to(torch.uint8)
82
+ return Image.fromarray(array.permute(1, 2, 0).cpu().numpy())
83
+
84
+
85
+ def estimate_duration(image=None, scale="2x", *args, **kwargs) -> int:
86
+ if image is None:
87
+ return 20
88
+ pixels = min(image.width * image.height, MAX_INPUT_PIXELS)
89
+ passes = FACTORS.get(scale, 1)
90
+ output_megapixels = pixels * 4**passes / 1e6
91
+ return int(min(90, 15 + 2 * output_megapixels))
92
+
93
+
94
+ @spaces.GPU(duration=estimate_duration)
95
+ def upscale(
96
+ image: Image.Image,
97
+ scale: str = "2x",
98
+ hff: float = 0.9,
99
+ guidance: float = 1.0,
100
+ seed: int = 0,
101
+ randomize_seed: bool = True,
102
+ noise_scale: float = -1.0,
103
+ ) -> tuple[tuple[Image.Image, Image.Image], str, int, str]:
104
+ """
105
+ Upscales an image 2x or 4x (two chained 2x passes) with the Steppe generative latent upscaler in the Wan 2.1 VAE
106
+ latent space (encode, upscale the latents in one step, decode).
107
+
108
+ Args:
109
+ image: input image (RGB). Larger than 1.3 MP is downscaled first.
110
+ scale: "2x" or "4x (2x → 2x)".
111
+ hff: target sharpness / fine detail in [0, 1]; -1 lets the model decide.
112
+ guidance: distilled guidance, 1 = off (default), 2 also works well.
113
+ seed: random seed of the generative upscaler (the second 4x pass uses seed + 1).
114
+ randomize_seed: pick a random seed instead of `seed`.
115
+ noise_scale: initial noise temperature, -1 = trained default (1.0).
116
+
117
+ Returns:
118
+ (bicubic, steppe) image pair, path of the full resolution PNG, the used seed, status text.
119
+ """
120
+ if image is None:
121
+ raise gr.Error("Upload an image first.")
122
+ if randomize_seed:
123
+ seed = random.randint(0, MAX_SEED)
124
+ seed = int(seed)
125
+ passes = FACTORS[scale]
126
+ factor = 2**passes
127
+ started = time.perf_counter()
128
+
129
+ image, note = limit_size(image.convert("RGB"))
130
+ width, height = image.size
131
+ with torch.inference_mode():
132
+ latents = vae.encode(to_pixels(image).to("cuda")).latent_dist.mode()
133
+ for index in range(passes):
134
+ settings = UpscaleSettings(
135
+ spatial=True,
136
+ temporal=False,
137
+ hff=None if hff < 0 else float(hff),
138
+ guidance=float(guidance),
139
+ noise_scale=None if noise_scale < 0 else float(noise_scale),
140
+ seed=seed + index,
141
+ )
142
+ latents = upscaler.upscale(latents, settings, device="cuda").to("cuda")
143
+ pixels = vae.decode(latents).sample
144
+ result = to_image(pixels, width * factor, height * factor)
145
+ del latents, pixels
146
+
147
+ bicubic = image.resize(result.size, Image.BICUBIC)
148
+ path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
149
+ result.save(path)
150
+ elapsed = time.perf_counter() - started
151
+ status = f"{note}{width}×{height} → {result.width}×{result.height} ({factor}x) in {elapsed:.1f} s, seed {seed}."
152
+ return (bicubic, result), path, seed, status
153
+
154
+
155
+ CSS = """
156
+ #col-container { max-width: 1200px; margin: 0 auto; }
157
+ .dark .gradio-container { color: var(--body-text-color); }
158
+ """
159
+
160
+ INTRO = """
161
+ # Steppe: generative latent upscaler for Wan 2.1 VAE
162
+
163
+ 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
164
+ directly by the VAE, no extra diffusion pass. Here: image → VAE encode → Steppe 200M 1-step → VAE decode.
165
+ 4x chains two 2x passes in latent space.
166
+
167
+ [Model](https://huggingface.co/TensorForger/Steppe-Wan2.1) · [ComfyUI nodes](https://github.com/TensorForger/ComfyUI-Steppe)
168
+ """
169
+
170
+ EXAMPLES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples")
171
+ EXAMPLES = [
172
+ [os.path.join(EXAMPLES_DIRECTORY, name), scale]
173
+ for name, scale in (
174
+ ("cat.png", "4x (2x → 2x)"),
175
+ ("anime.png", "4x (2x → 2x)"),
176
+ ("portrait.png", "2x"),
177
+ ("cloth.png", "4x (2x → 2x)"),
178
+ ("leaves.png", "2x"),
179
+ )
180
+ ]
181
+
182
+ with gr.Blocks(title="Steppe latent upscaler") as demo:
183
+ with gr.Column(elem_id="col-container"):
184
+ gr.Markdown(INTRO)
185
+ with gr.Row():
186
+ with gr.Column(scale=2):
187
+ input_image = gr.Image(label="Input image", type="pil", image_mode="RGB", height=420)
188
+ scale = gr.Radio(list(FACTORS), value="2x", label="Upscale")
189
+ run = gr.Button("Upscale", variant="primary")
190
+ with gr.Accordion("Settings", open=False):
191
+ hff = gr.Slider(-1.0, 1.0, value=0.9, step=0.01, label="hff", info=HFF_INFO)
192
+ guidance = gr.Slider(1.0, 30.0, value=1.0, step=0.1, label="guidance", info=GUIDANCE_INFO)
193
+ with gr.Row():
194
+ seed = gr.Number(label="seed", value=0, precision=0, minimum=0, maximum=MAX_SEED)
195
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
196
+ noise_scale = gr.Slider(-1.0, 2.0, value=-1.0, step=0.01, label="noise_scale", info=NOISE_SCALE_INFO)
197
+ with gr.Column(scale=3):
198
+ comparison = gr.ImageSlider(label="Bicubic ↔ Steppe", type="pil", format="webp", height=560)
199
+ status = gr.Markdown()
200
+ download = gr.File(label="Full resolution PNG")
201
+
202
+ gr.Examples(
203
+ examples=EXAMPLES,
204
+ inputs=[input_image, scale],
205
+ outputs=[comparison, download, seed, status],
206
+ fn=upscale,
207
+ cache_examples=True,
208
+ cache_mode="lazy",
209
+ )
210
+
211
+ run.click(
212
+ upscale,
213
+ inputs=[input_image, scale, hff, guidance, seed, randomize_seed, noise_scale],
214
+ outputs=[comparison, download, seed, status],
215
+ api_name="upscale",
216
+ )
217
+
218
+ if __name__ == "__main__":
219
+ demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
examples/anime.png ADDED

Git LFS Details

  • SHA256: fda81814c5140143284077342c429727770c90d40034349657c20987ec6c9dbc
  • Pointer size: 132 Bytes
  • Size of remote file: 1.81 MB
examples/cat.png ADDED

Git LFS Details

  • SHA256: 1370ec68ecee561b6016a4a2cb60c5941775d31b7d6cecc38a34deb939cb5cec
  • Pointer size: 132 Bytes
  • Size of remote file: 1.7 MB
examples/cloth.png ADDED

Git LFS Details

  • SHA256: ad71a579d4c1989cd5a589d027f409beed4b4ee944e2cb7cf6c6b480cc98eb98
  • Pointer size: 132 Bytes
  • Size of remote file: 1.87 MB
examples/leaves.png ADDED

Git LFS Details

  • SHA256: d97b5546a63878ea32a8d506d9b961d2eeb1426b9dba539e71affda1f7d1ca3b
  • Pointer size: 131 Bytes
  • Size of remote file: 907 kB
examples/portrait.png ADDED

Git LFS Details

  • SHA256: 5508271bfb20e1ea951581074eeed5cbf1dbc1f0b7f354f12816c73d86b885e1
  • Pointer size: 132 Bytes
  • Size of remote file: 1.52 MB
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ diffusers>=0.35
2
+ steppe @ git+https://github.com/tensorforger/ComfyUI-Steppe@0b37bf6b6aa6f4fcb45461b4b5fd8226aeecf121