陈硕 commited on
Commit
d061c3e
1 Parent(s): 297746c

Add application file

Browse files
app.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=your_base_url python app.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 PIL import Image
21
+ from diffusers import (
22
+ CogVideoXPipeline,
23
+ CogVideoXDPMScheduler,
24
+ CogVideoXVideoToVideoPipeline,
25
+ CogVideoXImageToVideoPipeline,
26
+ CogVideoXTransformer3DModel,
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
+
38
+ device = "cuda" if torch.cuda.is_available() else "cpu"
39
+
40
+ hf_hub_download(repo_id="ai-forever/Real-ESRGAN", filename="RealESRGAN_x4.pth", local_dir="model_real_esran")
41
+ snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
42
+
43
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16).to(device)
44
+ pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
45
+
46
+ pipe_image = CogVideoXImageToVideoPipeline.from_pretrained(
47
+ "THUDM/CogVideoX-5b-I2V",
48
+ transformer=CogVideoXTransformer3DModel.from_pretrained(
49
+ "THUDM/CogVideoX-5b-I2V", subfolder="transformer", torch_dtype=torch.bfloat16
50
+ ),
51
+ vae=pipe.vae,
52
+ scheduler=pipe.scheduler,
53
+ tokenizer=pipe.tokenizer,
54
+ text_encoder=pipe.text_encoder,
55
+ torch_dtype=torch.bfloat16,
56
+ )
57
+ lora_path = "your_lora_path"
58
+ lora_rank = 256
59
+ pipe_image.load_lora_weights(lora_path, weight_name="pytorch_lora_weights.safetensors", adapter_name="test_1")
60
+ pipe_image.fuse_lora(lora_scale=1 / lora_rank)
61
+ pipe_image = pipe_image.to(device)
62
+
63
+
64
+ # pipe.transformer.to(memory_format=torch.channels_last)
65
+ # pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
66
+ # pipe_image.transformer.to(memory_format=torch.channels_last)
67
+ # pipe_image.transformer = torch.compile(pipe_image.transformer, mode="max-autotune", fullgraph=True)
68
+
69
+ os.makedirs("./output", exist_ok=True)
70
+ os.makedirs("./gradio_tmp", exist_ok=True)
71
+
72
+ upscale_model = utils.load_sd_upscale("model_real_esran/RealESRGAN_x4.pth", device)
73
+ frame_interpolation_model = load_rife_model("model_rife")
74
+
75
+ sys_prompt = """You are part of a team of bots that creates videos. You work with an assistant bot that will draw anything you say in square brackets.
76
+
77
+ For example , outputting " a beautiful morning in the woods with the sun peaking through the trees " will trigger your partner bot to output an video of a forest morning , as described. You will be prompted by people looking to create detailed , amazing videos. The way to accomplish this is to take their short prompts and make them extremely detailed and descriptive.
78
+ There are a few rules to follow:
79
+
80
+ You will only ever output a single video description per user request.
81
+
82
+ When modifications are requested , you should not simply make the description longer . You should refactor the entire description to integrate the suggestions.
83
+ Other times the user will not want modifications , but instead want a new image . In this case , you should ignore your previous conversation with the user.
84
+
85
+ Video descriptions must have the same num of words as examples below. Extra words will be ignored.
86
+ """
87
+
88
+
89
+ def resize_if_unfit(input_video, progress=gr.Progress(track_tqdm=True)):
90
+ width, height = get_video_dimensions(input_video)
91
+
92
+ if width == 720 and height == 480:
93
+ processed_video = input_video
94
+ else:
95
+ processed_video = center_crop_resize(input_video)
96
+ return processed_video
97
+
98
+
99
+ def get_video_dimensions(input_video_path):
100
+ reader = imageio_ffmpeg.read_frames(input_video_path)
101
+ metadata = next(reader)
102
+ return metadata["size"]
103
+
104
+
105
+ def center_crop_resize(input_video_path, target_width=720, target_height=480):
106
+ cap = cv2.VideoCapture(input_video_path)
107
+
108
+ orig_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
109
+ orig_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
110
+ orig_fps = cap.get(cv2.CAP_PROP_FPS)
111
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
112
+
113
+ width_factor = target_width / orig_width
114
+ height_factor = target_height / orig_height
115
+ resize_factor = max(width_factor, height_factor)
116
+
117
+ inter_width = int(orig_width * resize_factor)
118
+ inter_height = int(orig_height * resize_factor)
119
+
120
+ target_fps = 8
121
+ ideal_skip = max(0, math.ceil(orig_fps / target_fps) - 1)
122
+ skip = min(5, ideal_skip) # Cap at 5
123
+
124
+ while (total_frames / (skip + 1)) < 49 and skip > 0:
125
+ skip -= 1
126
+
127
+ processed_frames = []
128
+ frame_count = 0
129
+ total_read = 0
130
+
131
+ while frame_count < 49 and total_read < total_frames:
132
+ ret, frame = cap.read()
133
+ if not ret:
134
+ break
135
+
136
+ if total_read % (skip + 1) == 0:
137
+ resized = cv2.resize(frame, (inter_width, inter_height), interpolation=cv2.INTER_AREA)
138
+
139
+ start_x = (inter_width - target_width) // 2
140
+ start_y = (inter_height - target_height) // 2
141
+ cropped = resized[start_y : start_y + target_height, start_x : start_x + target_width]
142
+
143
+ processed_frames.append(cropped)
144
+ frame_count += 1
145
+
146
+ total_read += 1
147
+
148
+ cap.release()
149
+
150
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
151
+ temp_video_path = temp_file.name
152
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
153
+ out = cv2.VideoWriter(temp_video_path, fourcc, target_fps, (target_width, target_height))
154
+
155
+ for frame in processed_frames:
156
+ out.write(frame)
157
+
158
+ out.release()
159
+
160
+ return temp_video_path
161
+
162
+
163
+ def convert_prompt(prompt: str, retry_times: int = 3) -> str:
164
+ if not os.environ.get("OPENAI_API_KEY"):
165
+ return prompt
166
+ client = OpenAI()
167
+ text = prompt.strip()
168
+
169
+ for i in range(retry_times):
170
+ response = client.chat.completions.create(
171
+ messages=[
172
+ {"role": "system", "content": sys_prompt},
173
+ {
174
+ "role": "user",
175
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"',
176
+ },
177
+ {
178
+ "role": "assistant",
179
+ "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.",
180
+ },
181
+ {
182
+ "role": "user",
183
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"',
184
+ },
185
+ {
186
+ "role": "assistant",
187
+ "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.",
188
+ },
189
+ {
190
+ "role": "user",
191
+ "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"',
192
+ },
193
+ {
194
+ "role": "assistant",
195
+ "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.",
196
+ },
197
+ {
198
+ "role": "user",
199
+ "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"',
200
+ },
201
+ ],
202
+ model="glm-4-plus",
203
+ temperature=0.01,
204
+ top_p=0.7,
205
+ stream=False,
206
+ max_tokens=200,
207
+ )
208
+ if response.choices:
209
+ return response.choices[0].message.content
210
+ return prompt
211
+
212
+
213
+ def infer(
214
+ prompt: str,
215
+ image_input: str,
216
+ num_inference_steps: int,
217
+ guidance_scale: float,
218
+ seed: int = -1,
219
+ progress=gr.Progress(track_tqdm=True),
220
+ ):
221
+ if seed == -1:
222
+ seed = random.randint(0, 2**8 - 1)
223
+
224
+ # if video_input is not None:
225
+ # video = load_video(video_input)[:49] # Limit to 49 frames
226
+ # video_pt = pipe_video(
227
+ # video=video,
228
+ # prompt=prompt,
229
+ # num_inference_steps=num_inference_steps,
230
+ # num_videos_per_prompt=1,
231
+ # strength=video_strenght,
232
+ # use_dynamic_cfg=True,
233
+ # output_type="pt",
234
+ # guidance_scale=guidance_scale,
235
+ # generator=torch.Generator(device="cpu").manual_seed(seed),
236
+ # ).frames
237
+ if image_input is not None:
238
+ image_input = Image.fromarray(image_input).resize(size=(720, 480)) # Convert to PIL
239
+ image = load_image(image_input)
240
+ video_pt = pipe_image(
241
+ image=image,
242
+ prompt=prompt,
243
+ num_inference_steps=num_inference_steps,
244
+ num_videos_per_prompt=1,
245
+ use_dynamic_cfg=True,
246
+ output_type="pt",
247
+ guidance_scale=guidance_scale,
248
+ generator=torch.Generator(device="cpu").manual_seed(seed),
249
+ ).frames
250
+ else:
251
+ video_pt = pipe(
252
+ prompt=prompt,
253
+ num_videos_per_prompt=1,
254
+ num_inference_steps=num_inference_steps,
255
+ num_frames=49,
256
+ use_dynamic_cfg=True,
257
+ output_type="pt",
258
+ guidance_scale=guidance_scale,
259
+ generator=torch.Generator(device="cpu").manual_seed(seed),
260
+ ).frames
261
+
262
+ return (video_pt, seed)
263
+
264
+
265
+ def convert_to_gif(video_path):
266
+ clip = mp.VideoFileClip(video_path)
267
+ clip = clip.set_fps(8)
268
+ clip = clip.resize(height=240)
269
+ gif_path = video_path.replace(".mp4", ".gif")
270
+ clip.write_gif(gif_path, fps=8)
271
+ return gif_path
272
+
273
+
274
+ def delete_old_files():
275
+ while True:
276
+ now = datetime.now()
277
+ cutoff = now - timedelta(minutes=10)
278
+ directories = ["./output", "./gradio_tmp"]
279
+
280
+ for directory in directories:
281
+ for filename in os.listdir(directory):
282
+ file_path = os.path.join(directory, filename)
283
+ if os.path.isfile(file_path):
284
+ file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
285
+ if file_mtime < cutoff:
286
+ os.remove(file_path)
287
+ time.sleep(600)
288
+
289
+
290
+ threading.Thread(target=delete_old_files, daemon=True).start()
291
+ examples_images = [["example_images/beef.png"], ["example_images/candle.png"], ["example_images/person.png"]]
292
+
293
+ with gr.Blocks() as demo:
294
+ gr.Markdown("""
295
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
296
+ DimensionX Demo
297
+ </div>
298
+ <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
299
+ ⚠️ This demo is for academic research and experiential use only.
300
+ </div>
301
+ """)
302
+ with gr.Row():
303
+ with gr.Column():
304
+ with gr.Accordion("I2V: Image Input (cannot be used simultaneously with video input)", open=False):
305
+ image_input = gr.Image(label="Input Image (will be cropped to 720 * 480)")
306
+ examples_component_images = gr.Examples(examples_images, inputs=[image_input], cache_examples=False)
307
+ # with gr.Accordion("V2V: Video Input (cannot be used simultaneously with image input)", open=False):
308
+ # video_input = gr.Video(label="Input Video (will be cropped to 49 frames, 6 seconds at 8fps)")
309
+ # strength = gr.Slider(0.1, 1.0, value=0.8, step=0.01, label="Strength")
310
+ # examples_component_videos = gr.Examples(examples_videos, inputs=[video_input], cache_examples=False)
311
+ prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
312
+
313
+ with gr.Row():
314
+ gr.Markdown(
315
+ "✨Upon pressing the enhanced prompt button, we will use [GLM-4 Model](https://github.com/THUDM/GLM-4) to polish the prompt and overwrite the original one."
316
+ )
317
+ enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
318
+ with gr.Group():
319
+ with gr.Column():
320
+ with gr.Row():
321
+ seed_param = gr.Number(
322
+ label="Inference Seed (Enter a positive number, -1 for random)", value=-1
323
+ )
324
+ with gr.Row():
325
+ enable_scale = gr.Checkbox(label="Super-Resolution (720 × 480 -> 2880 × 1920)", value=False)
326
+ enable_rife = gr.Checkbox(label="Frame Interpolation (8fps -> 16fps)", value=False)
327
+ gr.Markdown(
328
+ "✨In this demo, we use [RIFE](https://github.com/hzwer/ECCV2022-RIFE) for frame interpolation and [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) for upscaling(Super-Resolution).<br>&nbsp;&nbsp;&nbsp;&nbsp;The entire process is based on open-source solutions."
329
+ )
330
+
331
+ generate_button = gr.Button("🎬 Generate Video")
332
+
333
+ with gr.Column():
334
+ video_output = gr.Video(label="CogVideoX Generate Video", width=720, height=480)
335
+ with gr.Row():
336
+ download_video_button = gr.File(label="📥 Download Video", visible=False)
337
+ download_gif_button = gr.File(label="📥 Download GIF", visible=False)
338
+ seed_text = gr.Number(label="Seed Used for Video Generation", visible=False)
339
+
340
+ def generate(
341
+ prompt,
342
+ image_input,
343
+ # video_input,
344
+ # video_strength,
345
+ seed_value,
346
+ scale_status,
347
+ rife_status,
348
+ progress=gr.Progress(track_tqdm=True)
349
+ ):
350
+ latents, seed = infer(
351
+ prompt,
352
+ image_input,
353
+ # video_input,
354
+ # video_strength,
355
+ num_inference_steps=50, # NOT Changed
356
+ guidance_scale=7.0, # NOT Changed
357
+ seed=seed_value,
358
+ progress=progress,
359
+ )
360
+ if scale_status:
361
+ latents = utils.upscale_batch_and_concatenate(upscale_model, latents, device)
362
+ if rife_status:
363
+ latents = rife_inference_with_latents(frame_interpolation_model, latents)
364
+
365
+ batch_size = latents.shape[0]
366
+ batch_video_frames = []
367
+ for batch_idx in range(batch_size):
368
+ pt_image = latents[batch_idx]
369
+ pt_image = torch.stack([pt_image[i] for i in range(pt_image.shape[0])])
370
+
371
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image)
372
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
373
+ batch_video_frames.append(image_pil)
374
+
375
+ video_path = utils.save_video(batch_video_frames[0], fps=math.ceil((len(batch_video_frames[0]) - 1) / 6))
376
+ video_update = gr.update(visible=True, value=video_path)
377
+ gif_path = convert_to_gif(video_path)
378
+ gif_update = gr.update(visible=True, value=gif_path)
379
+ seed_update = gr.update(visible=True, value=seed)
380
+
381
+ return video_path, video_update, gif_update, seed_update
382
+
383
+ def enhance_prompt_func(prompt):
384
+ return convert_prompt(prompt, retry_times=1)
385
+
386
+ generate_button.click(
387
+ generate,
388
+ inputs=[prompt, image_input, seed_param, enable_scale, enable_rife],
389
+ outputs=[video_output, download_video_button, download_gif_button, seed_text],
390
+ )
391
+
392
+ enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt])
393
+ # video_input.upload(resize_if_unfit, inputs=[video_input], outputs=[video_input])
394
+
395
+ if __name__ == "__main__":
396
+ demo.queue(max_size=15)
397
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spaces>=0.29.3
2
+ safetensors>=0.4.5
3
+ spandrel>=0.4.0
4
+ tqdm>=4.66.5
5
+ scikit-video>=1.1.11
6
+ diffusers
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.4.0
13
+ torchvision>=0.19.0
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
rife/IFNet.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
File without changes
rife/__pycache__/IFNet_HDv3.cpython-312.pyc ADDED
Binary file (7.18 kB). View file
 
