Skip to content

Open-Sora: Democratizing Efficient Video Production for All

Python

fix flolpips

Shen-Chenhuia2ef63922fe5
diff --git a/eval/vae/cal_flolpips.py b/eval/vae/cal_flolpips.py
index ebca822..7d8f08c 100644
--- a/eval/vae/cal_flolpips.py
+++ b/eval/vae/cal_flolpips.py
@@ -7,8 +7,10 @@ from tqdm import tqdm
sys.path.append(".")
# ERROR: cannot locate the model file
-# loss_fn = FloLPIPS(net='alex', version='0.1').eval().requires_grad_(False)
-# flownet = PWCNet().eval().requires_grad_(False)
+from flolpips.pwcnet import Network as PWCNet
+from flolpips.flolpips import FloLPIPS
+loss_fn = FloLPIPS(net='alex', version='0.1').eval().requires_grad_(False)
+flownet = PWCNet().eval().requires_grad_(False)
def trans(x):
diff --git a/eval/vae/eval_common_metric.py b/eval/vae/eval_common_metric.py
index 5ca4b80..4570738 100644
--- a/eval/vae/eval_common_metric.py
+++ b/eval/vae/eval_common_metric.py
@@ -138,22 +138,32 @@ def _preprocess(video_data, short_size=128, crop_size=None):
def calculate_common_metric(args, dataloader, device):
- score_list = []
- for batch_data in tqdm(dataloader): # {'real': real_video_tensor, 'generated':generated_video_tensor }
- real_videos = batch_data['real']
- generated_videos = batch_data['generated']
- assert real_videos.shape[2] == generated_videos.shape[2]
- if args.metric == 'ssim':
- tmp_list = list(calculate_ssim(real_videos, generated_videos)['value'].values())
- elif args.metric == 'psnr':
- tmp_list = list(calculate_psnr(real_videos, generated_videos)['value'].values())
- elif args.metric == 'flolpips':
- result = calculate_flolpips(real_videos, generated_videos, args.device)
- tmp_list = list(result['value'].values())
- else:
- tmp_list = list(calculate_lpips(real_videos, generated_videos, args.device)['value'].values())
- score_list += tmp_list
- return np.mean(score_list)
+ metric_dict = {}
+ if type(args.metric) is str:
+ args.metric = [m.strip() for m in args.metric.split(",")]
+ print(args.metric)
+ for metric in args.metric:
+ score_list = []
+ for batch_data in tqdm(dataloader): # {'real': real_video_tensor, 'generated':generated_video_tensor }
+ real_videos = batch_data['real']
+ generated_videos = batch_data['generated']
+ assert real_videos.shape[2] == generated_videos.shape[2]
+ if metric == 'ssim':
+ tmp_list = list(calculate_ssim(real_videos, generated_videos)['value'].values())
+ elif metric == 'psnr':
+ tmp_list = list(calculate_psnr(real_videos, generated_videos)['value'].values())
+ elif metric == 'flolpips':
+ result = calculate_flolpips(real_videos, generated_videos, args.device)
+ tmp_list = list(result['value'].values())
+ elif metric == "lpips":
+ tmp_list = list(calculate_lpips(real_videos, generated_videos, args.device)['value'].values())
+ else:
+ print(f"metric {metric} is not in acceped list, not calculated")
+ continue
+ score_list += tmp_list
+ metric_dict[metric] = np.mean(score_list)
+
+ return metric_dict
def main():
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
@@ -174,7 +184,8 @@ def main():
parser.add_argument('--num_frames', type=int, default=100)
parser.add_argument('--sample_rate', type=int, default=1)
parser.add_argument('--subset_size', type=int, default=None)
- parser.add_argument("--metric", type=str, default="fvd",choices=['fvd','psnr','ssim','lpips', 'flolpips'])
+ # parser.add_argument("--metric", type=str, default="fvd",choices=['fvd','psnr','ssim','lpips', 'flolpips'])
+ parser.add_argument("--metric", nargs='+', default=[])
parser.add_argument("--fvd_method", type=str, default='styleganv',choices=['styleganv','videogpt'])
diff --git a/eval/vae/flolpips/flolpips.py b/eval/vae/flolpips/flolpips.py
index 66f4731..6bd2bac 100644
--- a/eval/vae/flolpips/flolpips.py
+++ b/eval/vae/flolpips/flolpips.py
@@ -11,9 +11,21 @@ import torch.nn.functional as F
import torchvision.transforms.functional as TF
import cv2
+import hashlib
+import requests
+from tqdm import tqdm
+
from .pwcnet import Network as PWCNet
from .utils import *
+URL_MAP = {"alex": "https://raw.githubusercontent.com/danier97/flolpips/main/weights/v0.1/alex.pth"}
+
+CKPT_MAP = {"alex": "alex.pth"}
+
+MD5_MAP = {"alex": "9642209e2b57a85d20f86d812320f9e6"}
+
+
+
def spatial_average(in_tens, keepdim=True):
return in_tens.mean([2,3],keepdim=keepdim)
@@ -49,6 +61,33 @@ def upsample(in_tens, out_HW=(64,64)): # assumes scale factor is same for H and
in_H, in_W = in_tens.shape[2], in_tens.shape[3]
return nn.Upsample(size=out_HW, mode='bilinear', align_corners=False)(in_tens)
+
+def md5_hash(path):
+ with open(path, "rb") as f:
+ content = f.read()
+ return hashlib.md5(content).hexdigest()
+
+def download(url, local_path, chunk_size=1024):
+ os.makedirs(os.path.split(local_path)[0], exist_ok=True)
+ with requests.get(url, stream=True) as r:
+ total_size = int(r.headers.get("content-length", 0))
+ with tqdm(total=total_size, unit="B", unit_scale=True) as pbar:
+ with open(local_path, "wb") as f:
+ for data in r.iter_content(chunk_size=chunk_size):
+ if data:
+ f.write(data)
+ pbar.update(chunk_size)
+
+def get_ckpt_path(name, root, check=False):
+ assert name in URL_MAP
+ path = os.path.join(root, CKPT_MAP[name])
+ if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]):
+ print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path))
+ download(URL_MAP[name], path)
+ md5 = md5_hash(path)
+ assert md5 == MD5_MAP[name], md5
+ return path
+
# Learned perceptual metric
class LPIPS(nn.Module):
def __init__(self, pretrained=True, net='alex', version='0.1', lpips=True, spatial=False,
@@ -96,18 +135,17 @@ class LPIPS(nn.Module):
self.lins = nn.ModuleList(self.lins)
if(pretrained):
- if(model_path is None):
- import inspect
- import os
- model_path = os.path.abspath(os.path.join(inspect.getfile(self.__init__), '..', 'weights/v%s/%s.pth'%(version,net)))
-
+ self.load_from_pretrained(version, net)
if(verbose):
- print('Loading model from: %s'%model_path)
- self.load_state_dict(torch.load(model_path, map_location='cpu'), strict=False)
+ print('Loaded model from: %s'%model_path)
if(eval_mode):
self.eval()
+ def load_from_pretrained(self, version, net):
+ ckpt = get_ckpt_path(net, "pretrained_models/flolpips/weights/v%s"%(version))
+ self.load_state_dict(torch.load(ckpt, map_location='cpu'), strict=False)
+
def forward(self, in0, in1, retPerLayer=False, normalize=False):
if normalize: # turn on this flag if input is [0,1] so it can be adjusted to [-1, +1]
in0 = 2 * in0 - 1
diff --git a/eval/vae/script/cal_lpips.sh b/eval/vae/script/cal_lpips.sh
deleted file mode 100644
index 9ebaf26..0000000
--- a/eval/vae/script/cal_lpips.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-python eval_common_metric.py \
- --real_video_dir path/to/imageA\
- --generated_video_dir path/to/imageB \
- --batch_size 10 \
- --num_frames 20 \
- --crop_size 64 \
- --device 'cuda' \
- --metric 'lpips'
\ No newline at end of file
diff --git a/eval/vae/script/cal_psnr.sh b/eval/vae/script/cal_psnr.sh
deleted file mode 100644
index a60a5d1..0000000
--- a/eval/vae/script/cal_psnr.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-
-python eval_common_metric.py \
- --real_video_dir /data/xiaogeng_liu/data/video1 \
- --generated_video_dir /data/xiaogeng_liu/data/video2 \
- --batch_size 10 \
- --num_frames 20 \
- --crop_size 64 \
- --device 'cuda' \
- --metric 'psnr'
\ No newline at end of file
diff --git a/eval/vae/script/cal_ssim.sh b/eval/vae/script/cal_ssim.sh
deleted file mode 100644
index 404d8da..0000000
--- a/eval/vae/script/cal_ssim.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-python eval_common_metric.py \
- --real_video_dir /data/xiaogeng_liu/data/video1 \
- --generated_video_dir /data/xiaogeng_liu/data/video2 \
- --batch_size 10 \
- --num_frames 20 \
- --crop_size 64 \
- --device 'cuda' \
- --metric 'ssim'
\ No newline at end of file
diff --git a/eval/vae/script/eval.sh b/eval/vae/script/eval.sh
index c1d1dbc..897166e 100644
--- a/eval/vae/script/eval.sh
+++ b/eval/vae/script/eval.sh
@@ -9,4 +9,4 @@ python eval/eval_common_metric.py \
--num_frames 17 \
--sample_rate 1 \
--subset_size 100 \
- --metric ssim
\ No newline at end of file
+ --metric ssim psnr lpips flolpips
\ No newline at end of file