Spaces:
Running
on
Zero
Running
on
Zero
zRzRzRzRzRzRzR
commited on
Commit
·
f0ae490
1
Parent(s):
fff6dc8
init
Browse files- README.md +8 -22
- app.py +253 -472
- example_images/beach.png +0 -0
- example_images/camping.png +0 -0
- example_images/street.png +0 -0
- example_videos/horse.mp4 +0 -3
- example_videos/kitten.mp4 +0 -0
- example_videos/train_running.mp4 +0 -0
- requirements.txt +4 -19
- rife/IFNet.py +0 -123
- rife/IFNet_2R.py +0 -123
- rife/IFNet_HDv3.py +0 -138
- rife/IFNet_m.py +0 -127
- rife/RIFE.py +0 -95
- rife/RIFE_HDv3.py +0 -86
- rife/__init__.py +0 -0
- rife/laplacian.py +0 -69
- rife/loss.py +0 -130
- rife/pytorch_msssim/__init__.py +0 -203
- rife/refine.py +0 -107
- rife/refine_2R.py +0 -104
- rife/warplayer.py +0 -34
- rife_model.py +0 -129
- utils.py +0 -221
README.md
CHANGED
@@ -1,37 +1,23 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
colorFrom: yellow
|
5 |
colorTo: blue
|
6 |
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
suggested_hardware: l40sx1
|
9 |
suggested_storage: large
|
10 |
app_port: 7860
|
11 |
app_file: app.py
|
12 |
models:
|
13 |
-
- THUDM/
|
14 |
tags:
|
15 |
-
-
|
16 |
-
-
|
17 |
-
|
18 |
-
short_description: Text-to-Video
|
19 |
disable_embedding: false
|
20 |
---
|
21 |
|
22 |
-
# Gradio Composite Demo
|
23 |
-
|
24 |
-
This Gradio demo integrates the CogVideoX-5B model, allowing you to perform video inference directly in your browser. It
|
25 |
-
supports features like UpScale, RIFE, and other functionalities.
|
26 |
-
|
27 |
-
## Environment Setup
|
28 |
-
|
29 |
-
Set the following environment variables in your system:
|
30 |
-
|
31 |
-
+ OPENAI_API_KEY = your_api_key
|
32 |
-
+ OPENAI_BASE_URL= your_base_url
|
33 |
-
+ GRADIO_TEMP_DIR= gradio_tmp
|
34 |
-
|
35 |
## Installation
|
36 |
|
37 |
```bash
|
@@ -41,7 +27,7 @@ pip install -r requirements.txt
|
|
41 |
## Running the code
|
42 |
|
43 |
```bash
|
44 |
-
python
|
45 |
```
|
46 |
|
47 |
|
|
|
1 |
---
|
2 |
+
title: GLM-4.1V-9B
|
3 |
+
emoji: 🖼️
|
4 |
colorFrom: yellow
|
5 |
colorTo: blue
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 5.25.2
|
8 |
suggested_hardware: l40sx1
|
9 |
suggested_storage: large
|
10 |
app_port: 7860
|
11 |
app_file: app.py
|
12 |
models:
|
13 |
+
- THUDM/GLM-4.1V-9B
|
14 |
tags:
|
15 |
+
- image2text
|
16 |
+
- GLM
|
17 |
+
short_description: Image-to-Text
|
|
|
18 |
disable_embedding: false
|
19 |
---
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
## Installation
|
22 |
|
23 |
```bash
|
|
|
27 |
## Running the code
|
28 |
|
29 |
```bash
|
30 |
+
python app.py
|
31 |
```
|
32 |
|
33 |
|
app.py
CHANGED
@@ -1,491 +1,272 @@
|
|
1 |
-
"""
|
2 |
-
THis is the main file for the gradio web demo. It uses the CogVideoX-5B model to generate videos gradio web demo.
|
3 |
-
set environment variable OPENAI_API_KEY to use the OpenAI API to enhance the prompt.
|
4 |
-
|
5 |
-
Usage:
|
6 |
-
OpenAI_API_KEY=your_openai_api_key OPENAI_BASE_URL=https://api.openai.com/v1 python inference/gradio_web_demo.py
|
7 |
-
"""
|
8 |
-
|
9 |
-
import math
|
10 |
-
import os
|
11 |
-
import random
|
12 |
-
import threading
|
13 |
-
import time
|
14 |
-
|
15 |
-
import cv2
|
16 |
-
import tempfile
|
17 |
-
import imageio_ffmpeg
|
18 |
import gradio as gr
|
19 |
import torch
|
20 |
-
from
|
21 |
-
from
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
)
|
28 |
-
from diffusers.utils import load_video, load_image
|
29 |
-
from datetime import datetime, timedelta
|
30 |
-
|
31 |
-
from diffusers.image_processor import VaeImageProcessor
|
32 |
-
from openai import OpenAI
|
33 |
-
import moviepy.editor as mp
|
34 |
-
import utils
|
35 |
-
from rife_model import load_rife_model, rife_inference_with_latents
|
36 |
-
from huggingface_hub import hf_hub_download, snapshot_download
|
37 |
-
import gc
|
38 |
-
|
39 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
40 |
-
|
41 |
-
hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
|
42 |
-
snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
|
43 |
-
|
44 |
-
pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to("cpu")
|
45 |
-
pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
|
46 |
-
|
47 |
-
i2v_transformer = CogVideoXTransformer3DModel.from_pretrained(
|
48 |
-
"THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=torch.bfloat16
|
49 |
-
)
|
50 |
|
51 |
-
|
52 |
-
# pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
|
53 |
-
# pipe_image.transformer.to(memory_format=torch.channels_last)
|
54 |
-
# pipe_image.transformer = torch.compile(pipe_image.transformer, mode="max-autotune", fullgraph=True)
|
55 |
|
56 |
-
os.makedirs("./output", exist_ok=True)
|
57 |
-
os.makedirs("./gradio_tmp", exist_ok=True)
|
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 |
-
while (total_frames / (skip + 1)) < 49 and skip > 0:
|
112 |
-
skip -= 1
|
113 |
-
|
114 |
-
processed_frames = []
|
115 |
-
frame_count = 0
|
116 |
-
total_read = 0
|
117 |
-
|
118 |
-
while frame_count < 49 and total_read < total_frames:
|
119 |
-
ret, frame = cap.read()
|
120 |
-
if not ret:
|
121 |
-
break
|
122 |
-
|
123 |
-
if total_read % (skip + 1) == 0:
|
124 |
-
resized = cv2.resize(frame, (inter_width, inter_height), interpolation=cv2.INTER_AREA)
|
125 |
-
|
126 |
-
start_x = (inter_width - target_width) // 2
|
127 |
-
start_y = (inter_height - target_height) // 2
|
128 |
-
cropped = resized[start_y : start_y + target_height, start_x : start_x + target_width]
|
129 |
-
|
130 |
-
processed_frames.append(cropped)
|
131 |
-
frame_count += 1
|
132 |
-
|
133 |
-
total_read += 1
|
134 |
-
|
135 |
-
cap.release()
|
136 |
-
|
137 |
-
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
|
138 |
-
temp_video_path = temp_file.name
|
139 |
-
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
140 |
-
out = cv2.VideoWriter(temp_video_path, fourcc, target_fps, (target_width, target_height))
|
141 |
-
|
142 |
-
for frame in processed_frames:
|
143 |
-
out.write(frame)
|
144 |
-
|
145 |
-
out.release()
|
146 |
-
|
147 |
-
return temp_video_path
|
148 |
-
|
149 |
-
|
150 |
-
def convert_prompt(prompt: str, retry_times: int = 3) -> str:
|
151 |
-
if not os.environ.get("OPENAI_API_KEY"):
|
152 |
-
return prompt
|
153 |
-
client = OpenAI()
|
154 |
-
text = prompt.strip()
|
155 |
-
|
156 |
-
for i in range(retry_times):
|
157 |
-
response = client.chat.completions.create(
|
158 |
-
messages=[
|
159 |
-
{"role": "system", "content": sys_prompt},
|
160 |
-
{
|
161 |
-
"role": "user",
|
162 |
-
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
|
163 |
-
},
|
164 |
-
{
|
165 |
-
"role": "assistant",
|
166 |
-
"content": "A radiant woman stands on a deserted beach, arms outstretched, wearing a beige trench coat, white blouse, light blue jeans, and chic boots, against a backdrop of soft sky and sea. Moments later, she is seen mid-twirl, arms exuberant, with the lighting suggesting dawn or dusk. Then, she runs along the beach, her attire complemented by an off-white scarf and black ankle boots, the tranquil sea behind her. Finally, she holds a paper airplane, her pose reflecting joy and freedom, with the ocean's gentle waves and the sky's soft pastel hues enhancing the serene ambiance.",
|
167 |
-
},
|
168 |
-
{
|
169 |
-
"role": "user",
|
170 |
-
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
|
171 |
-
},
|
172 |
-
{
|
173 |
-
"role": "assistant",
|
174 |
-
"content": "A determined man in athletic attire, including a blue long-sleeve shirt, black shorts, and blue socks, jogs around a snow-covered soccer field, showcasing his solitary exercise in a quiet, overcast setting. His long dreadlocks, focused expression, and the serene winter backdrop highlight his dedication to fitness. As he moves, his attire, consisting of a blue sports sweatshirt, black athletic pants, gloves, and sneakers, grips the snowy ground. He is seen running past a chain-link fence enclosing the playground area, with a basketball hoop and children's slide, suggesting a moment of solitary exercise amidst the empty field.",
|
175 |
-
},
|
176 |
-
{
|
177 |
-
"role": "user",
|
178 |
-
"content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
|
179 |
-
},
|
180 |
-
{
|
181 |
-
"role": "assistant",
|
182 |
-
"content": "A young woman with her hair in an updo and wearing a teal hoodie stands against a light backdrop, initially looking over her shoulder with a contemplative expression. She then confidently makes a subtle dance move, suggesting rhythm and movement. Next, she appears poised and focused, looking directly at the camera. Her expression shifts to one of introspection as she gazes downward slightly. Finally, she dances with confidence, her left hand over her heart, symbolizing a poignant moment, all while dressed in the same teal hoodie against a plain, light-colored background.",
|
183 |
-
},
|
184 |
-
{
|
185 |
-
"role": "user",
|
186 |
-
"content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
|
187 |
-
},
|
188 |
-
],
|
189 |
-
model="glm-4-plus",
|
190 |
-
temperature=0.01,
|
191 |
-
top_p=0.7,
|
192 |
-
stream=False,
|
193 |
-
max_tokens=200,
|
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 |
-
generator=torch.Generator(device="cpu").manual_seed(seed),
|
276 |
-
).frames
|
277 |
-
pipe.to("cpu")
|
278 |
-
gc.collect()
|
279 |
-
return (video_pt, seed)
|
280 |
-
|
281 |
-
|
282 |
-
def convert_to_gif(video_path):
|
283 |
-
clip = mp.VideoFileClip(video_path)
|
284 |
-
clip = clip.set_fps(8)
|
285 |
-
clip = clip.resize(height=240)
|
286 |
-
gif_path = video_path.replace(".mp4", ".gif")
|
287 |
-
clip.write_gif(gif_path, fps=8)
|
288 |
-
return gif_path
|
289 |
-
|
290 |
-
|
291 |
-
def delete_old_files():
|
292 |
-
while True:
|
293 |
-
now = datetime.now()
|
294 |
-
cutoff = now - timedelta(minutes=10)
|
295 |
-
directories = ["./output", "./gradio_tmp"]
|
296 |
-
|
297 |
-
for directory in directories:
|
298 |
-
for filename in os.listdir(directory):
|
299 |
-
file_path = os.path.join(directory, filename)
|
300 |
-
if os.path.isfile(file_path):
|
301 |
-
file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
|
302 |
-
if file_mtime < cutoff:
|
303 |
-
os.remove(file_path)
|
304 |
-
time.sleep(600)
|
305 |
-
|
306 |
-
|
307 |
-
threading.Thread(target=delete_old_files, daemon=True).start()
|
308 |
-
examples_videos = [["example_videos/horse.mp4"], ["example_videos/kitten.mp4"], ["example_videos/train_running.mp4"]]
|
309 |
-
examples_images = [["example_images/beach.png"], ["example_images/street.png"], ["example_images/camping.png"]]
|
310 |
-
|
311 |
-
with gr.Blocks() as demo:
|
312 |
gr.Markdown("""
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
<a href="https://huggingface.co/THUDM/
|
318 |
-
<a href="https://
|
319 |
-
<a href="https://
|
320 |
-
|
321 |
-
|
322 |
-
<div style="text-align: center;display: flex;justify-content: center;align-items: center;margin-top: 1em;margin-bottom: .5em;">
|
323 |
-
<span>If the Space is too busy, duplicate it to use privately</span>
|
324 |
-
<a href="https://huggingface.co/spaces/THUDM/CogVideoX-5B-Space?duplicate=true"><img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-lg.svg" width="160" style="
|
325 |
-
margin-left: .75em;
|
326 |
-
"></a>
|
327 |
-
</div>
|
328 |
-
<div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
|
329 |
-
⚠️ This demo is for academic research and experiential use only.
|
330 |
-
</div>
|
331 |
-
""")
|
332 |
with gr.Row():
|
333 |
-
with gr.Column():
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
|
342 |
-
|
343 |
with gr.Row():
|
344 |
-
gr.
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
generate_button = gr.Button("🎬 Generate Video")
|
362 |
-
|
363 |
-
with gr.Column():
|
364 |
-
video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
|
365 |
-
with gr.Row():
|
366 |
-
download_video_button = gr.File(label="📥 Download Video", visible=False)
|
367 |
-
download_gif_button = gr.File(label="📥 Download GIF", visible=False)
|
368 |
-
seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
|
369 |
-
|
370 |
-
gr.Markdown("""
|
371 |
-
<table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
|
372 |
-
<div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
|
373 |
-
🎥 Video Gallery
|
374 |
-
</div>
|
375 |
-
<tr>
|
376 |
-
<td style="width: 25%; vertical-align: top; font-size: 0.9em;">
|
377 |
-
<p>A garden comes to life as a kaleidoscope of butterflies flutters amidst the blossoms, their delicate wings casting shadows on the petals below. In the background, a grand fountain cascades water with a gentle splendor, its rhythmic sound providing a soothing backdrop. Beneath the cool shade of a mature tree, a solitary wooden chair invites solitude and reflection, its smooth surface worn by the touch of countless visitors seeking a moment of tranquility in nature's embrace.</p>
|
378 |
-
</td>
|
379 |
-
<td style="width: 25%; vertical-align: top;">
|
380 |
-
<video src="https://github.com/user-attachments/assets/cf5953ea-96d3-48fd-9907-c4708752c714" width="100%" controls autoplay loop></video>
|
381 |
-
</td>
|
382 |
-
<td style="width: 25%; vertical-align: top; font-size: 0.9em;">
|
383 |
-
<p>A small boy, head bowed and determination etched on his face, sprints through the torrential downpour as lightning crackles and thunder rumbles in the distance. The relentless rain pounds the ground, creating a chaotic dance of water droplets that mirror the dramatic sky's anger. In the far background, the silhouette of a cozy home beckons, a faint beacon of safety and warmth amidst the fierce weather. The scene is one of perseverance and the unyielding spirit of a child braving the elements.</p>
|
384 |
-
</td>
|
385 |
-
<td style="width: 25%; vertical-align: top;">
|
386 |
-
<video src="https://github.com/user-attachments/assets/fe0a78e6-b669-4800-8cf0-b5f9b5145b52" width="100%" controls autoplay loop></video>
|
387 |
-
</td>
|
388 |
-
</tr>
|
389 |
-
<tr>
|
390 |
-
<td style="width: 25%; vertical-align: top; font-size: 0.9em;">
|
391 |
-
<p>A suited astronaut, with the red dust of Mars clinging to their boots, reaches out to shake hands with an alien being, their skin a shimmering blue, under the pink-tinged sky of the fourth planet. In the background, a sleek silver rocket, a beacon of human ingenuity, stands tall, its engines powered down, as the two representatives of different worlds exchange a historic greeting amidst the desolate beauty of the Martian landscape.</p>
|
392 |
-
</td>
|
393 |
-
<td style="width: 25%; vertical-align: top;">
|
394 |
-
<video src="https://github.com/user-attachments/assets/c182f606-8f8c-421d-b414-8487070fcfcb" width="100%" controls autoplay loop></video>
|
395 |
-
</td>
|
396 |
-
<td style="width: 25%; vertical-align: top; font-size: 0.9em;">
|
397 |
-
<p>An elderly gentleman, with a serene expression, sits at the water's edge, a steaming cup of tea by his side. He is engrossed in his artwork, brush in hand, as he renders an oil painting on a canvas that's propped up against a small, weathered table. The sea breeze whispers through his silver hair, gently billowing his loose-fitting white shirt, while the salty air adds an intangible element to his masterpiece in progress. The scene is one of tranquility and inspiration, with the artist's canvas capturing the vibrant hues of the setting sun reflecting off the tranquil sea.</p>
|
398 |
-
</td>
|
399 |
-
<td style="width: 25%; vertical-align: top;">
|
400 |
-
<video src="https://github.com/user-attachments/assets/7db2bbce-194d-434d-a605-350254b6c298" width="100%" controls autoplay loop></video>
|
401 |
-
</td>
|
402 |
-
</tr>
|
403 |
-
<tr>
|
404 |
-
<td style="width: 25%; vertical-align: top; font-size: 0.9em;">
|
405 |
-
<p>In a dimly lit bar, purplish light bathes the face of a mature man, his eyes blinking thoughtfully as he ponders in close-up, the background artfully blurred to focus on his introspective expression, the ambiance of the bar a mere suggestion of shadows and soft lighting.</p>
|
406 |
-
</td>
|
407 |
-
<td style="width: 25%; vertical-align: top;">
|
408 |
-
<video src="https://github.com/user-attachments/assets/62b01046-8cab-44cc-bd45-4d965bb615ec" width="100%" controls autoplay loop></video>
|
409 |
-
</td>
|
410 |
-
<td style="width: 25%; vertical-align: top; font-size: 0.9em;">
|
411 |
-
<p>A golden retriever, sporting sleek black sunglasses, with its lengthy fur flowing in the breeze, sprints playfully across a rooftop terrace, recently refreshed by a light rain. The scene unfolds from a distance, the dog's energetic bounds growing larger as it approaches the camera, its tail wagging with unrestrained joy, while droplets of water glisten on the concrete behind it. The overcast sky provides a dramatic backdrop, emphasizing the vibrant golden coat of the canine as it dashes towards the viewer.</p>
|
412 |
-
</td>
|
413 |
-
<td style="width: 25%; vertical-align: top;">
|
414 |
-
<video src="https://github.com/user-attachments/assets/d78e552a-4b3f-4b81-ac3f-3898079554f6" width="100%" controls autoplay loop></video>
|
415 |
-
</td>
|
416 |
-
</tr>
|
417 |
-
<tr>
|
418 |
-
<td style="width: 25%; vertical-align: top; font-size: 0.9em;">
|
419 |
-
<p>On a brilliant sunny day, the lakeshore is lined with an array of willow trees, their slender branches swaying gently in the soft breeze. The tranquil surface of the lake reflects the clear blue sky, while several elegant swans glide gracefully through the still water, leaving behind delicate ripples that disturb the mirror-like quality of the lake. The scene is one of serene beauty, with the willows' greenery providing a picturesque frame for the peaceful avian visitors.</p>
|
420 |
-
</td>
|
421 |
-
<td style="width: 25%; vertical-align: top;">
|
422 |
-
<video src="https://github.com/user-attachments/assets/30894f12-c741-44a2-9e6e-ddcacc231e5b" width="100%" controls autoplay loop></video>
|
423 |
-
</td>
|
424 |
-
<td style="width: 25%; vertical-align: top; font-size: 0.9em;">
|
425 |
-
<p>A Chinese mother, draped in a soft, pastel-colored robe, gently rocks back and forth in a cozy rocking chair positioned in the tranquil setting of a nursery. The dimly lit bedroom is adorned with whimsical mobiles dangling from the ceiling, casting shadows that dance on the walls. Her baby, swaddled in a delicate, patterned blanket, rests against her chest, the child's earlier cries now replaced by contented coos as the mother's soothing voice lulls the little one to sleep. The scent of lavender fills the air, adding to the serene atmosphere, while a warm, orange glow from a nearby nightlight illuminates the scene with a gentle hue, capturing a moment of tender love and comfort.</p>
|
426 |
-
</td>
|
427 |
-
<td style="width: 25%; vertical-align: top;">
|
428 |
-
<video src="https://github.com/user-attachments/assets/926575ca-7150-435b-a0ff-4900a963297b" width="100%" controls autoplay loop></video>
|
429 |
-
</td>
|
430 |
-
</tr>
|
431 |
-
</table>
|
432 |
-
""")
|
433 |
-
|
434 |
-
def generate(
|
435 |
-
prompt,
|
436 |
-
image_input,
|
437 |
-
video_input,
|
438 |
-
video_strength,
|
439 |
-
seed_value,
|
440 |
-
scale_status,
|
441 |
-
rife_status,
|
442 |
-
progress=gr.Progress(track_tqdm=True)
|
443 |
-
):
|
444 |
-
latents, seed = infer(
|
445 |
-
prompt,
|
446 |
-
image_input,
|
447 |
-
video_input,
|
448 |
-
video_strength,
|
449 |
-
num_inference_steps=50, # NOT Changed
|
450 |
-
guidance_scale=7.0, # NOT Changed
|
451 |
-
seed=seed_value,
|
452 |
-
progress=progress,
|
453 |
-
)
|
454 |
-
if scale_status:
|
455 |
-
latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
|
456 |
-
if rife_status:
|
457 |
-
latents = rife_inference_with_latents(frame_interpolation_model, latents)
|
458 |
-
|
459 |
-
batch_size = latents.shape[0]
|
460 |
-
batch_video_frames = []
|
461 |
-
for batch_idx in range(batch_size):
|
462 |
-
pt_image = latents[batch_idx]
|
463 |
-
pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
|
464 |
-
|
465 |
-
image_np = VaeImageProcessor.pt_to_numpy(pt_image)
|
466 |
-
image_pil = VaeImageProcessor.numpy_to_pil(image_np)
|
467 |
-
batch_video_frames.append(image_pil)
|
468 |
-
|
469 |
-
video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
|
470 |
-
video_update = gr.update(visible=True, value=video_path)
|
471 |
-
gif_path = convert_to_gif(video_path)
|
472 |
-
gif_update = gr.update(visible=True, value=gif_path)
|
473 |
-
seed_update = gr.update(visible=True, value=seed)
|
474 |
-
|
475 |
-
return video_path, video_update, gif_update, seed_update
|
476 |
-
|
477 |
-
def enhance_prompt_func(prompt):
|
478 |
-
return convert_prompt(prompt, retry_times=1)
|
479 |
-
|
480 |
-
generate_button.click(
|
481 |
-
generate,
|
482 |
-
inputs=[prompt, image_input, video_input, strength, seed_param, enable_scale, enable_rife],
|
483 |
-
outputs=[video_output, download_video_button, download_gif_button, seed_text],
|
484 |
-
)
|
485 |
-
|
486 |
-
enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
|
487 |
-
video_input.upload(resize_if_unfit, inputs=[video_input], outputs=[video_input])
|
488 |
|
489 |
if __name__ == "__main__":
|
490 |
-
|
491 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
+
from transformers import AutoProcessor, Glm4vForConditionalGeneration, TextIteratorStreamer
|
4 |
+
from pathlib import Path
|
5 |
+
import threading
|
6 |
+
import re
|
7 |
+
import argparse
|
8 |
+
import copy
|
9 |
+
import spaces
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
MODEL_PATH = "/model/glm-4v-9b-0529"
|
|
|
|
|
|
|
12 |
|
|
|
|
|
13 |
|
14 |
+
class GLM4VModel:
|
15 |
+
def __init__(self):
|
16 |
+
self.processor = None
|
17 |
+
self.model = None
|
18 |
+
self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
19 |
|
20 |
+
def load(self):
|
21 |
+
self.processor = AutoProcessor.from_pretrained(MODEL_PATH, use_fast=True)
|
22 |
+
self.model = Glm4vForConditionalGeneration.from_pretrained(
|
23 |
+
MODEL_PATH,
|
24 |
+
torch_dtype=torch.bfloat16,
|
25 |
+
device_map=self.device,
|
26 |
+
attn_implementation="sdpa",
|
27 |
+
)
|
28 |
|
29 |
+
def _strip_html(self, t):
|
30 |
+
return re.sub(r"<[^>]+>", "", t).strip()
|
31 |
+
|
32 |
+
def _wrap_text(self, t):
|
33 |
+
return [{"type": "text", "text": t}]
|
34 |
+
|
35 |
+
def _files_to_content(self, media):
|
36 |
+
out = []
|
37 |
+
for f in media or []:
|
38 |
+
ext = Path(f.name).suffix.lower()
|
39 |
+
if ext in [".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv", ".webm", ".mpeg", ".m4v"]:
|
40 |
+
out.append({"type": "video", "url": f.name})
|
41 |
+
elif ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp"]:
|
42 |
+
out.append({"type": "image", "url": f.name})
|
43 |
+
return out
|
44 |
+
|
45 |
+
# -----------------------------------------------------------
|
46 |
+
# 🖼️ Output formatting
|
47 |
+
# -----------------------------------------------------------
|
48 |
+
def _format_output(self, txt):
|
49 |
+
"""Called once完整生成结束时"""
|
50 |
+
think_pat, ans_pat = r"<think>(.*?)</think>", r"<answer>(.*?)</answer>"
|
51 |
+
think = re.findall(think_pat, txt, re.DOTALL)
|
52 |
+
ans = re.findall(ans_pat, txt, re.DOTALL)
|
53 |
+
html = ""
|
54 |
+
if think:
|
55 |
+
html += (
|
56 |
+
"<details open><summary style='cursor:pointer;font-weight:bold;color:#bbbbbb;'>💭 Thinking Process</summary>"
|
57 |
+
"<div style='color:#cccccc;line-height:1.4;'>"
|
58 |
+
+ think[0].strip()
|
59 |
+
+ "</div></details><br>"
|
60 |
+
)
|
61 |
+
body = ans[0] if ans else re.sub(think_pat, "", txt, flags=re.DOTALL)
|
62 |
+
html += f"<div style='color:#ffffff;'>{body.strip()}</div>"
|
63 |
+
return html
|
64 |
+
|
65 |
+
def _stream_fragment(self, buf: str) -> str:
|
66 |
+
think_html = ""
|
67 |
+
if "<think>" in buf:
|
68 |
+
if "</think>" in buf:
|
69 |
+
think_content = re.search(r"<think>(.*?)</think>", buf, re.DOTALL)
|
70 |
+
if think_content:
|
71 |
+
think_html = (
|
72 |
+
"<details open><summary style='cursor:pointer;font-weight:bold;color:#bbbbbb;'>💭 Thinking Process</summary>"
|
73 |
+
"<div style='color:#cccccc;line-height:1.4;'>"
|
74 |
+
+ think_content.group(1).strip()
|
75 |
+
+ "</div></details><br>"
|
76 |
+
)
|
77 |
+
else:
|
78 |
+
partial = buf.split("<think>", 1)[1]
|
79 |
+
think_html = (
|
80 |
+
"<details open><summary style='cursor:pointer;font-weight:bold;color:#bbbbbb;'>💭 Thinking Process</summary>"
|
81 |
+
"<div style='color:#cccccc;line-height:1.4;'>" + partial
|
82 |
+
)
|
83 |
|
84 |
+
answer_html = ""
|
85 |
+
if "<answer>" in buf:
|
86 |
+
if "</answer>" in buf:
|
87 |
+
ans_content = re.search(r"<answer>(.*?)</answer>", buf, re.DOTALL)
|
88 |
+
if ans_content:
|
89 |
+
answer_html = (
|
90 |
+
"<div style='color:#ffffff;'>" + ans_content.group(1).strip() + "</div>"
|
91 |
+
)
|
92 |
+
else:
|
93 |
+
partial = buf.split("<answer>", 1)[1]
|
94 |
+
answer_html = "<div style='color:#ffffff;'>" + partial
|
95 |
|
96 |
+
if not think_html and not answer_html:
|
97 |
+
return self._strip_html(buf)
|
98 |
|
99 |
+
return think_html + answer_html
|
|
|
100 |
|
101 |
+
def _build_messages(self, hist, sys_prompt):
|
102 |
+
msgs = []
|
103 |
|
104 |
+
if sys_prompt.strip():
|
105 |
+
msgs.append({
|
106 |
+
"role": "system",
|
107 |
+
"content": [{"type": "text", "text": sys_prompt.strip()}]
|
108 |
+
})
|
109 |
|
110 |
+
for h in hist:
|
111 |
+
if h["role"] == "user":
|
112 |
+
payload = h.get("file_info") or self._wrap_text(
|
113 |
+
self._strip_html(h["content"])
|
114 |
+
)
|
115 |
+
msgs.append({"role": "user", "content": payload})
|
116 |
+
|
117 |
+
else:
|
118 |
+
raw = h["content"]
|
119 |
+
raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL)
|
120 |
+
raw = re.sub(r"<details.*?</details>", "", raw, flags=re.DOTALL)
|
121 |
+
clean = self._strip_html(raw).strip()
|
122 |
+
|
123 |
+
msgs.append({"role": "assistant", "content": self._wrap_text(clean)})
|
124 |
+
|
125 |
+
return msgs
|
126 |
+
|
127 |
+
@spaces.GPU(duration=240)
|
128 |
+
def stream_generate(self, hist, sys_prompt):
|
129 |
+
msgs = self._build_messages(hist, sys_prompt)
|
130 |
+
print(msgs)
|
131 |
+
inputs = self.processor.apply_chat_template(
|
132 |
+
msgs,
|
133 |
+
tokenize=True,
|
134 |
+
add_generation_prompt=True,
|
135 |
+
return_dict=True,
|
136 |
+
return_tensors="pt",
|
137 |
+
padding=True,
|
138 |
+
).to(self.device)
|
139 |
+
|
140 |
+
streamer = TextIteratorStreamer(
|
141 |
+
self.processor.tokenizer, skip_prompt=True, skip_special_tokens=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
)
|
143 |
+
gen_args = dict(
|
144 |
+
inputs,
|
145 |
+
max_new_tokens=8192,
|
146 |
+
repetition_penalty=1.1,
|
147 |
+
do_sample=True,
|
148 |
+
top_k=2,
|
149 |
+
temperature=None,
|
150 |
+
top_p=1e-5,
|
151 |
+
streamer=streamer,
|
152 |
+
)
|
153 |
+
threading.Thread(target=self.model.generate, kwargs=gen_args).start()
|
154 |
+
|
155 |
+
buf = ""
|
156 |
+
for tok in streamer:
|
157 |
+
buf += tok
|
158 |
+
yield self._stream_fragment(buf)
|
159 |
+
yield self._format_output(buf)
|
160 |
+
|
161 |
+
|
162 |
+
glm4v = GLM4VModel()
|
163 |
+
glm4v.load()
|
164 |
+
|
165 |
+
|
166 |
+
def check_files(files):
|
167 |
+
vids = imgs = 0
|
168 |
+
for f in files or []:
|
169 |
+
ext = Path(f.name).suffix.lower()
|
170 |
+
if ext in [".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv", ".webm", ".mpeg", ".m4v"]:
|
171 |
+
vids += 1
|
172 |
+
elif ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp"]:
|
173 |
+
imgs += 1
|
174 |
+
if vids > 1:
|
175 |
+
return False, "Only 1 video allowed"
|
176 |
+
if imgs > 10:
|
177 |
+
return False, "Max 10 images"
|
178 |
+
if vids and imgs:
|
179 |
+
return False, "Cannot mix video and images"
|
180 |
+
return True, ""
|
181 |
+
|
182 |
+
|
183 |
+
def chat(files, msg, hist, sys_prompt):
|
184 |
+
ok, err = check_files(files)
|
185 |
+
if not ok:
|
186 |
+
hist.append({"role": "assistant", "content": err})
|
187 |
+
yield copy.deepcopy(hist), None, ""
|
188 |
+
return
|
189 |
+
|
190 |
+
payload = glm4v._files_to_content(files) if files else None
|
191 |
+
if msg.strip():
|
192 |
+
if payload is None:
|
193 |
+
payload = glm4v._wrap_text(msg.strip())
|
194 |
+
else:
|
195 |
+
payload.append({"type": "text", "text": msg.strip()})
|
196 |
+
|
197 |
+
display = f"[{len(files)} file(s) uploaded]\n{msg}" if files else msg
|
198 |
+
user_rec = {"role": "user", "content": display}
|
199 |
+
if payload:
|
200 |
+
user_rec["file_info"] = payload
|
201 |
+
hist.append(user_rec)
|
202 |
+
|
203 |
+
place = {"role": "assistant", "content": ""}
|
204 |
+
hist.append(place)
|
205 |
+
yield copy.deepcopy(hist), None, ""
|
206 |
+
|
207 |
+
for chunk in glm4v.stream_generate(hist[:-1], sys_prompt):
|
208 |
+
place["content"] = chunk
|
209 |
+
yield copy.deepcopy(hist), None, ""
|
210 |
+
yield copy.deepcopy(hist), None, ""
|
211 |
+
|
212 |
+
|
213 |
+
def reset():
|
214 |
+
return [], None, ""
|
215 |
+
|
216 |
+
|
217 |
+
css = """.chatbot-container .message-wrap .message{font-size:14px!important}
|
218 |
+
details summary{cursor:pointer;font-weight:bold}
|
219 |
+
details[open] summary{margin-bottom:10px}"""
|
220 |
+
|
221 |
+
demo = gr.Blocks(title="GLM-4.1V Chat", theme=gr.themes.Soft(), css=css)
|
222 |
+
with demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
gr.Markdown("""
|
224 |
+
<div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
|
225 |
+
GLM-4.1V-9B Gradio Space🤗
|
226 |
+
</div>
|
227 |
+
<div style="text-align: center;">
|
228 |
+
<a href="https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking">🤗 Model Hub</a> |
|
229 |
+
<a href="https://github.com/THUDM/CogVLM">🌐 Github</a> |
|
230 |
+
<a href="https://arxiv.org/abs/">📜 arxiv</a>
|
231 |
+
</div>
|
232 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
233 |
with gr.Row():
|
234 |
+
with gr.Column(scale=7):
|
235 |
+
chatbox = gr.Chatbot(
|
236 |
+
label="Conversation",
|
237 |
+
type="messages",
|
238 |
+
height=600,
|
239 |
+
elem_classes="chatbot-container",
|
240 |
+
)
|
241 |
+
textbox = gr.Textbox(label="💭 Message", lines=3)
|
|
|
|
|
242 |
with gr.Row():
|
243 |
+
send = gr.Button("Send", variant="primary")
|
244 |
+
clear = gr.Button("Clear")
|
245 |
+
with gr.Column(scale=3):
|
246 |
+
up = gr.File(
|
247 |
+
label="📁 Upload",
|
248 |
+
file_count="multiple",
|
249 |
+
file_types=["image", "video"],
|
250 |
+
type="filepath",
|
251 |
+
)
|
252 |
+
gr.Markdown("""
|
253 |
+
<span style="color:red">Please upload the Bay image before entering text.</span>
|
254 |
+
""")
|
255 |
+
sys = gr.Textbox(label="⚙️ System Prompt", lines=6)
|
256 |
+
|
257 |
+
send.click(chat, inputs=[up, textbox, chatbox, sys], outputs=[chatbox, up, textbox])
|
258 |
+
textbox.submit(chat, inputs=[up, textbox, chatbox, sys], outputs=[chatbox, up, textbox])
|
259 |
+
clear.click(reset, outputs=[chatbox, up, textbox])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
260 |
|
261 |
if __name__ == "__main__":
|
262 |
+
parser = argparse.ArgumentParser()
|
263 |
+
parser.add_argument("--port", type=int, default=8000)
|
264 |
+
parser.add_argument("--host", type=str, default="0.0.0.0")
|
265 |
+
parser.add_argument("--share", action="store_true")
|
266 |
+
args = parser.parse_args()
|
267 |
+
|
268 |
+
demo.launch(
|
269 |
+
server_port=args.port,
|
270 |
+
server_name=args.host,
|
271 |
+
share=args.share,
|
272 |
+
)
|
example_images/beach.png
DELETED
Binary file (385 kB)
|
|
example_images/camping.png
DELETED
Binary file (484 kB)
|
|
example_images/street.png
DELETED
Binary file (478 kB)
|
|
example_videos/horse.mp4
DELETED
@@ -1,3 +0,0 @@
|
|
1 |
-
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:3c857bbc0d197c0751db9d6da9b5c85eafd163511ff9b0e10be65adf8ef9e352
|
3 |
-
size 453387
|
|
|
|
|
|
|
|
example_videos/kitten.mp4
DELETED
Binary file (882 kB)
|
|
example_videos/train_running.mp4
DELETED
Binary file (577 kB)
|
|
requirements.txt
CHANGED
@@ -1,19 +1,4 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
scikit-video>=1.1.11
|
6 |
-
git+https://github.com/huggingface/diffusers.git@main
|
7 |
-
transformers>=4.44.0
|
8 |
-
accelerate>=0.34.2
|
9 |
-
opencv-python>=4.10.0.84
|
10 |
-
sentencepiece>=0.2.0
|
11 |
-
numpy==1.26.0
|
12 |
-
torch==2.2.0
|
13 |
-
torchvision
|
14 |
-
gradio>=4.44.0
|
15 |
-
imageio>=2.34.2
|
16 |
-
imageio-ffmpeg>=0.5.1
|
17 |
-
openai>=1.45.0
|
18 |
-
moviepy>=1.0.3
|
19 |
-
pillow==9.5.0
|
|
|
1 |
+
git+https://github.com/huggingface/transformers.git@main
|
2 |
+
opencv-python>=4.11.0.86
|
3 |
+
gradio>=5.25.0
|
4 |
+
spaces>=0.37.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/IFNet.py
DELETED
@@ -1,123 +0,0 @@
|
|
1 |
-
from .refine import *
|
2 |
-
|
3 |
-
|
4 |
-
def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1):
|
5 |
-
return nn.Sequential(
|
6 |
-
torch.nn.ConvTranspose2d(in_channels=in_planes, out_channels=out_planes, kernel_size=4, stride=2, padding=1),
|
7 |
-
nn.PReLU(out_planes),
|
8 |
-
)
|
9 |
-
|
10 |
-
|
11 |
-
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
12 |
-
return nn.Sequential(
|
13 |
-
nn.Conv2d(
|
14 |
-
in_planes,
|
15 |
-
out_planes,
|
16 |
-
kernel_size=kernel_size,
|
17 |
-
stride=stride,
|
18 |
-
padding=padding,
|
19 |
-
dilation=dilation,
|
20 |
-
bias=True,
|
21 |
-
),
|
22 |
-
nn.PReLU(out_planes),
|
23 |
-
)
|
24 |
-
|
25 |
-
|
26 |
-
class IFBlock(nn.Module):
|
27 |
-
def __init__(self, in_planes, c=64):
|
28 |
-
super(IFBlock, self).__init__()
|
29 |
-
self.conv0 = nn.Sequential(
|
30 |
-
conv(in_planes, c // 2, 3, 2, 1),
|
31 |
-
conv(c // 2, c, 3, 2, 1),
|
32 |
-
)
|
33 |
-
self.convblock = nn.Sequential(
|
34 |
-
conv(c, c),
|
35 |
-
conv(c, c),
|
36 |
-
conv(c, c),
|
37 |
-
conv(c, c),
|
38 |
-
conv(c, c),
|
39 |
-
conv(c, c),
|
40 |
-
conv(c, c),
|
41 |
-
conv(c, c),
|
42 |
-
)
|
43 |
-
self.lastconv = nn.ConvTranspose2d(c, 5, 4, 2, 1)
|
44 |
-
|
45 |
-
def forward(self, x, flow, scale):
|
46 |
-
if scale != 1:
|
47 |
-
x = F.interpolate(x, scale_factor=1.0 / scale, mode="bilinear", align_corners=False)
|
48 |
-
if flow != None:
|
49 |
-
flow = F.interpolate(flow, scale_factor=1.0 / scale, mode="bilinear", align_corners=False) * 1.0 / scale
|
50 |
-
x = torch.cat((x, flow), 1)
|
51 |
-
x = self.conv0(x)
|
52 |
-
x = self.convblock(x) + x
|
53 |
-
tmp = self.lastconv(x)
|
54 |
-
tmp = F.interpolate(tmp, scale_factor=scale * 2, mode="bilinear", align_corners=False)
|
55 |
-
flow = tmp[:, :4] * scale * 2
|
56 |
-
mask = tmp[:, 4:5]
|
57 |
-
return flow, mask
|
58 |
-
|
59 |
-
|
60 |
-
class IFNet(nn.Module):
|
61 |
-
def __init__(self):
|
62 |
-
super(IFNet, self).__init__()
|
63 |
-
self.block0 = IFBlock(6, c=240)
|
64 |
-
self.block1 = IFBlock(13 + 4, c=150)
|
65 |
-
self.block2 = IFBlock(13 + 4, c=90)
|
66 |
-
self.block_tea = IFBlock(16 + 4, c=90)
|
67 |
-
self.contextnet = Contextnet()
|
68 |
-
self.unet = Unet()
|
69 |
-
|
70 |
-
def forward(self, x, scale=[4, 2, 1], timestep=0.5):
|
71 |
-
img0 = x[:, :3]
|
72 |
-
img1 = x[:, 3:6]
|
73 |
-
gt = x[:, 6:] # In inference time, gt is None
|
74 |
-
flow_list = []
|
75 |
-
merged = []
|
76 |
-
mask_list = []
|
77 |
-
warped_img0 = img0
|
78 |
-
warped_img1 = img1
|
79 |
-
flow = None
|
80 |
-
loss_distill = 0
|
81 |
-
stu = [self.block0, self.block1, self.block2]
|
82 |
-
for i in range(3):
|
83 |
-
if flow != None:
|
84 |
-
flow_d, mask_d = stu[i](
|
85 |
-
torch.cat((img0, img1, warped_img0, warped_img1, mask), 1), flow, scale=scale[i]
|
86 |
-
)
|
87 |
-
flow = flow + flow_d
|
88 |
-
mask = mask + mask_d
|
89 |
-
else:
|
90 |
-
flow, mask = stu[i](torch.cat((img0, img1), 1), None, scale=scale[i])
|
91 |
-
mask_list.append(torch.sigmoid(mask))
|
92 |
-
flow_list.append(flow)
|
93 |
-
warped_img0 = warp(img0, flow[:, :2])
|
94 |
-
warped_img1 = warp(img1, flow[:, 2:4])
|
95 |
-
merged_student = (warped_img0, warped_img1)
|
96 |
-
merged.append(merged_student)
|
97 |
-
if gt.shape[1] == 3:
|
98 |
-
flow_d, mask_d = self.block_tea(
|
99 |
-
torch.cat((img0, img1, warped_img0, warped_img1, mask, gt), 1), flow, scale=1
|
100 |
-
)
|
101 |
-
flow_teacher = flow + flow_d
|
102 |
-
warped_img0_teacher = warp(img0, flow_teacher[:, :2])
|
103 |
-
warped_img1_teacher = warp(img1, flow_teacher[:, 2:4])
|
104 |
-
mask_teacher = torch.sigmoid(mask + mask_d)
|
105 |
-
merged_teacher = warped_img0_teacher * mask_teacher + warped_img1_teacher * (1 - mask_teacher)
|
106 |
-
else:
|
107 |
-
flow_teacher = None
|
108 |
-
merged_teacher = None
|
109 |
-
for i in range(3):
|
110 |
-
merged[i] = merged[i][0] * mask_list[i] + merged[i][1] * (1 - mask_list[i])
|
111 |
-
if gt.shape[1] == 3:
|
112 |
-
loss_mask = (
|
113 |
-
((merged[i] - gt).abs().mean(1, True) > (merged_teacher - gt).abs().mean(1, True) + 0.01)
|
114 |
-
.float()
|
115 |
-
.detach()
|
116 |
-
)
|
117 |
-
loss_distill += (((flow_teacher.detach() - flow_list[i]) ** 2).mean(1, True) ** 0.5 * loss_mask).mean()
|
118 |
-
c0 = self.contextnet(img0, flow[:, :2])
|
119 |
-
c1 = self.contextnet(img1, flow[:, 2:4])
|
120 |
-
tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
|
121 |
-
res = tmp[:, :3] * 2 - 1
|
122 |
-
merged[2] = torch.clamp(merged[2] + res, 0, 1)
|
123 |
-
return flow_list, mask_list[2], merged, flow_teacher, merged_teacher, loss_distill
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/IFNet_2R.py
DELETED
@@ -1,123 +0,0 @@
|
|
1 |
-
from .refine_2R import *
|
2 |
-
|
3 |
-
|
4 |
-
def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1):
|
5 |
-
return nn.Sequential(
|
6 |
-
torch.nn.ConvTranspose2d(in_channels=in_planes, out_channels=out_planes, kernel_size=4, stride=2, padding=1),
|
7 |
-
nn.PReLU(out_planes),
|
8 |
-
)
|
9 |
-
|
10 |
-
|
11 |
-
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
12 |
-
return nn.Sequential(
|
13 |
-
nn.Conv2d(
|
14 |
-
in_planes,
|
15 |
-
out_planes,
|
16 |
-
kernel_size=kernel_size,
|
17 |
-
stride=stride,
|
18 |
-
padding=padding,
|
19 |
-
dilation=dilation,
|
20 |
-
bias=True,
|
21 |
-
),
|
22 |
-
nn.PReLU(out_planes),
|
23 |
-
)
|
24 |
-
|
25 |
-
|
26 |
-
class IFBlock(nn.Module):
|
27 |
-
def __init__(self, in_planes, c=64):
|
28 |
-
super(IFBlock, self).__init__()
|
29 |
-
self.conv0 = nn.Sequential(
|
30 |
-
conv(in_planes, c // 2, 3, 1, 1),
|
31 |
-
conv(c // 2, c, 3, 2, 1),
|
32 |
-
)
|
33 |
-
self.convblock = nn.Sequential(
|
34 |
-
conv(c, c),
|
35 |
-
conv(c, c),
|
36 |
-
conv(c, c),
|
37 |
-
conv(c, c),
|
38 |
-
conv(c, c),
|
39 |
-
conv(c, c),
|
40 |
-
conv(c, c),
|
41 |
-
conv(c, c),
|
42 |
-
)
|
43 |
-
self.lastconv = nn.ConvTranspose2d(c, 5, 4, 2, 1)
|
44 |
-
|
45 |
-
def forward(self, x, flow, scale):
|
46 |
-
if scale != 1:
|
47 |
-
x = F.interpolate(x, scale_factor=1.0 / scale, mode="bilinear", align_corners=False)
|
48 |
-
if flow != None:
|
49 |
-
flow = F.interpolate(flow, scale_factor=1.0 / scale, mode="bilinear", align_corners=False) * 1.0 / scale
|
50 |
-
x = torch.cat((x, flow), 1)
|
51 |
-
x = self.conv0(x)
|
52 |
-
x = self.convblock(x) + x
|
53 |
-
tmp = self.lastconv(x)
|
54 |
-
tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear", align_corners=False)
|
55 |
-
flow = tmp[:, :4] * scale
|
56 |
-
mask = tmp[:, 4:5]
|
57 |
-
return flow, mask
|
58 |
-
|
59 |
-
|
60 |
-
class IFNet(nn.Module):
|
61 |
-
def __init__(self):
|
62 |
-
super(IFNet, self).__init__()
|
63 |
-
self.block0 = IFBlock(6, c=240)
|
64 |
-
self.block1 = IFBlock(13 + 4, c=150)
|
65 |
-
self.block2 = IFBlock(13 + 4, c=90)
|
66 |
-
self.block_tea = IFBlock(16 + 4, c=90)
|
67 |
-
self.contextnet = Contextnet()
|
68 |
-
self.unet = Unet()
|
69 |
-
|
70 |
-
def forward(self, x, scale=[4, 2, 1], timestep=0.5):
|
71 |
-
img0 = x[:, :3]
|
72 |
-
img1 = x[:, 3:6]
|
73 |
-
gt = x[:, 6:] # In inference time, gt is None
|
74 |
-
flow_list = []
|
75 |
-
merged = []
|
76 |
-
mask_list = []
|
77 |
-
warped_img0 = img0
|
78 |
-
warped_img1 = img1
|
79 |
-
flow = None
|
80 |
-
loss_distill = 0
|
81 |
-
stu = [self.block0, self.block1, self.block2]
|
82 |
-
for i in range(3):
|
83 |
-
if flow != None:
|
84 |
-
flow_d, mask_d = stu[i](
|
85 |
-
torch.cat((img0, img1, warped_img0, warped_img1, mask), 1), flow, scale=scale[i]
|
86 |
-
)
|
87 |
-
flow = flow + flow_d
|
88 |
-
mask = mask + mask_d
|
89 |
-
else:
|
90 |
-
flow, mask = stu[i](torch.cat((img0, img1), 1), None, scale=scale[i])
|
91 |
-
mask_list.append(torch.sigmoid(mask))
|
92 |
-
flow_list.append(flow)
|
93 |
-
warped_img0 = warp(img0, flow[:, :2])
|
94 |
-
warped_img1 = warp(img1, flow[:, 2:4])
|
95 |
-
merged_student = (warped_img0, warped_img1)
|
96 |
-
merged.append(merged_student)
|
97 |
-
if gt.shape[1] == 3:
|
98 |
-
flow_d, mask_d = self.block_tea(
|
99 |
-
torch.cat((img0, img1, warped_img0, warped_img1, mask, gt), 1), flow, scale=1
|
100 |
-
)
|
101 |
-
flow_teacher = flow + flow_d
|
102 |
-
warped_img0_teacher = warp(img0, flow_teacher[:, :2])
|
103 |
-
warped_img1_teacher = warp(img1, flow_teacher[:, 2:4])
|
104 |
-
mask_teacher = torch.sigmoid(mask + mask_d)
|
105 |
-
merged_teacher = warped_img0_teacher * mask_teacher + warped_img1_teacher * (1 - mask_teacher)
|
106 |
-
else:
|
107 |
-
flow_teacher = None
|
108 |
-
merged_teacher = None
|
109 |
-
for i in range(3):
|
110 |
-
merged[i] = merged[i][0] * mask_list[i] + merged[i][1] * (1 - mask_list[i])
|
111 |
-
if gt.shape[1] == 3:
|
112 |
-
loss_mask = (
|
113 |
-
((merged[i] - gt).abs().mean(1, True) > (merged_teacher - gt).abs().mean(1, True) + 0.01)
|
114 |
-
.float()
|
115 |
-
.detach()
|
116 |
-
)
|
117 |
-
loss_distill += (((flow_teacher.detach() - flow_list[i]) ** 2).mean(1, True) ** 0.5 * loss_mask).mean()
|
118 |
-
c0 = self.contextnet(img0, flow[:, :2])
|
119 |
-
c1 = self.contextnet(img1, flow[:, 2:4])
|
120 |
-
tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
|
121 |
-
res = tmp[:, :3] * 2 - 1
|
122 |
-
merged[2] = torch.clamp(merged[2] + res, 0, 1)
|
123 |
-
return flow_list, mask_list[2], merged, flow_teacher, merged_teacher, loss_distill
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/IFNet_HDv3.py
DELETED
@@ -1,138 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
import torch.nn.functional as F
|
4 |
-
from .warplayer import warp
|
5 |
-
|
6 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
-
|
8 |
-
|
9 |
-
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
10 |
-
return nn.Sequential(
|
11 |
-
nn.Conv2d(
|
12 |
-
in_planes,
|
13 |
-
out_planes,
|
14 |
-
kernel_size=kernel_size,
|
15 |
-
stride=stride,
|
16 |
-
padding=padding,
|
17 |
-
dilation=dilation,
|
18 |
-
bias=True,
|
19 |
-
),
|
20 |
-
nn.PReLU(out_planes),
|
21 |
-
)
|
22 |
-
|
23 |
-
|
24 |
-
def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
25 |
-
return nn.Sequential(
|
26 |
-
nn.Conv2d(
|
27 |
-
in_planes,
|
28 |
-
out_planes,
|
29 |
-
kernel_size=kernel_size,
|
30 |
-
stride=stride,
|
31 |
-
padding=padding,
|
32 |
-
dilation=dilation,
|
33 |
-
bias=False,
|
34 |
-
),
|
35 |
-
nn.BatchNorm2d(out_planes),
|
36 |
-
nn.PReLU(out_planes),
|
37 |
-
)
|
38 |
-
|
39 |
-
|
40 |
-
class IFBlock(nn.Module):
|
41 |
-
def __init__(self, in_planes, c=64):
|
42 |
-
super(IFBlock, self).__init__()
|
43 |
-
self.conv0 = nn.Sequential(
|
44 |
-
conv(in_planes, c // 2, 3, 2, 1),
|
45 |
-
conv(c // 2, c, 3, 2, 1),
|
46 |
-
)
|
47 |
-
self.convblock0 = nn.Sequential(conv(c, c), conv(c, c))
|
48 |
-
self.convblock1 = nn.Sequential(conv(c, c), conv(c, c))
|
49 |
-
self.convblock2 = nn.Sequential(conv(c, c), conv(c, c))
|
50 |
-
self.convblock3 = nn.Sequential(conv(c, c), conv(c, c))
|
51 |
-
self.conv1 = nn.Sequential(
|
52 |
-
nn.ConvTranspose2d(c, c // 2, 4, 2, 1),
|
53 |
-
nn.PReLU(c // 2),
|
54 |
-
nn.ConvTranspose2d(c // 2, 4, 4, 2, 1),
|
55 |
-
)
|
56 |
-
self.conv2 = nn.Sequential(
|
57 |
-
nn.ConvTranspose2d(c, c // 2, 4, 2, 1),
|
58 |
-
nn.PReLU(c // 2),
|
59 |
-
nn.ConvTranspose2d(c // 2, 1, 4, 2, 1),
|
60 |
-
)
|
61 |
-
|
62 |
-
def forward(self, x, flow, scale=1):
|
63 |
-
x = F.interpolate(
|
64 |
-
x, scale_factor=1.0 / scale, mode="bilinear", align_corners=False, recompute_scale_factor=False
|
65 |
-
)
|
66 |
-
flow = (
|
67 |
-
F.interpolate(
|
68 |
-
flow, scale_factor=1.0 / scale, mode="bilinear", align_corners=False, recompute_scale_factor=False
|
69 |
-
)
|
70 |
-
* 1.0
|
71 |
-
/ scale
|
72 |
-
)
|
73 |
-
feat = self.conv0(torch.cat((x, flow), 1))
|
74 |
-
feat = self.convblock0(feat) + feat
|
75 |
-
feat = self.convblock1(feat) + feat
|
76 |
-
feat = self.convblock2(feat) + feat
|
77 |
-
feat = self.convblock3(feat) + feat
|
78 |
-
flow = self.conv1(feat)
|
79 |
-
mask = self.conv2(feat)
|
80 |
-
flow = (
|
81 |
-
F.interpolate(flow, scale_factor=scale, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
82 |
-
* scale
|
83 |
-
)
|
84 |
-
mask = F.interpolate(
|
85 |
-
mask, scale_factor=scale, mode="bilinear", align_corners=False, recompute_scale_factor=False
|
86 |
-
)
|
87 |
-
return flow, mask
|
88 |
-
|
89 |
-
|
90 |
-
class IFNet(nn.Module):
|
91 |
-
def __init__(self):
|
92 |
-
super(IFNet, self).__init__()
|
93 |
-
self.block0 = IFBlock(7 + 4, c=90)
|
94 |
-
self.block1 = IFBlock(7 + 4, c=90)
|
95 |
-
self.block2 = IFBlock(7 + 4, c=90)
|
96 |
-
self.block_tea = IFBlock(10 + 4, c=90)
|
97 |
-
# self.contextnet = Contextnet()
|
98 |
-
# self.unet = Unet()
|
99 |
-
|
100 |
-
def forward(self, x, scale_list=[4, 2, 1], training=False):
|
101 |
-
if training == False:
|
102 |
-
channel = x.shape[1] // 2
|
103 |
-
img0 = x[:, :channel]
|
104 |
-
img1 = x[:, channel:]
|
105 |
-
flow_list = []
|
106 |
-
merged = []
|
107 |
-
mask_list = []
|
108 |
-
warped_img0 = img0
|
109 |
-
warped_img1 = img1
|
110 |
-
flow = (x[:, :4]).detach() * 0
|
111 |
-
mask = (x[:, :1]).detach() * 0
|
112 |
-
loss_cons = 0
|
113 |
-
block = [self.block0, self.block1, self.block2]
|
114 |
-
for i in range(3):
|
115 |
-
f0, m0 = block[i](torch.cat((warped_img0[:, :3], warped_img1[:, :3], mask), 1), flow, scale=scale_list[i])
|
116 |
-
f1, m1 = block[i](
|
117 |
-
torch.cat((warped_img1[:, :3], warped_img0[:, :3], -mask), 1),
|
118 |
-
torch.cat((flow[:, 2:4], flow[:, :2]), 1),
|
119 |
-
scale=scale_list[i],
|
120 |
-
)
|
121 |
-
flow = flow + (f0 + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2
|
122 |
-
mask = mask + (m0 + (-m1)) / 2
|
123 |
-
mask_list.append(mask)
|
124 |
-
flow_list.append(flow)
|
125 |
-
warped_img0 = warp(img0, flow[:, :2])
|
126 |
-
warped_img1 = warp(img1, flow[:, 2:4])
|
127 |
-
merged.append((warped_img0, warped_img1))
|
128 |
-
"""
|
129 |
-
c0 = self.contextnet(img0, flow[:, :2])
|
130 |
-
c1 = self.contextnet(img1, flow[:, 2:4])
|
131 |
-
tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
|
132 |
-
res = tmp[:, 1:4] * 2 - 1
|
133 |
-
"""
|
134 |
-
for i in range(3):
|
135 |
-
mask_list[i] = torch.sigmoid(mask_list[i])
|
136 |
-
merged[i] = merged[i][0] * mask_list[i] + merged[i][1] * (1 - mask_list[i])
|
137 |
-
# merged[i] = torch.clamp(merged[i] + res, 0, 1)
|
138 |
-
return flow_list, mask_list[2], merged
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/IFNet_m.py
DELETED
@@ -1,127 +0,0 @@
|
|
1 |
-
from .refine import *
|
2 |
-
|
3 |
-
|
4 |
-
def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1):
|
5 |
-
return nn.Sequential(
|
6 |
-
torch.nn.ConvTranspose2d(in_channels=in_planes, out_channels=out_planes, kernel_size=4, stride=2, padding=1),
|
7 |
-
nn.PReLU(out_planes),
|
8 |
-
)
|
9 |
-
|
10 |
-
|
11 |
-
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
12 |
-
return nn.Sequential(
|
13 |
-
nn.Conv2d(
|
14 |
-
in_planes,
|
15 |
-
out_planes,
|
16 |
-
kernel_size=kernel_size,
|
17 |
-
stride=stride,
|
18 |
-
padding=padding,
|
19 |
-
dilation=dilation,
|
20 |
-
bias=True,
|
21 |
-
),
|
22 |
-
nn.PReLU(out_planes),
|
23 |
-
)
|
24 |
-
|
25 |
-
|
26 |
-
class IFBlock(nn.Module):
|
27 |
-
def __init__(self, in_planes, c=64):
|
28 |
-
super(IFBlock, self).__init__()
|
29 |
-
self.conv0 = nn.Sequential(
|
30 |
-
conv(in_planes, c // 2, 3, 2, 1),
|
31 |
-
conv(c // 2, c, 3, 2, 1),
|
32 |
-
)
|
33 |
-
self.convblock = nn.Sequential(
|
34 |
-
conv(c, c),
|
35 |
-
conv(c, c),
|
36 |
-
conv(c, c),
|
37 |
-
conv(c, c),
|
38 |
-
conv(c, c),
|
39 |
-
conv(c, c),
|
40 |
-
conv(c, c),
|
41 |
-
conv(c, c),
|
42 |
-
)
|
43 |
-
self.lastconv = nn.ConvTranspose2d(c, 5, 4, 2, 1)
|
44 |
-
|
45 |
-
def forward(self, x, flow, scale):
|
46 |
-
if scale != 1:
|
47 |
-
x = F.interpolate(x, scale_factor=1.0 / scale, mode="bilinear", align_corners=False)
|
48 |
-
if flow != None:
|
49 |
-
flow = F.interpolate(flow, scale_factor=1.0 / scale, mode="bilinear", align_corners=False) * 1.0 / scale
|
50 |
-
x = torch.cat((x, flow), 1)
|
51 |
-
x = self.conv0(x)
|
52 |
-
x = self.convblock(x) + x
|
53 |
-
tmp = self.lastconv(x)
|
54 |
-
tmp = F.interpolate(tmp, scale_factor=scale * 2, mode="bilinear", align_corners=False)
|
55 |
-
flow = tmp[:, :4] * scale * 2
|
56 |
-
mask = tmp[:, 4:5]
|
57 |
-
return flow, mask
|
58 |
-
|
59 |
-
|
60 |
-
class IFNet_m(nn.Module):
|
61 |
-
def __init__(self):
|
62 |
-
super(IFNet_m, self).__init__()
|
63 |
-
self.block0 = IFBlock(6 + 1, c=240)
|
64 |
-
self.block1 = IFBlock(13 + 4 + 1, c=150)
|
65 |
-
self.block2 = IFBlock(13 + 4 + 1, c=90)
|
66 |
-
self.block_tea = IFBlock(16 + 4 + 1, c=90)
|
67 |
-
self.contextnet = Contextnet()
|
68 |
-
self.unet = Unet()
|
69 |
-
|
70 |
-
def forward(self, x, scale=[4, 2, 1], timestep=0.5, returnflow=False):
|
71 |
-
timestep = (x[:, :1].clone() * 0 + 1) * timestep
|
72 |
-
img0 = x[:, :3]
|
73 |
-
img1 = x[:, 3:6]
|
74 |
-
gt = x[:, 6:] # In inference time, gt is None
|
75 |
-
flow_list = []
|
76 |
-
merged = []
|
77 |
-
mask_list = []
|
78 |
-
warped_img0 = img0
|
79 |
-
warped_img1 = img1
|
80 |
-
flow = None
|
81 |
-
loss_distill = 0
|
82 |
-
stu = [self.block0, self.block1, self.block2]
|
83 |
-
for i in range(3):
|
84 |
-
if flow != None:
|
85 |
-
flow_d, mask_d = stu[i](
|
86 |
-
torch.cat((img0, img1, timestep, warped_img0, warped_img1, mask), 1), flow, scale=scale[i]
|
87 |
-
)
|
88 |
-
flow = flow + flow_d
|
89 |
-
mask = mask + mask_d
|
90 |
-
else:
|
91 |
-
flow, mask = stu[i](torch.cat((img0, img1, timestep), 1), None, scale=scale[i])
|
92 |
-
mask_list.append(torch.sigmoid(mask))
|
93 |
-
flow_list.append(flow)
|
94 |
-
warped_img0 = warp(img0, flow[:, :2])
|
95 |
-
warped_img1 = warp(img1, flow[:, 2:4])
|
96 |
-
merged_student = (warped_img0, warped_img1)
|
97 |
-
merged.append(merged_student)
|
98 |
-
if gt.shape[1] == 3:
|
99 |
-
flow_d, mask_d = self.block_tea(
|
100 |
-
torch.cat((img0, img1, timestep, warped_img0, warped_img1, mask, gt), 1), flow, scale=1
|
101 |
-
)
|
102 |
-
flow_teacher = flow + flow_d
|
103 |
-
warped_img0_teacher = warp(img0, flow_teacher[:, :2])
|
104 |
-
warped_img1_teacher = warp(img1, flow_teacher[:, 2:4])
|
105 |
-
mask_teacher = torch.sigmoid(mask + mask_d)
|
106 |
-
merged_teacher = warped_img0_teacher * mask_teacher + warped_img1_teacher * (1 - mask_teacher)
|
107 |
-
else:
|
108 |
-
flow_teacher = None
|
109 |
-
merged_teacher = None
|
110 |
-
for i in range(3):
|
111 |
-
merged[i] = merged[i][0] * mask_list[i] + merged[i][1] * (1 - mask_list[i])
|
112 |
-
if gt.shape[1] == 3:
|
113 |
-
loss_mask = (
|
114 |
-
((merged[i] - gt).abs().mean(1, True) > (merged_teacher - gt).abs().mean(1, True) + 0.01)
|
115 |
-
.float()
|
116 |
-
.detach()
|
117 |
-
)
|
118 |
-
loss_distill += (((flow_teacher.detach() - flow_list[i]) ** 2).mean(1, True) ** 0.5 * loss_mask).mean()
|
119 |
-
if returnflow:
|
120 |
-
return flow
|
121 |
-
else:
|
122 |
-
c0 = self.contextnet(img0, flow[:, :2])
|
123 |
-
c1 = self.contextnet(img1, flow[:, 2:4])
|
124 |
-
tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
|
125 |
-
res = tmp[:, :3] * 2 - 1
|
126 |
-
merged[2] = torch.clamp(merged[2] + res, 0, 1)
|
127 |
-
return flow_list, mask_list[2], merged, flow_teacher, merged_teacher, loss_distill
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/RIFE.py
DELETED
@@ -1,95 +0,0 @@
|
|
1 |
-
from torch.optim import AdamW
|
2 |
-
from torch.nn.parallel import DistributedDataParallel as DDP
|
3 |
-
from .IFNet import *
|
4 |
-
from .IFNet_m import *
|
5 |
-
from .loss import *
|
6 |
-
from .laplacian import *
|
7 |
-
from .refine import *
|
8 |
-
|
9 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
10 |
-
|
11 |
-
|
12 |
-
class Model:
|
13 |
-
def __init__(self, local_rank=-1, arbitrary=False):
|
14 |
-
if arbitrary == True:
|
15 |
-
self.flownet = IFNet_m()
|
16 |
-
else:
|
17 |
-
self.flownet = IFNet()
|
18 |
-
self.device()
|
19 |
-
self.optimG = AdamW(
|
20 |
-
self.flownet.parameters(), lr=1e-6, weight_decay=1e-3
|
21 |
-
) # use large weight decay may avoid NaN loss
|
22 |
-
self.epe = EPE()
|
23 |
-
self.lap = LapLoss()
|
24 |
-
self.sobel = SOBEL()
|
25 |
-
if local_rank != -1:
|
26 |
-
self.flownet = DDP(self.flownet, device_ids=[local_rank], output_device=local_rank)
|
27 |
-
|
28 |
-
def train(self):
|
29 |
-
self.flownet.train()
|
30 |
-
|
31 |
-
def eval(self):
|
32 |
-
self.flownet.eval()
|
33 |
-
|
34 |
-
def device(self):
|
35 |
-
self.flownet.to(device)
|
36 |
-
|
37 |
-
def load_model(self, path, rank=0):
|
38 |
-
def convert(param):
|
39 |
-
return {k.replace("module.", ""): v for k, v in param.items() if "module." in k}
|
40 |
-
|
41 |
-
if rank <= 0:
|
42 |
-
self.flownet.load_state_dict(convert(torch.load("{}/flownet.pkl".format(path))))
|
43 |
-
|
44 |
-
def save_model(self, path, rank=0):
|
45 |
-
if rank == 0:
|
46 |
-
torch.save(self.flownet.state_dict(), "{}/flownet.pkl".format(path))
|
47 |
-
|
48 |
-
def inference(self, img0, img1, scale=1, scale_list=[4, 2, 1], TTA=False, timestep=0.5):
|
49 |
-
for i in range(3):
|
50 |
-
scale_list[i] = scale_list[i] * 1.0 / scale
|
51 |
-
imgs = torch.cat((img0, img1), 1)
|
52 |
-
flow, mask, merged, flow_teacher, merged_teacher, loss_distill = self.flownet(
|
53 |
-
imgs, scale_list, timestep=timestep
|
54 |
-
)
|
55 |
-
if TTA == False:
|
56 |
-
return merged[2]
|
57 |
-
else:
|
58 |
-
flow2, mask2, merged2, flow_teacher2, merged_teacher2, loss_distill2 = self.flownet(
|
59 |
-
imgs.flip(2).flip(3), scale_list, timestep=timestep
|
60 |
-
)
|
61 |
-
return (merged[2] + merged2[2].flip(2).flip(3)) / 2
|
62 |
-
|
63 |
-
def update(self, imgs, gt, learning_rate=0, mul=1, training=True, flow_gt=None):
|
64 |
-
for param_group in self.optimG.param_groups:
|
65 |
-
param_group["lr"] = learning_rate
|
66 |
-
img0 = imgs[:, :3]
|
67 |
-
img1 = imgs[:, 3:]
|
68 |
-
if training:
|
69 |
-
self.train()
|
70 |
-
else:
|
71 |
-
self.eval()
|
72 |
-
flow, mask, merged, flow_teacher, merged_teacher, loss_distill = self.flownet(
|
73 |
-
torch.cat((imgs, gt), 1), scale=[4, 2, 1]
|
74 |
-
)
|
75 |
-
loss_l1 = (self.lap(merged[2], gt)).mean()
|
76 |
-
loss_tea = (self.lap(merged_teacher, gt)).mean()
|
77 |
-
if training:
|
78 |
-
self.optimG.zero_grad()
|
79 |
-
loss_G = (
|
80 |
-
loss_l1 + loss_tea + loss_distill * 0.01
|
81 |
-
) # when training RIFEm, the weight of loss_distill should be 0.005 or 0.002
|
82 |
-
loss_G.backward()
|
83 |
-
self.optimG.step()
|
84 |
-
else:
|
85 |
-
flow_teacher = flow[2]
|
86 |
-
return merged[2], {
|
87 |
-
"merged_tea": merged_teacher,
|
88 |
-
"mask": mask,
|
89 |
-
"mask_tea": mask,
|
90 |
-
"flow": flow[2][:, :2],
|
91 |
-
"flow_tea": flow_teacher,
|
92 |
-
"loss_l1": loss_l1,
|
93 |
-
"loss_tea": loss_tea,
|
94 |
-
"loss_distill": loss_distill,
|
95 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/RIFE_HDv3.py
DELETED
@@ -1,86 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
import numpy as np
|
4 |
-
from torch.optim import AdamW
|
5 |
-
import torch.optim as optim
|
6 |
-
import itertools
|
7 |
-
from .warplayer import warp
|
8 |
-
from torch.nn.parallel import DistributedDataParallel as DDP
|
9 |
-
from .IFNet_HDv3 import *
|
10 |
-
import torch.nn.functional as F
|
11 |
-
from .loss import *
|
12 |
-
|
13 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
14 |
-
|
15 |
-
|
16 |
-
class Model:
|
17 |
-
def __init__(self, local_rank=-1):
|
18 |
-
self.flownet = IFNet()
|
19 |
-
self.device()
|
20 |
-
self.optimG = AdamW(self.flownet.parameters(), lr=1e-6, weight_decay=1e-4)
|
21 |
-
self.epe = EPE()
|
22 |
-
# self.vgg = VGGPerceptualLoss().to(device)
|
23 |
-
self.sobel = SOBEL()
|
24 |
-
if local_rank != -1:
|
25 |
-
self.flownet = DDP(self.flownet, device_ids=[local_rank], output_device=local_rank)
|
26 |
-
|
27 |
-
def train(self):
|
28 |
-
self.flownet.train()
|
29 |
-
|
30 |
-
def eval(self):
|
31 |
-
self.flownet.eval()
|
32 |
-
|
33 |
-
def device(self):
|
34 |
-
self.flownet.to(device)
|
35 |
-
|
36 |
-
def load_model(self, path, rank=0):
|
37 |
-
def convert(param):
|
38 |
-
if rank == -1:
|
39 |
-
return {k.replace("module.", ""): v for k, v in param.items() if "module." in k}
|
40 |
-
else:
|
41 |
-
return param
|
42 |
-
|
43 |
-
if rank <= 0:
|
44 |
-
if torch.cuda.is_available():
|
45 |
-
self.flownet.load_state_dict(convert(torch.load("{}/flownet.pkl".format(path))))
|
46 |
-
else:
|
47 |
-
self.flownet.load_state_dict(convert(torch.load("{}/flownet.pkl".format(path), map_location="cpu")))
|
48 |
-
|
49 |
-
def save_model(self, path, rank=0):
|
50 |
-
if rank == 0:
|
51 |
-
torch.save(self.flownet.state_dict(), "{}/flownet.pkl".format(path))
|
52 |
-
|
53 |
-
def inference(self, img0, img1, scale=1.0):
|
54 |
-
imgs = torch.cat((img0, img1), 1)
|
55 |
-
scale_list = [4 / scale, 2 / scale, 1 / scale]
|
56 |
-
flow, mask, merged = self.flownet(imgs, scale_list)
|
57 |
-
return merged[2]
|
58 |
-
|
59 |
-
def update(self, imgs, gt, learning_rate=0, mul=1, training=True, flow_gt=None):
|
60 |
-
for param_group in self.optimG.param_groups:
|
61 |
-
param_group["lr"] = learning_rate
|
62 |
-
img0 = imgs[:, :3]
|
63 |
-
img1 = imgs[:, 3:]
|
64 |
-
if training:
|
65 |
-
self.train()
|
66 |
-
else:
|
67 |
-
self.eval()
|
68 |
-
scale = [4, 2, 1]
|
69 |
-
flow, mask, merged = self.flownet(torch.cat((imgs, gt), 1), scale=scale, training=training)
|
70 |
-
loss_l1 = (merged[2] - gt).abs().mean()
|
71 |
-
loss_smooth = self.sobel(flow[2], flow[2] * 0).mean()
|
72 |
-
# loss_vgg = self.vgg(merged[2], gt)
|
73 |
-
if training:
|
74 |
-
self.optimG.zero_grad()
|
75 |
-
loss_G = loss_cons + loss_smooth * 0.1
|
76 |
-
loss_G.backward()
|
77 |
-
self.optimG.step()
|
78 |
-
else:
|
79 |
-
flow_teacher = flow[2]
|
80 |
-
return merged[2], {
|
81 |
-
"mask": mask,
|
82 |
-
"flow": flow[2][:, :2],
|
83 |
-
"loss_l1": loss_l1,
|
84 |
-
"loss_cons": loss_cons,
|
85 |
-
"loss_smooth": loss_smooth,
|
86 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/__init__.py
DELETED
File without changes
|
rife/laplacian.py
DELETED
@@ -1,69 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import numpy as np
|
3 |
-
import torch.nn as nn
|
4 |
-
import torch.nn.functional as F
|
5 |
-
|
6 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
-
|
8 |
-
import torch
|
9 |
-
|
10 |
-
|
11 |
-
def gauss_kernel(size=5, channels=3):
|
12 |
-
kernel = torch.tensor(
|
13 |
-
[
|
14 |
-
[1.0, 4.0, 6.0, 4.0, 1],
|
15 |
-
[4.0, 16.0, 24.0, 16.0, 4.0],
|
16 |
-
[6.0, 24.0, 36.0, 24.0, 6.0],
|
17 |
-
[4.0, 16.0, 24.0, 16.0, 4.0],
|
18 |
-
[1.0, 4.0, 6.0, 4.0, 1.0],
|
19 |
-
]
|
20 |
-
)
|
21 |
-
kernel /= 256.0
|
22 |
-
kernel = kernel.repeat(channels, 1, 1, 1)
|
23 |
-
kernel = kernel.to(device)
|
24 |
-
return kernel
|
25 |
-
|
26 |
-
|
27 |
-
def downsample(x):
|
28 |
-
return x[:, :, ::2, ::2]
|
29 |
-
|
30 |
-
|
31 |
-
def upsample(x):
|
32 |
-
cc = torch.cat([x, torch.zeros(x.shape[0], x.shape[1], x.shape[2], x.shape[3]).to(device)], dim=3)
|
33 |
-
cc = cc.view(x.shape[0], x.shape[1], x.shape[2] * 2, x.shape[3])
|
34 |
-
cc = cc.permute(0, 1, 3, 2)
|
35 |
-
cc = torch.cat([cc, torch.zeros(x.shape[0], x.shape[1], x.shape[3], x.shape[2] * 2).to(device)], dim=3)
|
36 |
-
cc = cc.view(x.shape[0], x.shape[1], x.shape[3] * 2, x.shape[2] * 2)
|
37 |
-
x_up = cc.permute(0, 1, 3, 2)
|
38 |
-
return conv_gauss(x_up, 4 * gauss_kernel(channels=x.shape[1]))
|
39 |
-
|
40 |
-
|
41 |
-
def conv_gauss(img, kernel):
|
42 |
-
img = torch.nn.functional.pad(img, (2, 2, 2, 2), mode="reflect")
|
43 |
-
out = torch.nn.functional.conv2d(img, kernel, groups=img.shape[1])
|
44 |
-
return out
|
45 |
-
|
46 |
-
|
47 |
-
def laplacian_pyramid(img, kernel, max_levels=3):
|
48 |
-
current = img
|
49 |
-
pyr = []
|
50 |
-
for level in range(max_levels):
|
51 |
-
filtered = conv_gauss(current, kernel)
|
52 |
-
down = downsample(filtered)
|
53 |
-
up = upsample(down)
|
54 |
-
diff = current - up
|
55 |
-
pyr.append(diff)
|
56 |
-
current = down
|
57 |
-
return pyr
|
58 |
-
|
59 |
-
|
60 |
-
class LapLoss(torch.nn.Module):
|
61 |
-
def __init__(self, max_levels=5, channels=3):
|
62 |
-
super(LapLoss, self).__init__()
|
63 |
-
self.max_levels = max_levels
|
64 |
-
self.gauss_kernel = gauss_kernel(channels=channels)
|
65 |
-
|
66 |
-
def forward(self, input, target):
|
67 |
-
pyr_input = laplacian_pyramid(img=input, kernel=self.gauss_kernel, max_levels=self.max_levels)
|
68 |
-
pyr_target = laplacian_pyramid(img=target, kernel=self.gauss_kernel, max_levels=self.max_levels)
|
69 |
-
return sum(torch.nn.functional.l1_loss(a, b) for a, b in zip(pyr_input, pyr_target))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/loss.py
DELETED
@@ -1,130 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import numpy as np
|
3 |
-
import torch.nn as nn
|
4 |
-
import torch.nn.functional as F
|
5 |
-
import torchvision.models as models
|
6 |
-
|
7 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
8 |
-
|
9 |
-
|
10 |
-
class EPE(nn.Module):
|
11 |
-
def __init__(self):
|
12 |
-
super(EPE, self).__init__()
|
13 |
-
|
14 |
-
def forward(self, flow, gt, loss_mask):
|
15 |
-
loss_map = (flow - gt.detach()) ** 2
|
16 |
-
loss_map = (loss_map.sum(1, True) + 1e-6) ** 0.5
|
17 |
-
return loss_map * loss_mask
|
18 |
-
|
19 |
-
|
20 |
-
class Ternary(nn.Module):
|
21 |
-
def __init__(self):
|
22 |
-
super(Ternary, self).__init__()
|
23 |
-
patch_size = 7
|
24 |
-
out_channels = patch_size * patch_size
|
25 |
-
self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels))
|
26 |
-
self.w = np.transpose(self.w, (3, 2, 0, 1))
|
27 |
-
self.w = torch.tensor(self.w).float().to(device)
|
28 |
-
|
29 |
-
def transform(self, img):
|
30 |
-
patches = F.conv2d(img, self.w, padding=3, bias=None)
|
31 |
-
transf = patches - img
|
32 |
-
transf_norm = transf / torch.sqrt(0.81 + transf**2)
|
33 |
-
return transf_norm
|
34 |
-
|
35 |
-
def rgb2gray(self, rgb):
|
36 |
-
r, g, b = rgb[:, 0:1, :, :], rgb[:, 1:2, :, :], rgb[:, 2:3, :, :]
|
37 |
-
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
|
38 |
-
return gray
|
39 |
-
|
40 |
-
def hamming(self, t1, t2):
|
41 |
-
dist = (t1 - t2) ** 2
|
42 |
-
dist_norm = torch.mean(dist / (0.1 + dist), 1, True)
|
43 |
-
return dist_norm
|
44 |
-
|
45 |
-
def valid_mask(self, t, padding):
|
46 |
-
n, _, h, w = t.size()
|
47 |
-
inner = torch.ones(n, 1, h - 2 * padding, w - 2 * padding).type_as(t)
|
48 |
-
mask = F.pad(inner, [padding] * 4)
|
49 |
-
return mask
|
50 |
-
|
51 |
-
def forward(self, img0, img1):
|
52 |
-
img0 = self.transform(self.rgb2gray(img0))
|
53 |
-
img1 = self.transform(self.rgb2gray(img1))
|
54 |
-
return self.hamming(img0, img1) * self.valid_mask(img0, 1)
|
55 |
-
|
56 |
-
|
57 |
-
class SOBEL(nn.Module):
|
58 |
-
def __init__(self):
|
59 |
-
super(SOBEL, self).__init__()
|
60 |
-
self.kernelX = torch.tensor(
|
61 |
-
[
|
62 |
-
[1, 0, -1],
|
63 |
-
[2, 0, -2],
|
64 |
-
[1, 0, -1],
|
65 |
-
]
|
66 |
-
).float()
|
67 |
-
self.kernelY = self.kernelX.clone().T
|
68 |
-
self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device)
|
69 |
-
self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device)
|
70 |
-
|
71 |
-
def forward(self, pred, gt):
|
72 |
-
N, C, H, W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3]
|
73 |
-
img_stack = torch.cat([pred.reshape(N * C, 1, H, W), gt.reshape(N * C, 1, H, W)], 0)
|
74 |
-
sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1)
|
75 |
-
sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1)
|
76 |
-
pred_X, gt_X = sobel_stack_x[: N * C], sobel_stack_x[N * C :]
|
77 |
-
pred_Y, gt_Y = sobel_stack_y[: N * C], sobel_stack_y[N * C :]
|
78 |
-
|
79 |
-
L1X, L1Y = torch.abs(pred_X - gt_X), torch.abs(pred_Y - gt_Y)
|
80 |
-
loss = L1X + L1Y
|
81 |
-
return loss
|
82 |
-
|
83 |
-
|
84 |
-
class MeanShift(nn.Conv2d):
|
85 |
-
def __init__(self, data_mean, data_std, data_range=1, norm=True):
|
86 |
-
c = len(data_mean)
|
87 |
-
super(MeanShift, self).__init__(c, c, kernel_size=1)
|
88 |
-
std = torch.Tensor(data_std)
|
89 |
-
self.weight.data = torch.eye(c).view(c, c, 1, 1)
|
90 |
-
if norm:
|
91 |
-
self.weight.data.div_(std.view(c, 1, 1, 1))
|
92 |
-
self.bias.data = -1 * data_range * torch.Tensor(data_mean)
|
93 |
-
self.bias.data.div_(std)
|
94 |
-
else:
|
95 |
-
self.weight.data.mul_(std.view(c, 1, 1, 1))
|
96 |
-
self.bias.data = data_range * torch.Tensor(data_mean)
|
97 |
-
self.requires_grad = False
|
98 |
-
|
99 |
-
|
100 |
-
class VGGPerceptualLoss(torch.nn.Module):
|
101 |
-
def __init__(self, rank=0):
|
102 |
-
super(VGGPerceptualLoss, self).__init__()
|
103 |
-
blocks = []
|
104 |
-
pretrained = True
|
105 |
-
self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features
|
106 |
-
self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda()
|
107 |
-
for param in self.parameters():
|
108 |
-
param.requires_grad = False
|
109 |
-
|
110 |
-
def forward(self, X, Y, indices=None):
|
111 |
-
X = self.normalize(X)
|
112 |
-
Y = self.normalize(Y)
|
113 |
-
indices = [2, 7, 12, 21, 30]
|
114 |
-
weights = [1.0 / 2.6, 1.0 / 4.8, 1.0 / 3.7, 1.0 / 5.6, 10 / 1.5]
|
115 |
-
k = 0
|
116 |
-
loss = 0
|
117 |
-
for i in range(indices[-1]):
|
118 |
-
X = self.vgg_pretrained_features[i](X)
|
119 |
-
Y = self.vgg_pretrained_features[i](Y)
|
120 |
-
if (i + 1) in indices:
|
121 |
-
loss += weights[k] * (X - Y.detach()).abs().mean() * 0.1
|
122 |
-
k += 1
|
123 |
-
return loss
|
124 |
-
|
125 |
-
|
126 |
-
if __name__ == "__main__":
|
127 |
-
img0 = torch.zeros(3, 3, 256, 256).float().to(device)
|
128 |
-
img1 = torch.tensor(np.random.normal(0, 1, (3, 3, 256, 256))).float().to(device)
|
129 |
-
ternary_loss = Ternary()
|
130 |
-
print(ternary_loss(img0, img1).shape)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/pytorch_msssim/__init__.py
DELETED
@@ -1,203 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn.functional as F
|
3 |
-
from math import exp
|
4 |
-
import numpy as np
|
5 |
-
|
6 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
-
|
8 |
-
|
9 |
-
def gaussian(window_size, sigma):
|
10 |
-
gauss = torch.Tensor([exp(-((x - window_size // 2) ** 2) / float(2 * sigma**2)) for x in range(window_size)])
|
11 |
-
return gauss / gauss.sum()
|
12 |
-
|
13 |
-
|
14 |
-
def create_window(window_size, channel=1):
|
15 |
-
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
|
16 |
-
_2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0).to(device)
|
17 |
-
window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
|
18 |
-
return window
|
19 |
-
|
20 |
-
|
21 |
-
def create_window_3d(window_size, channel=1):
|
22 |
-
_1D_window = gaussian(window_size, 1.5).unsqueeze(1)
|
23 |
-
_2D_window = _1D_window.mm(_1D_window.t())
|
24 |
-
_3D_window = _2D_window.unsqueeze(2) @ (_1D_window.t())
|
25 |
-
window = _3D_window.expand(1, channel, window_size, window_size, window_size).contiguous().to(device)
|
26 |
-
return window
|
27 |
-
|
28 |
-
|
29 |
-
def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
|
30 |
-
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
|
31 |
-
if val_range is None:
|
32 |
-
if torch.max(img1) > 128:
|
33 |
-
max_val = 255
|
34 |
-
else:
|
35 |
-
max_val = 1
|
36 |
-
|
37 |
-
if torch.min(img1) < -0.5:
|
38 |
-
min_val = -1
|
39 |
-
else:
|
40 |
-
min_val = 0
|
41 |
-
L = max_val - min_val
|
42 |
-
else:
|
43 |
-
L = val_range
|
44 |
-
|
45 |
-
padd = 0
|
46 |
-
(_, channel, height, width) = img1.size()
|
47 |
-
if window is None:
|
48 |
-
real_size = min(window_size, height, width)
|
49 |
-
window = create_window(real_size, channel=channel).to(img1.device)
|
50 |
-
|
51 |
-
# mu1 = F.conv2d(img1, window, padding=padd, groups=channel)
|
52 |
-
# mu2 = F.conv2d(img2, window, padding=padd, groups=channel)
|
53 |
-
mu1 = F.conv2d(F.pad(img1, (5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=channel)
|
54 |
-
mu2 = F.conv2d(F.pad(img2, (5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=channel)
|
55 |
-
|
56 |
-
mu1_sq = mu1.pow(2)
|
57 |
-
mu2_sq = mu2.pow(2)
|
58 |
-
mu1_mu2 = mu1 * mu2
|
59 |
-
|
60 |
-
sigma1_sq = F.conv2d(F.pad(img1 * img1, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu1_sq
|
61 |
-
sigma2_sq = F.conv2d(F.pad(img2 * img2, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu2_sq
|
62 |
-
sigma12 = F.conv2d(F.pad(img1 * img2, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu1_mu2
|
63 |
-
|
64 |
-
C1 = (0.01 * L) ** 2
|
65 |
-
C2 = (0.03 * L) ** 2
|
66 |
-
|
67 |
-
v1 = 2.0 * sigma12 + C2
|
68 |
-
v2 = sigma1_sq + sigma2_sq + C2
|
69 |
-
cs = torch.mean(v1 / v2) # contrast sensitivity
|
70 |
-
|
71 |
-
ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
|
72 |
-
|
73 |
-
if size_average:
|
74 |
-
ret = ssim_map.mean()
|
75 |
-
else:
|
76 |
-
ret = ssim_map.mean(1).mean(1).mean(1)
|
77 |
-
|
78 |
-
if full:
|
79 |
-
return ret, cs
|
80 |
-
return ret
|
81 |
-
|
82 |
-
|
83 |
-
def ssim_matlab(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
|
84 |
-
# Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).
|
85 |
-
if val_range is None:
|
86 |
-
if torch.max(img1) > 128:
|
87 |
-
max_val = 255
|
88 |
-
else:
|
89 |
-
max_val = 1
|
90 |
-
|
91 |
-
if torch.min(img1) < -0.5:
|
92 |
-
min_val = -1
|
93 |
-
else:
|
94 |
-
min_val = 0
|
95 |
-
L = max_val - min_val
|
96 |
-
else:
|
97 |
-
L = val_range
|
98 |
-
|
99 |
-
padd = 0
|
100 |
-
(_, _, height, width) = img1.size()
|
101 |
-
if window is None:
|
102 |
-
real_size = min(window_size, height, width)
|
103 |
-
window = create_window_3d(real_size, channel=1).to(img1.device, dtype=img1.dtype)
|
104 |
-
# Channel is set to 1 since we consider color images as volumetric images
|
105 |
-
|
106 |
-
img1 = img1.unsqueeze(1)
|
107 |
-
img2 = img2.unsqueeze(1)
|
108 |
-
|
109 |
-
mu1 = F.conv3d(F.pad(img1, (5, 5, 5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=1)
|
110 |
-
mu2 = F.conv3d(F.pad(img2, (5, 5, 5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=1)
|
111 |
-
|
112 |
-
mu1_sq = mu1.pow(2)
|
113 |
-
mu2_sq = mu2.pow(2)
|
114 |
-
mu1_mu2 = mu1 * mu2
|
115 |
-
|
116 |
-
sigma1_sq = F.conv3d(F.pad(img1 * img1, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu1_sq
|
117 |
-
sigma2_sq = F.conv3d(F.pad(img2 * img2, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu2_sq
|
118 |
-
sigma12 = F.conv3d(F.pad(img1 * img2, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu1_mu2
|
119 |
-
|
120 |
-
C1 = (0.01 * L) ** 2
|
121 |
-
C2 = (0.03 * L) ** 2
|
122 |
-
|
123 |
-
v1 = 2.0 * sigma12 + C2
|
124 |
-
v2 = sigma1_sq + sigma2_sq + C2
|
125 |
-
cs = torch.mean(v1 / v2) # contrast sensitivity
|
126 |
-
|
127 |
-
ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
|
128 |
-
|
129 |
-
if size_average:
|
130 |
-
ret = ssim_map.mean()
|
131 |
-
else:
|
132 |
-
ret = ssim_map.mean(1).mean(1).mean(1)
|
133 |
-
|
134 |
-
if full:
|
135 |
-
return ret, cs
|
136 |
-
return ret
|
137 |
-
|
138 |
-
|
139 |
-
def msssim(img1, img2, window_size=11, size_average=True, val_range=None, normalize=False):
|
140 |
-
device = img1.device
|
141 |
-
weights = torch.FloatTensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]).to(device)
|
142 |
-
levels = weights.size()[0]
|
143 |
-
mssim = []
|
144 |
-
mcs = []
|
145 |
-
for _ in range(levels):
|
146 |
-
sim, cs = ssim(img1, img2, window_size=window_size, size_average=size_average, full=True, val_range=val_range)
|
147 |
-
mssim.append(sim)
|
148 |
-
mcs.append(cs)
|
149 |
-
|
150 |
-
img1 = F.avg_pool2d(img1, (2, 2))
|
151 |
-
img2 = F.avg_pool2d(img2, (2, 2))
|
152 |
-
|
153 |
-
mssim = torch.stack(mssim)
|
154 |
-
mcs = torch.stack(mcs)
|
155 |
-
|
156 |
-
# Normalize (to avoid NaNs during training unstable models, not compliant with original definition)
|
157 |
-
if normalize:
|
158 |
-
mssim = (mssim + 1) / 2
|
159 |
-
mcs = (mcs + 1) / 2
|
160 |
-
|
161 |
-
pow1 = mcs**weights
|
162 |
-
pow2 = mssim**weights
|
163 |
-
# From Matlab implementation https://ece.uwaterloo.ca/~z70wang/research/iwssim/
|
164 |
-
output = torch.prod(pow1[:-1] * pow2[-1])
|
165 |
-
return output
|
166 |
-
|
167 |
-
|
168 |
-
# Classes to re-use window
|
169 |
-
class SSIM(torch.nn.Module):
|
170 |
-
def __init__(self, window_size=11, size_average=True, val_range=None):
|
171 |
-
super(SSIM, self).__init__()
|
172 |
-
self.window_size = window_size
|
173 |
-
self.size_average = size_average
|
174 |
-
self.val_range = val_range
|
175 |
-
|
176 |
-
# Assume 3 channel for SSIM
|
177 |
-
self.channel = 3
|
178 |
-
self.window = create_window(window_size, channel=self.channel)
|
179 |
-
|
180 |
-
def forward(self, img1, img2):
|
181 |
-
(_, channel, _, _) = img1.size()
|
182 |
-
|
183 |
-
if channel == self.channel and self.window.dtype == img1.dtype:
|
184 |
-
window = self.window
|
185 |
-
else:
|
186 |
-
window = create_window(self.window_size, channel).to(img1.device).type(img1.dtype)
|
187 |
-
self.window = window
|
188 |
-
self.channel = channel
|
189 |
-
|
190 |
-
_ssim = ssim(img1, img2, window=window, window_size=self.window_size, size_average=self.size_average)
|
191 |
-
dssim = (1 - _ssim) / 2
|
192 |
-
return dssim
|
193 |
-
|
194 |
-
|
195 |
-
class MSSSIM(torch.nn.Module):
|
196 |
-
def __init__(self, window_size=11, size_average=True, channel=3):
|
197 |
-
super(MSSSIM, self).__init__()
|
198 |
-
self.window_size = window_size
|
199 |
-
self.size_average = size_average
|
200 |
-
self.channel = channel
|
201 |
-
|
202 |
-
def forward(self, img1, img2):
|
203 |
-
return msssim(img1, img2, window_size=self.window_size, size_average=self.size_average)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/refine.py
DELETED
@@ -1,107 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
from .warplayer import warp
|
4 |
-
import torch.nn.functional as F
|
5 |
-
|
6 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
-
|
8 |
-
|
9 |
-
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
10 |
-
return nn.Sequential(
|
11 |
-
nn.Conv2d(
|
12 |
-
in_planes,
|
13 |
-
out_planes,
|
14 |
-
kernel_size=kernel_size,
|
15 |
-
stride=stride,
|
16 |
-
padding=padding,
|
17 |
-
dilation=dilation,
|
18 |
-
bias=True,
|
19 |
-
),
|
20 |
-
nn.PReLU(out_planes),
|
21 |
-
)
|
22 |
-
|
23 |
-
|
24 |
-
def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1):
|
25 |
-
return nn.Sequential(
|
26 |
-
torch.nn.ConvTranspose2d(
|
27 |
-
in_channels=in_planes, out_channels=out_planes, kernel_size=4, stride=2, padding=1, bias=True
|
28 |
-
),
|
29 |
-
nn.PReLU(out_planes),
|
30 |
-
)
|
31 |
-
|
32 |
-
|
33 |
-
class Conv2(nn.Module):
|
34 |
-
def __init__(self, in_planes, out_planes, stride=2):
|
35 |
-
super(Conv2, self).__init__()
|
36 |
-
self.conv1 = conv(in_planes, out_planes, 3, stride, 1)
|
37 |
-
self.conv2 = conv(out_planes, out_planes, 3, 1, 1)
|
38 |
-
|
39 |
-
def forward(self, x):
|
40 |
-
x = self.conv1(x)
|
41 |
-
x = self.conv2(x)
|
42 |
-
return x
|
43 |
-
|
44 |
-
|
45 |
-
c = 16
|
46 |
-
|
47 |
-
|
48 |
-
class Contextnet(nn.Module):
|
49 |
-
def __init__(self):
|
50 |
-
super(Contextnet, self).__init__()
|
51 |
-
self.conv1 = Conv2(3, c)
|
52 |
-
self.conv2 = Conv2(c, 2 * c)
|
53 |
-
self.conv3 = Conv2(2 * c, 4 * c)
|
54 |
-
self.conv4 = Conv2(4 * c, 8 * c)
|
55 |
-
|
56 |
-
def forward(self, x, flow):
|
57 |
-
x = self.conv1(x)
|
58 |
-
flow = (
|
59 |
-
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
60 |
-
* 0.5
|
61 |
-
)
|
62 |
-
f1 = warp(x, flow)
|
63 |
-
x = self.conv2(x)
|
64 |
-
flow = (
|
65 |
-
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
66 |
-
* 0.5
|
67 |
-
)
|
68 |
-
f2 = warp(x, flow)
|
69 |
-
x = self.conv3(x)
|
70 |
-
flow = (
|
71 |
-
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
72 |
-
* 0.5
|
73 |
-
)
|
74 |
-
f3 = warp(x, flow)
|
75 |
-
x = self.conv4(x)
|
76 |
-
flow = (
|
77 |
-
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
78 |
-
* 0.5
|
79 |
-
)
|
80 |
-
f4 = warp(x, flow)
|
81 |
-
return [f1, f2, f3, f4]
|
82 |
-
|
83 |
-
|
84 |
-
class Unet(nn.Module):
|
85 |
-
def __init__(self):
|
86 |
-
super(Unet, self).__init__()
|
87 |
-
self.down0 = Conv2(17, 2 * c)
|
88 |
-
self.down1 = Conv2(4 * c, 4 * c)
|
89 |
-
self.down2 = Conv2(8 * c, 8 * c)
|
90 |
-
self.down3 = Conv2(16 * c, 16 * c)
|
91 |
-
self.up0 = deconv(32 * c, 8 * c)
|
92 |
-
self.up1 = deconv(16 * c, 4 * c)
|
93 |
-
self.up2 = deconv(8 * c, 2 * c)
|
94 |
-
self.up3 = deconv(4 * c, c)
|
95 |
-
self.conv = nn.Conv2d(c, 3, 3, 1, 1)
|
96 |
-
|
97 |
-
def forward(self, img0, img1, warped_img0, warped_img1, mask, flow, c0, c1):
|
98 |
-
s0 = self.down0(torch.cat((img0, img1, warped_img0, warped_img1, mask, flow), 1))
|
99 |
-
s1 = self.down1(torch.cat((s0, c0[0], c1[0]), 1))
|
100 |
-
s2 = self.down2(torch.cat((s1, c0[1], c1[1]), 1))
|
101 |
-
s3 = self.down3(torch.cat((s2, c0[2], c1[2]), 1))
|
102 |
-
x = self.up0(torch.cat((s3, c0[3], c1[3]), 1))
|
103 |
-
x = self.up1(torch.cat((x, s2), 1))
|
104 |
-
x = self.up2(torch.cat((x, s1), 1))
|
105 |
-
x = self.up3(torch.cat((x, s0), 1))
|
106 |
-
x = self.conv(x)
|
107 |
-
return torch.sigmoid(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/refine_2R.py
DELETED
@@ -1,104 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
from .warplayer import warp
|
4 |
-
import torch.nn.functional as F
|
5 |
-
|
6 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
-
|
8 |
-
|
9 |
-
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
10 |
-
return nn.Sequential(
|
11 |
-
nn.Conv2d(
|
12 |
-
in_planes,
|
13 |
-
out_planes,
|
14 |
-
kernel_size=kernel_size,
|
15 |
-
stride=stride,
|
16 |
-
padding=padding,
|
17 |
-
dilation=dilation,
|
18 |
-
bias=True,
|
19 |
-
),
|
20 |
-
nn.PReLU(out_planes),
|
21 |
-
)
|
22 |
-
|
23 |
-
|
24 |
-
def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1):
|
25 |
-
return nn.Sequential(
|
26 |
-
torch.nn.ConvTranspose2d(
|
27 |
-
in_channels=in_planes, out_channels=out_planes, kernel_size=4, stride=2, padding=1, bias=True
|
28 |
-
),
|
29 |
-
nn.PReLU(out_planes),
|
30 |
-
)
|
31 |
-
|
32 |
-
|
33 |
-
class Conv2(nn.Module):
|
34 |
-
def __init__(self, in_planes, out_planes, stride=2):
|
35 |
-
super(Conv2, self).__init__()
|
36 |
-
self.conv1 = conv(in_planes, out_planes, 3, stride, 1)
|
37 |
-
self.conv2 = conv(out_planes, out_planes, 3, 1, 1)
|
38 |
-
|
39 |
-
def forward(self, x):
|
40 |
-
x = self.conv1(x)
|
41 |
-
x = self.conv2(x)
|
42 |
-
return x
|
43 |
-
|
44 |
-
|
45 |
-
c = 16
|
46 |
-
|
47 |
-
|
48 |
-
class Contextnet(nn.Module):
|
49 |
-
def __init__(self):
|
50 |
-
super(Contextnet, self).__init__()
|
51 |
-
self.conv1 = Conv2(3, c, 1)
|
52 |
-
self.conv2 = Conv2(c, 2 * c)
|
53 |
-
self.conv3 = Conv2(2 * c, 4 * c)
|
54 |
-
self.conv4 = Conv2(4 * c, 8 * c)
|
55 |
-
|
56 |
-
def forward(self, x, flow):
|
57 |
-
x = self.conv1(x)
|
58 |
-
# flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False) * 0.5
|
59 |
-
f1 = warp(x, flow)
|
60 |
-
x = self.conv2(x)
|
61 |
-
flow = (
|
62 |
-
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
63 |
-
* 0.5
|
64 |
-
)
|
65 |
-
f2 = warp(x, flow)
|
66 |
-
x = self.conv3(x)
|
67 |
-
flow = (
|
68 |
-
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
69 |
-
* 0.5
|
70 |
-
)
|
71 |
-
f3 = warp(x, flow)
|
72 |
-
x = self.conv4(x)
|
73 |
-
flow = (
|
74 |
-
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False, recompute_scale_factor=False)
|
75 |
-
* 0.5
|
76 |
-
)
|
77 |
-
f4 = warp(x, flow)
|
78 |
-
return [f1, f2, f3, f4]
|
79 |
-
|
80 |
-
|
81 |
-
class Unet(nn.Module):
|
82 |
-
def __init__(self):
|
83 |
-
super(Unet, self).__init__()
|
84 |
-
self.down0 = Conv2(17, 2 * c, 1)
|
85 |
-
self.down1 = Conv2(4 * c, 4 * c)
|
86 |
-
self.down2 = Conv2(8 * c, 8 * c)
|
87 |
-
self.down3 = Conv2(16 * c, 16 * c)
|
88 |
-
self.up0 = deconv(32 * c, 8 * c)
|
89 |
-
self.up1 = deconv(16 * c, 4 * c)
|
90 |
-
self.up2 = deconv(8 * c, 2 * c)
|
91 |
-
self.up3 = deconv(4 * c, c)
|
92 |
-
self.conv = nn.Conv2d(c, 3, 3, 2, 1)
|
93 |
-
|
94 |
-
def forward(self, img0, img1, warped_img0, warped_img1, mask, flow, c0, c1):
|
95 |
-
s0 = self.down0(torch.cat((img0, img1, warped_img0, warped_img1, mask, flow), 1))
|
96 |
-
s1 = self.down1(torch.cat((s0, c0[0], c1[0]), 1))
|
97 |
-
s2 = self.down2(torch.cat((s1, c0[1], c1[1]), 1))
|
98 |
-
s3 = self.down3(torch.cat((s2, c0[2], c1[2]), 1))
|
99 |
-
x = self.up0(torch.cat((s3, c0[3], c1[3]), 1))
|
100 |
-
x = self.up1(torch.cat((x, s2), 1))
|
101 |
-
x = self.up2(torch.cat((x, s1), 1))
|
102 |
-
x = self.up3(torch.cat((x, s0), 1))
|
103 |
-
x = self.conv(x)
|
104 |
-
return torch.sigmoid(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife/warplayer.py
DELETED
@@ -1,34 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
|
4 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
5 |
-
backwarp_tenGrid = {}
|
6 |
-
|
7 |
-
|
8 |
-
def warp(tenInput, tenFlow):
|
9 |
-
k = (str(tenFlow.device), str(tenFlow.size()))
|
10 |
-
if k not in backwarp_tenGrid:
|
11 |
-
tenHorizontal = (
|
12 |
-
torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=device)
|
13 |
-
.view(1, 1, 1, tenFlow.shape[3])
|
14 |
-
.expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)
|
15 |
-
)
|
16 |
-
tenVertical = (
|
17 |
-
torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=device)
|
18 |
-
.view(1, 1, tenFlow.shape[2], 1)
|
19 |
-
.expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])
|
20 |
-
)
|
21 |
-
backwarp_tenGrid[k] = torch.cat([tenHorizontal, tenVertical], 1).to(device)
|
22 |
-
|
23 |
-
tenFlow = torch.cat(
|
24 |
-
[
|
25 |
-
tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),
|
26 |
-
tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0),
|
27 |
-
],
|
28 |
-
1,
|
29 |
-
)
|
30 |
-
|
31 |
-
g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)
|
32 |
-
return torch.nn.functional.grid_sample(
|
33 |
-
input=tenInput, grid=g, mode="bilinear", padding_mode="border", align_corners=True
|
34 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rife_model.py
DELETED
@@ -1,129 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
from diffusers.image_processor import VaeImageProcessor
|
3 |
-
from torch.nn import functional as F
|
4 |
-
import cv2
|
5 |
-
import utils
|
6 |
-
from rife.pytorch_msssim import ssim_matlab
|
7 |
-
import numpy as np
|
8 |
-
import logging
|
9 |
-
import skvideo.io
|
10 |
-
from rife.RIFE_HDv3 import Model
|
11 |
-
|
12 |
-
logger = logging.getLogger(__name__)
|
13 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
14 |
-
|
15 |
-
|
16 |
-
def pad_image(img, scale):
|
17 |
-
_, _, h, w = img.shape
|
18 |
-
tmp = max(32, int(32 / scale))
|
19 |
-
ph = ((h - 1) // tmp + 1) * tmp
|
20 |
-
pw = ((w - 1) // tmp + 1) * tmp
|
21 |
-
padding = (0, 0, pw - w, ph - h)
|
22 |
-
return F.pad(img, padding)
|
23 |
-
|
24 |
-
|
25 |
-
def make_inference(model, I0, I1, upscale_amount, n):
|
26 |
-
middle = model.inference(I0, I1, upscale_amount)
|
27 |
-
if n == 1:
|
28 |
-
return [middle]
|
29 |
-
first_half = make_inference(model, I0, middle, upscale_amount, n=n // 2)
|
30 |
-
second_half = make_inference(model, middle, I1, upscale_amount, n=n // 2)
|
31 |
-
if n % 2:
|
32 |
-
return [*first_half, middle, *second_half]
|
33 |
-
else:
|
34 |
-
return [*first_half, *second_half]
|
35 |
-
|
36 |
-
|
37 |
-
@torch.inference_mode()
|
38 |
-
def ssim_interpolation_rife(model, samples, exp=1, upscale_amount=1, output_device="cpu"):
|
39 |
-
|
40 |
-
output = []
|
41 |
-
# [f, c, h, w]
|
42 |
-
for b in range(samples.shape[0]):
|
43 |
-
frame = samples[b : b + 1]
|
44 |
-
_, _, h, w = frame.shape
|
45 |
-
I0 = samples[b : b + 1]
|
46 |
-
I1 = samples[b + 1 : b + 2] if b + 2 < samples.shape[0] else samples[-1:]
|
47 |
-
I1 = pad_image(I1, upscale_amount)
|
48 |
-
# [c, h, w]
|
49 |
-
I0_small = F.interpolate(I0, (32, 32), mode="bilinear", align_corners=False)
|
50 |
-
I1_small = F.interpolate(I1, (32, 32), mode="bilinear", align_corners=False)
|
51 |
-
|
52 |
-
ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3])
|
53 |
-
|
54 |
-
if ssim > 0.996:
|
55 |
-
I1 = I0
|
56 |
-
I1 = pad_image(I1, upscale_amount)
|
57 |
-
I1 = make_inference(model, I0, I1, upscale_amount, 1)
|
58 |
-
|
59 |
-
I1_small = F.interpolate(I1[0], (32, 32), mode="bilinear", align_corners=False)
|
60 |
-
ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3])
|
61 |
-
frame = I1[0]
|
62 |
-
I1 = I1[0]
|
63 |
-
|
64 |
-
tmp_output = []
|
65 |
-
if ssim < 0.2:
|
66 |
-
for i in range((2**exp) - 1):
|
67 |
-
tmp_output.append(I0)
|
68 |
-
|
69 |
-
else:
|
70 |
-
tmp_output = make_inference(model, I0, I1, upscale_amount, 2**exp - 1) if exp else []
|
71 |
-
|
72 |
-
frame = pad_image(frame, upscale_amount)
|
73 |
-
tmp_output = [frame] + tmp_output
|
74 |
-
for i, frame in enumerate(tmp_output):
|
75 |
-
output.append(frame.to(output_device))
|
76 |
-
return output
|
77 |
-
|
78 |
-
|
79 |
-
def load_rife_model(model_path):
|
80 |
-
model = Model()
|
81 |
-
model.load_model(model_path, -1)
|
82 |
-
model.eval()
|
83 |
-
return model
|
84 |
-
|
85 |
-
|
86 |
-
# Create a generator that yields each frame, similar to cv2.VideoCapture
|
87 |
-
def frame_generator(video_capture):
|
88 |
-
while True:
|
89 |
-
ret, frame = video_capture.read()
|
90 |
-
if not ret:
|
91 |
-
break
|
92 |
-
yield frame
|
93 |
-
video_capture.release()
|
94 |
-
|
95 |
-
|
96 |
-
def rife_inference_with_path(model, video_path):
|
97 |
-
video_capture = cv2.VideoCapture(video_path)
|
98 |
-
tot_frame = video_capture.get(cv2.CAP_PROP_FRAME_COUNT)
|
99 |
-
pt_frame_data = []
|
100 |
-
pt_frame = skvideo.io.vreader(video_path)
|
101 |
-
for frame in pt_frame:
|
102 |
-
pt_frame_data.append(
|
103 |
-
torch.from_numpy(np.transpose(frame, (2, 0, 1))).to("cpu", non_blocking=True).float() / 255.0
|
104 |
-
)
|
105 |
-
|
106 |
-
pt_frame = torch.from_numpy(np.stack(pt_frame_data))
|
107 |
-
pt_frame = pt_frame.to(device)
|
108 |
-
pbar = utils.ProgressBar(tot_frame, desc="RIFE inference")
|
109 |
-
frames = ssim_interpolation_rife(model, pt_frame)
|
110 |
-
pt_image = torch.stack([frames[i].squeeze(0) for i in range(len(frames))])
|
111 |
-
image_np = VaeImageProcessor.pt_to_numpy(pt_image) # (to [49, 512, 480, 3])
|
112 |
-
image_pil = VaeImageProcessor.numpy_to_pil(image_np)
|
113 |
-
video_path = utils.save_video(image_pil, fps=16)
|
114 |
-
if pbar:
|
115 |
-
pbar.update(1)
|
116 |
-
return video_path
|
117 |
-
|
118 |
-
|
119 |
-
def rife_inference_with_latents(model, latents):
|
120 |
-
rife_results = []
|
121 |
-
latents = latents.to(device)
|
122 |
-
for i in range(latents.size(0)):
|
123 |
-
# [f, c, w, h]
|
124 |
-
latent = latents[i]
|
125 |
-
frames = ssim_interpolation_rife(model, latent)
|
126 |
-
pt_image = torch.stack([frames[i].squeeze(0) for i in range(len(frames))]) # (to [f, c, w, h])
|
127 |
-
rife_results.append(pt_image)
|
128 |
-
|
129 |
-
return torch.stack(rife_results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils.py
DELETED
@@ -1,221 +0,0 @@
|
|
1 |
-
import math
|
2 |
-
from typing import Union, List
|
3 |
-
|
4 |
-
import torch
|
5 |
-
import os
|
6 |
-
from datetime import datetime
|
7 |
-
import numpy as np
|
8 |
-
import itertools
|
9 |
-
import PIL.Image
|
10 |
-
import safetensors.torch
|
11 |
-
import tqdm
|
12 |
-
import logging
|
13 |
-
from diffusers.utils import export_to_video
|
14 |
-
from spandrel import ModelLoader
|
15 |
-
|
16 |
-
logger = logging.getLogger(__file__)
|
17 |
-
|
18 |
-
|
19 |
-
def load_torch_file(ckpt, device=None, dtype=torch.float16):
|
20 |
-
if device is None:
|
21 |
-
device = torch.device("cpu")
|
22 |
-
if ckpt.lower().endswith(".safetensors") or ckpt.lower().endswith(".sft"):
|
23 |
-
sd = safetensors.torch.load_file(ckpt, device=device.type)
|
24 |
-
else:
|
25 |
-
if not "weights_only" in torch.load.__code__.co_varnames:
|
26 |
-
logger.warning(
|
27 |
-
"Warning torch.load doesn't support weights_only on this pytorch version, loading unsafely."
|
28 |
-
)
|
29 |
-
|
30 |
-
pl_sd = torch.load(ckpt, map_location=device, weights_only=True)
|
31 |
-
if "global_step" in pl_sd:
|
32 |
-
logger.debug(f"Global Step: {pl_sd['global_step']}")
|
33 |
-
if "state_dict" in pl_sd:
|
34 |
-
sd = pl_sd["state_dict"]
|
35 |
-
elif "params_ema" in pl_sd:
|
36 |
-
sd = pl_sd["params_ema"]
|
37 |
-
else:
|
38 |
-
sd = pl_sd
|
39 |
-
|
40 |
-
sd = {k: v.to(dtype) for k, v in sd.items()}
|
41 |
-
return sd
|
42 |
-
|
43 |
-
|
44 |
-
def state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=False):
|
45 |
-
if filter_keys:
|
46 |
-
out = {}
|
47 |
-
else:
|
48 |
-
out = state_dict
|
49 |
-
for rp in replace_prefix:
|
50 |
-
replace = list(
|
51 |
-
map(
|
52 |
-
lambda a: (a, "{}{}".format(replace_prefix[rp], a[len(rp) :])),
|
53 |
-
filter(lambda a: a.startswith(rp), state_dict.keys()),
|
54 |
-
)
|
55 |
-
)
|
56 |
-
for x in replace:
|
57 |
-
w = state_dict.pop(x[0])
|
58 |
-
out[x[1]] = w
|
59 |
-
return out
|
60 |
-
|
61 |
-
|
62 |
-
def module_size(module):
|
63 |
-
module_mem = 0
|
64 |
-
sd = module.state_dict()
|
65 |
-
for k in sd:
|
66 |
-
t = sd[k]
|
67 |
-
module_mem += t.nelement() * t.element_size()
|
68 |
-
return module_mem
|
69 |
-
|
70 |
-
|
71 |
-
def get_tiled_scale_steps(width, height, tile_x, tile_y, overlap):
|
72 |
-
return math.ceil((height / (tile_y - overlap))) * math.ceil((width / (tile_x - overlap)))
|
73 |
-
|
74 |
-
|
75 |
-
@torch.inference_mode()
|
76 |
-
def tiled_scale_multidim(
|
77 |
-
samples, function, tile=(64, 64), overlap=8, upscale_amount=4, out_channels=3, output_device="cpu", pbar=None
|
78 |
-
):
|
79 |
-
dims = len(tile)
|
80 |
-
print(f"samples dtype:{samples.dtype}")
|
81 |
-
output = torch.empty(
|
82 |
-
[samples.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), samples.shape[2:])),
|
83 |
-
device=output_device,
|
84 |
-
)
|
85 |
-
|
86 |
-
for b in range(samples.shape[0]):
|
87 |
-
s = samples[b : b + 1]
|
88 |
-
out = torch.zeros(
|
89 |
-
[s.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), s.shape[2:])),
|
90 |
-
device=output_device,
|
91 |
-
)
|
92 |
-
out_div = torch.zeros(
|
93 |
-
[s.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), s.shape[2:])),
|
94 |
-
device=output_device,
|
95 |
-
)
|
96 |
-
|
97 |
-
for it in itertools.product(*map(lambda a: range(0, a[0], a[1] - overlap), zip(s.shape[2:], tile))):
|
98 |
-
s_in = s
|
99 |
-
upscaled = []
|
100 |
-
|
101 |
-
for d in range(dims):
|
102 |
-
pos = max(0, min(s.shape[d + 2] - overlap, it[d]))
|
103 |
-
l = min(tile[d], s.shape[d + 2] - pos)
|
104 |
-
s_in = s_in.narrow(d + 2, pos, l)
|
105 |
-
upscaled.append(round(pos * upscale_amount))
|
106 |
-
|
107 |
-
ps = function(s_in).to(output_device)
|
108 |
-
mask = torch.ones_like(ps)
|
109 |
-
feather = round(overlap * upscale_amount)
|
110 |
-
for t in range(feather):
|
111 |
-
for d in range(2, dims + 2):
|
112 |
-
m = mask.narrow(d, t, 1)
|
113 |
-
m *= (1.0 / feather) * (t + 1)
|
114 |
-
m = mask.narrow(d, mask.shape[d] - 1 - t, 1)
|
115 |
-
m *= (1.0 / feather) * (t + 1)
|
116 |
-
|
117 |
-
o = out
|
118 |
-
o_d = out_div
|
119 |
-
for d in range(dims):
|
120 |
-
o = o.narrow(d + 2, upscaled[d], mask.shape[d + 2])
|
121 |
-
o_d = o_d.narrow(d + 2, upscaled[d], mask.shape[d + 2])
|
122 |
-
|
123 |
-
o += ps * mask
|
124 |
-
o_d += mask
|
125 |
-
|
126 |
-
if pbar is not None:
|
127 |
-
pbar.update(1)
|
128 |
-
|
129 |
-
output[b : b + 1] = out / out_div
|
130 |
-
return output
|
131 |
-
|
132 |
-
|
133 |
-
def tiled_scale(
|
134 |
-
samples,
|
135 |
-
function,
|
136 |
-
tile_x=64,
|
137 |
-
tile_y=64,
|
138 |
-
overlap=8,
|
139 |
-
upscale_amount=4,
|
140 |
-
out_channels=3,
|
141 |
-
output_device="cpu",
|
142 |
-
pbar=None,
|
143 |
-
):
|
144 |
-
return tiled_scale_multidim(
|
145 |
-
samples, function, (tile_y, tile_x), overlap, upscale_amount, out_channels, output_device, pbar
|
146 |
-
)
|
147 |
-
|
148 |
-
|
149 |
-
def load_sd_upscale(ckpt, inf_device):
|
150 |
-
sd = load_torch_file(ckpt, device=inf_device)
|
151 |
-
if "module.layers.0.residual_group.blocks.0.norm1.weight" in sd:
|
152 |
-
sd = state_dict_prefix_replace(sd, {"module.": ""})
|
153 |
-
out = ModelLoader().load_from_state_dict(sd).half()
|
154 |
-
return out
|
155 |
-
|
156 |
-
|
157 |
-
def upscale(upscale_model, tensor: torch.Tensor, inf_device, output_device="cpu") -> torch.Tensor:
|
158 |
-
memory_required = module_size(upscale_model.model)
|
159 |
-
memory_required += (
|
160 |
-
(512 * 512 * 3) * tensor.element_size() * max(upscale_model.scale, 1.0) * 384.0
|
161 |
-
) # The 384.0 is an estimate of how much some of these models take, TODO: make it more accurate
|
162 |
-
memory_required += tensor.nelement() * tensor.element_size()
|
163 |
-
print(f"UPScaleMemory required: {memory_required / 1024 / 1024 / 1024} GB")
|
164 |
-
|
165 |
-
upscale_model.to(inf_device)
|
166 |
-
tile = 512
|
167 |
-
overlap = 32
|
168 |
-
|
169 |
-
steps = tensor.shape[0] * get_tiled_scale_steps(
|
170 |
-
tensor.shape[3], tensor.shape[2], tile_x=tile, tile_y=tile, overlap=overlap
|
171 |
-
)
|
172 |
-
|
173 |
-
pbar = ProgressBar(steps, desc="Tiling and Upscaling")
|
174 |
-
|
175 |
-
s = tiled_scale(
|
176 |
-
samples=tensor.to(torch.float16),
|
177 |
-
function=lambda a: upscale_model(a),
|
178 |
-
tile_x=tile,
|
179 |
-
tile_y=tile,
|
180 |
-
overlap=overlap,
|
181 |
-
upscale_amount=upscale_model.scale,
|
182 |
-
pbar=pbar,
|
183 |
-
)
|
184 |
-
|
185 |
-
upscale_model.to(output_device)
|
186 |
-
return s
|
187 |
-
|
188 |
-
|
189 |
-
def upscale_batch_and_concatenate(upscale_model, latents, inf_device, output_device="cpu") -> torch.Tensor:
|
190 |
-
upscaled_latents = []
|
191 |
-
for i in range(latents.size(0)):
|
192 |
-
latent = latents[i]
|
193 |
-
upscaled_latent = upscale(upscale_model, latent, inf_device, output_device)
|
194 |
-
upscaled_latents.append(upscaled_latent)
|
195 |
-
return torch.stack(upscaled_latents)
|
196 |
-
|
197 |
-
|
198 |
-
def save_video(tensor: Union[List[np.ndarray], List[PIL.Image.Image]], fps: int = 8):
|
199 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
200 |
-
video_path = f"./output/{timestamp}.mp4"
|
201 |
-
os.makedirs(os.path.dirname(video_path), exist_ok=True)
|
202 |
-
export_to_video(tensor, video_path, fps=fps)
|
203 |
-
return video_path
|
204 |
-
|
205 |
-
|
206 |
-
class ProgressBar:
|
207 |
-
def __init__(self, total, desc=None):
|
208 |
-
self.total = total
|
209 |
-
self.current = 0
|
210 |
-
self.b_unit = tqdm.tqdm(total=total, desc="ProgressBar context index: 0" if desc is None else desc)
|
211 |
-
|
212 |
-
def update(self, value):
|
213 |
-
if value > self.total:
|
214 |
-
value = self.total
|
215 |
-
self.current = value
|
216 |
-
if self.b_unit is not None:
|
217 |
-
self.b_unit.set_description("ProgressBar context index: {}".format(self.current))
|
218 |
-
self.b_unit.refresh()
|
219 |
-
|
220 |
-
# 更新进度
|
221 |
-
self.b_unit.update(self.current)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|