rife/__pycache__/RIFE_HDv3.cpython-312.pyc ADDED
Binary file (5.48 kB). View file
 
rife/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (200 Bytes). View file
 
rife/__pycache__/loss.cpython-312.pyc ADDED
Binary file (10.3 kB). View file
 
rife/__pycache__/warplayer.cpython-312.pyc ADDED
Binary file (2.3 kB). View file
 
rife/laplacian.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/pytorch_msssim/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (10.4 kB). View file
 
rife/refine.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from huggingface_hub import hf_hub_download, snapshot_download
12
+ logger = logging.getLogger(__name__)
13
+
14
+ device = "cuda" if torch.cuda.is_available() else "cpu"
15
+
16
+
17
+ def pad_image(img, scale):
18
+ _, _, h, w = img.shape
19
+ tmp = max(32, int(32 / scale))
20
+ ph = ((h - 1) // tmp + 1) * tmp
21
+ pw = ((w - 1) // tmp + 1) * tmp
22
+ padding = (0, pw - w, 0, ph - h)
23
+ return F.pad(img, padding), padding
24
+
25
+
26
+ def make_inference(model, I0, I1, upscale_amount, n):
27
+ middle = model.inference(I0, I1, upscale_amount)
28
+ if n == 1:
29
+ return [middle]
30
+ first_half = make_inference(model, I0, middle, upscale_amount, n=n // 2)
31
+ second_half = make_inference(model, middle, I1, upscale_amount, n=n // 2)
32
+ if n % 2:
33
+ return [*first_half, middle, *second_half]
34
+ else:
35
+ return [*first_half, *second_half]
36
+
37
+
38
+ @torch.inference_mode()
39
+ def ssim_interpolation_rife(model, samples, exp=1, upscale_amount=1, output_device="cpu"):
40
+ print(f"samples dtype:{samples.dtype}")
41
+ print(f"samples shape:{samples.shape}")
42
+ output = []
43
+ pbar = utils.ProgressBar(samples.shape[0], desc="RIFE inference")
44
+ # [f, c, h, w]
45
+ for b in range(samples.shape[0]):
46
+ frame = samples[b : b + 1]
47
+ _, _, h, w = frame.shape
48
+
49
+ I0 = samples[b : b + 1]
50
+ I1 = samples[b + 1 : b + 2] if b + 2 < samples.shape[0] else samples[-1:]
51
+
52
+ I0, padding = pad_image(I0, upscale_amount)
53
+ I0 = I0.to(torch.float)
54
+ I1, _ = pad_image(I1, upscale_amount)
55
+ I1 = I1.to(torch.float)
56
+
57
+ # [c, h, w]
58
+ I0_small = F.interpolate(I0, (32, 32), mode="bilinear", align_corners=False)
59
+ I1_small = F.interpolate(I1, (32, 32), mode="bilinear", align_corners=False)
60
+
61
+ ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3])
62
+
63
+ if ssim > 0.996:
64
+ I1 = samples[b : b + 1]
65
+ # print(f'upscale_amount:{upscale_amount}')
66
+ # print(f'ssim:{upscale_amount}')
67
+ # print(f'I0 shape:{I0.shape}')
68
+ # print(f'I1 shape:{I1.shape}')
69
+ I1, padding = pad_image(I1, upscale_amount)
70
+ # print(f'I0 shape:{I0.shape}')
71
+ # print(f'I1 shape:{I1.shape}')
72
+ I1 = make_inference(model, I0, I1, upscale_amount, 1)
73
+
74
+ # print(f'I0 shape:{I0.shape}')
75
+ # print(f'I1[0] shape:{I1[0].shape}')
76
+ I1 = I1[0]
77
+
78
+ # print(f'I1[0] unpadded shape:{I1.shape}')
79
+ I1_small = F.interpolate(I1, (32, 32), mode="bilinear", align_corners=False)
80
+ ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3])
81
+ if padding[3] > 0 and padding[1] >0 :
82
+
83
+ frame = I1[:, :, : -padding[3],:-padding[1]]
84
+ elif padding[3] > 0:
85
+ frame = I1[:, :, : -padding[3],:]
86
+ elif padding[1] >0:
87
+ frame = I1[:, :, :,:-padding[1]]
88
+ else:
89
+ frame = I1
90
+
91
+ tmp_output = []
92
+ if ssim < 0.2:
93
+ for i in range((2**exp) - 1):
94
+ tmp_output.append(I0)
95
+
96
+ else:
97
+ tmp_output = make_inference(model, I0, I1, upscale_amount, 2**exp - 1) if exp else []
98
+
99
+ frame, _ = pad_image(frame, upscale_amount)
100
+ # print(f'frame shape:{frame.shape}')
101
+
102
+ frame = F.interpolate(frame, size=(h, w))
103
+ output.append(frame.to(output_device))
104
+ for i, tmp_frame in enumerate(tmp_output):
105
+
106
+ # tmp_frame, _ = pad_image(tmp_frame, upscale_amount)
107
+ tmp_frame = F.interpolate(tmp_frame, size=(h, w))
108
+ output.append(tmp_frame.to(output_device))
109
+ pbar.update(1)
110
+ return output
111
+
112
+
113
+ def load_rife_model(model_path):
114
+ model = Model()
115
+ model.load_model(model_path, -1)
116
+ model.eval()
117
+ return model
118
+
119
+
120
+ # Create a generator that yields each frame, similar to cv2.VideoCapture
121
+ def frame_generator(video_capture):
122
+ while True:
123
+ ret, frame = video_capture.read()
124
+ if not ret:
125
+ break
126
+ yield frame
127
+ video_capture.release()
128
+
129
+
130
+ def rife_inference_with_path(model, video_path):
131
+ # Open the video file
132
+ video_capture = cv2.VideoCapture(video_path)
133
+ fps = video_capture.get(cv2.CAP_PROP_FPS) # Get the frames per second
134
+ tot_frame = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) # Total frames in the video
135
+ pt_frame_data = []
136
+ pt_frame = skvideo.io.vreader(video_path)
137
+ # Cyclic reading of the video frames
138
+ while video_capture.isOpened():
139
+ ret, frame = video_capture.read()
140
+
141
+ if not ret:
142
+ break
143
+
144
+ # BGR to RGB
145
+ frame_rgb = frame[..., ::-1]
146
+ frame_rgb = frame_rgb.copy()
147
+ tensor = torch.from_numpy(frame_rgb).float().to("cpu", non_blocking=True).float() / 255.0
148
+ pt_frame_data.append(
149
+ tensor.permute(2, 0, 1)
150
+ ) # to [c, h, w,]
151
+
152
+ pt_frame = torch.from_numpy(np.stack(pt_frame_data))
153
+ pt_frame = pt_frame.to(device)
154
+ pbar = utils.ProgressBar(tot_frame, desc="RIFE inference")
155
+ frames = ssim_interpolation_rife(model, pt_frame)
156
+ pt_image = torch.stack([frames[i].squeeze(0) for i in range(len(frames))])
157
+ image_np = VaeImageProcessor.pt_to_numpy(pt_image) # (to [49, 512, 480, 3])
158
+ image_pil = VaeImageProcessor.numpy_to_pil(image_np)
159
+ video_path = utils.save_video(image_pil, fps=16)
160
+ if pbar:
161
+ pbar.update(1)
162
+ return video_path
163
+
164
+
165
+ def rife_inference_with_latents(model, latents):
166
+ rife_results = []
167
+ latents = latents.to(device)
168
+ for i in range(latents.size(0)):
169
+ # [f, c, w, h]
170
+ latent = latents[i]
171
+
172
+ frames = ssim_interpolation_rife(model, latent)
173
+ pt_image = torch.stack([frames[i].squeeze(0) for i in range(len(frames))]) # (to [f, c, w, h])
174
+ rife_results.append(pt_image)
175
+
176
+ return torch.stack(rife_results)
177
+
178
+
179
+ # if __name__ == "__main__":
180
+ # snapshot_download(repo_id="AlexWortega/RIFE", local_dir="model_rife")
181
+ # model = load_rife_model("model_rife")
182
+
183
+ # video_path = rife_inference_with_path(model, "/mnt/ceph/develop/jiawei/CogVideo/output/20241003_130720.mp4")
184
+ # print(video_path)
utils.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)