Ouzhang commited on
Commit
df8034f
·
verified ·
1 Parent(s): 7a4fcad

Support source maps for renamed source videos

Browse files
benchmarks/edit/__pycache__/build_six_method_manifest.cpython-313.pyc CHANGED
Binary files a/benchmarks/edit/__pycache__/build_six_method_manifest.cpython-313.pyc and b/benchmarks/edit/__pycache__/build_six_method_manifest.cpython-313.pyc differ
 
benchmarks/edit/__pycache__/run_traditional_metrics.cpython-313.pyc CHANGED
Binary files a/benchmarks/edit/__pycache__/run_traditional_metrics.cpython-313.pyc and b/benchmarks/edit/__pycache__/run_traditional_metrics.cpython-313.pyc differ
 
benchmarks/edit/build_six_method_manifest.py CHANGED
@@ -21,7 +21,54 @@ def read_jsonl(path: Path) -> list[dict]:
21
  return rows
22
 
23
 
24
- def resolve_source_video(repo_root: Path, raw_path: str, source_roots: list[Path]) -> Path:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  source_video = Path(raw_path)
26
  if not source_video.is_absolute():
27
  source_video = repo_root / source_video
@@ -52,6 +99,8 @@ def build_split(
52
  outputs_root: Path,
53
  output_path: Path,
54
  source_roots: list[Path],
 
 
55
  ) -> None:
56
  samples = read_jsonl(samples_path)
57
  output_path.parent.mkdir(parents=True, exist_ok=True)
@@ -61,7 +110,14 @@ def build_split(
61
  with output_path.open("w", encoding="utf-8") as handle:
62
  for sample in samples:
63
  sample_id = str(sample["id"])
64
- source_video = resolve_source_video(repo_root, str(sample["control_video"]), source_roots)
 
 
 
 
 
 
 
65
  if not source_video.exists():
66
  missing_sources.add(str(source_video))
67
  for method in METHODS:
@@ -102,11 +158,22 @@ def main() -> None:
102
  default=[],
103
  help="Optional directory to search for original source mp4s by basename when eval_samples control_video is missing.",
104
  )
 
 
 
 
 
 
 
 
 
 
105
  args = parser.parse_args()
106
 
107
  repo_root = args.repo_root.resolve()
108
  base = repo_root / "out/edit_model_face_stage1"
109
  output_dir = args.output_dir if args.output_dir.is_absolute() else repo_root / args.output_dir
 
110
 
111
  jobs = [
112
  (
@@ -125,7 +192,16 @@ def main() -> None:
125
  for split, samples_path, outputs_root, output_path in jobs:
126
  if not samples_path.exists():
127
  raise FileNotFoundError(samples_path)
128
- build_split(repo_root, split, samples_path, outputs_root, output_path, args.source_root)
 
 
 
 
 
 
 
 
 
129
 
130
 
131
  if __name__ == "__main__":
 
21
  return rows
22
 
23
 
24
+ def load_source_maps(paths: list[Path], repo_root: Path) -> tuple[dict[str, Path], dict[str, Path]]:
25
+ """Load optional source maps keyed by sample_id and by original path/basename."""
26
+ by_id: dict[str, Path] = {}
27
+ by_key: dict[str, Path] = {}
28
+ for path in paths:
29
+ path = path if path.is_absolute() else repo_root / path
30
+ rows = read_jsonl(path)
31
+ for row in rows:
32
+ video = (
33
+ row.get("path")
34
+ or row.get("video")
35
+ or row.get("source_video")
36
+ or row.get("source_path")
37
+ or row.get("control_video")
38
+ )
39
+ if not video:
40
+ continue
41
+ video_path = Path(str(video))
42
+ if not video_path.is_absolute():
43
+ video_path = repo_root / video_path
44
+ for key_name in ("sample_id", "id"):
45
+ if row.get(key_name) is not None:
46
+ by_id[str(row[key_name])] = video_path
47
+ for key_name in ("old_path", "old_video", "control_video", "source_video"):
48
+ if row.get(key_name) is not None:
49
+ key = str(row[key_name])
50
+ by_key[key] = video_path
51
+ by_key[Path(key).name] = video_path
52
+ by_key[video_path.name] = video_path
53
+ return by_id, by_key
54
+
55
+
56
+ def resolve_source_video(
57
+ repo_root: Path,
58
+ sample_id: str,
59
+ raw_path: str,
60
+ source_roots: list[Path],
61
+ source_by_id: dict[str, Path],
62
+ source_by_key: dict[str, Path],
63
+ ) -> Path:
64
+ if sample_id in source_by_id:
65
+ return source_by_id[sample_id]
66
+ if raw_path in source_by_key:
67
+ return source_by_key[raw_path]
68
+ raw_name = Path(raw_path).name
69
+ if raw_name in source_by_key:
70
+ return source_by_key[raw_name]
71
+
72
  source_video = Path(raw_path)
73
  if not source_video.is_absolute():
74
  source_video = repo_root / source_video
 
99
  outputs_root: Path,
100
  output_path: Path,
101
  source_roots: list[Path],
102
+ source_by_id: dict[str, Path],
103
+ source_by_key: dict[str, Path],
104
  ) -> None:
105
  samples = read_jsonl(samples_path)
106
  output_path.parent.mkdir(parents=True, exist_ok=True)
 
110
  with output_path.open("w", encoding="utf-8") as handle:
111
  for sample in samples:
112
  sample_id = str(sample["id"])
113
+ source_video = resolve_source_video(
114
+ repo_root,
115
+ sample_id,
116
+ str(sample["control_video"]),
117
+ source_roots,
118
+ source_by_id,
119
+ source_by_key,
120
+ )
121
  if not source_video.exists():
122
  missing_sources.add(str(source_video))
123
  for method in METHODS:
 
158
  default=[],
159
  help="Optional directory to search for original source mp4s by basename when eval_samples control_video is missing.",
160
  )
161
+ parser.add_argument(
162
+ "--source-map",
163
+ type=Path,
164
+ action="append",
165
+ default=[],
166
+ help=(
167
+ "Optional JSONL map. Each row may contain sample_id/id and path/video/source_video/source_path. "
168
+ "It can also contain old_path/old_video/control_video to map old names to current hashed paths."
169
+ ),
170
+ )
171
  args = parser.parse_args()
172
 
173
  repo_root = args.repo_root.resolve()
174
  base = repo_root / "out/edit_model_face_stage1"
175
  output_dir = args.output_dir if args.output_dir.is_absolute() else repo_root / args.output_dir
176
+ source_by_id, source_by_key = load_source_maps(args.source_map, repo_root)
177
 
178
  jobs = [
179
  (
 
192
  for split, samples_path, outputs_root, output_path in jobs:
193
  if not samples_path.exists():
194
  raise FileNotFoundError(samples_path)
195
+ build_split(
196
+ repo_root,
197
+ split,
198
+ samples_path,
199
+ outputs_root,
200
+ output_path,
201
+ args.source_root,
202
+ source_by_id,
203
+ source_by_key,
204
+ )
205
 
206
 
207
  if __name__ == "__main__":
benchmarks/edit/run_traditional_metrics.py CHANGED
@@ -101,6 +101,25 @@ def align_frame_arrays(source: np.ndarray, edited: np.ndarray) -> tuple[np.ndarr
101
  return source[:n], edited[:n]
102
 
103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  def global_ssim_gray(a: np.ndarray, b: np.ndarray) -> float:
105
  """Simple global SSIM over all sampled grayscale pixels, no skimage dependency."""
106
  a_gray = 0.299 * a[..., 0] + 0.587 * a[..., 1] + 0.114 * a[..., 2]
@@ -172,7 +191,7 @@ class ClipMetrics:
172
  for start in range(0, len(frames), self.batch_size):
173
  batch = frames[start : start + self.batch_size]
174
  inputs = self.processor(images=batch, return_tensors="pt").to(self.device)
175
- feats = self.model.get_image_features(**inputs)
176
  feats = feats / feats.norm(dim=-1, keepdim=True).clamp_min(1e-12)
177
  chunks.append(feats)
178
  return self.torch.cat(chunks, dim=0)
@@ -180,7 +199,7 @@ class ClipMetrics:
180
  def text_feature(self, text: str):
181
  with self.torch.inference_mode():
182
  inputs = self.processor(text=[text], return_tensors="pt", padding=True, truncation=True).to(self.device)
183
- feat = self.model.get_text_features(**inputs)
184
  feat = feat / feat.norm(dim=-1, keepdim=True).clamp_min(1e-12)
185
  return feat[0]
186
 
@@ -288,7 +307,7 @@ class LaionAestheticMetrics:
288
  for start in range(0, len(edited_frames), self.batch_size):
289
  batch = edited_frames[start : start + self.batch_size]
290
  inputs = self.processor(images=batch, return_tensors="pt").to(self.device)
291
- feats = self.clip.get_image_features(**inputs)
292
  feats = feats / feats.norm(dim=-1, keepdim=True).clamp_min(1e-12)
293
  if feats.shape[-1] != self.linear.in_features:
294
  raise RuntimeError(
@@ -378,9 +397,11 @@ def init_optional_scorer(name: str, factory):
378
  return scorer, ""
379
 
380
 
381
- def append_error(existing: Any, message: str) -> str:
382
- existing_text = str(existing) if existing else ""
383
- return f"{existing_text} | {message}" if existing_text else message
 
 
384
 
385
 
386
  def configure_cache_dirs(torch_home: Path | None, hf_home: Path | None, xdg_cache_home: Path | None) -> None:
@@ -518,15 +539,19 @@ def main() -> None:
518
  )
519
 
520
  if clip is not None:
521
- result.update(clip.compute(source_frames, edited_frames, str(row["instruction"])))
 
 
 
 
522
  if dino is not None:
523
- result.update(dino.compute(edited_frames))
524
  if aesthetic is not None:
525
- result.update(aesthetic.compute(edited_frames))
526
  if pyiqa_metrics is not None:
527
- result.update(pyiqa_metrics.compute(edited_frames))
528
  if lpips_metric is not None and source_frames is not None:
529
- result.update(lpips_metric.compute(source_frames, edited_frames))
530
  except Exception as exc:
531
  row_error = repr(exc)
532
  result["error"] = append_error(result.get("error"), row_error)
 
101
  return source[:n], edited[:n]
102
 
103
 
104
+ def append_error(existing: Any, message: str) -> str:
105
+ existing_text = str(existing) if existing else ""
106
+ return f"{existing_text} | {message}" if existing_text else message
107
+
108
+
109
+ def tensor_from_model_output(output: Any) -> Any:
110
+ """Handle transformers versions that return model outputs instead of tensors."""
111
+ if hasattr(output, "norm"):
112
+ return output
113
+ for attr in ("image_embeds", "text_embeds", "pooler_output"):
114
+ value = getattr(output, attr, None)
115
+ if value is not None:
116
+ return value
117
+ hidden = getattr(output, "last_hidden_state", None)
118
+ if hidden is not None:
119
+ return hidden[:, 0]
120
+ raise TypeError(f"cannot extract tensor from model output {type(output).__name__}")
121
+
122
+
123
  def global_ssim_gray(a: np.ndarray, b: np.ndarray) -> float:
124
  """Simple global SSIM over all sampled grayscale pixels, no skimage dependency."""
125
  a_gray = 0.299 * a[..., 0] + 0.587 * a[..., 1] + 0.114 * a[..., 2]
 
191
  for start in range(0, len(frames), self.batch_size):
192
  batch = frames[start : start + self.batch_size]
193
  inputs = self.processor(images=batch, return_tensors="pt").to(self.device)
194
+ feats = tensor_from_model_output(self.model.get_image_features(**inputs))
195
  feats = feats / feats.norm(dim=-1, keepdim=True).clamp_min(1e-12)
196
  chunks.append(feats)
197
  return self.torch.cat(chunks, dim=0)
 
199
  def text_feature(self, text: str):
200
  with self.torch.inference_mode():
201
  inputs = self.processor(text=[text], return_tensors="pt", padding=True, truncation=True).to(self.device)
202
+ feat = tensor_from_model_output(self.model.get_text_features(**inputs))
203
  feat = feat / feat.norm(dim=-1, keepdim=True).clamp_min(1e-12)
204
  return feat[0]
205
 
 
307
  for start in range(0, len(edited_frames), self.batch_size):
308
  batch = edited_frames[start : start + self.batch_size]
309
  inputs = self.processor(images=batch, return_tensors="pt").to(self.device)
310
+ feats = tensor_from_model_output(self.clip.get_image_features(**inputs))
311
  feats = feats / feats.norm(dim=-1, keepdim=True).clamp_min(1e-12)
312
  if feats.shape[-1] != self.linear.in_features:
313
  raise RuntimeError(
 
397
  return scorer, ""
398
 
399
 
400
+ def compute_optional(result: dict[str, Any], name: str, callback) -> None:
401
+ try:
402
+ result.update(callback())
403
+ except Exception as exc:
404
+ result["error"] = append_error(result.get("error"), f"{name}_failed={type(exc).__name__}: {exc}")
405
 
406
 
407
  def configure_cache_dirs(torch_home: Path | None, hf_home: Path | None, xdg_cache_home: Path | None) -> None:
 
539
  )
540
 
541
  if clip is not None:
542
+ compute_optional(
543
+ result,
544
+ "clip",
545
+ lambda: clip.compute(source_frames, edited_frames, str(row["instruction"])),
546
+ )
547
  if dino is not None:
548
+ compute_optional(result, "dino", lambda: dino.compute(edited_frames))
549
  if aesthetic is not None:
550
+ compute_optional(result, "laion_aesthetic", lambda: aesthetic.compute(edited_frames))
551
  if pyiqa_metrics is not None:
552
+ compute_optional(result, "pyiqa", lambda: pyiqa_metrics.compute(edited_frames))
553
  if lpips_metric is not None and source_frames is not None:
554
+ compute_optional(result, "lpips", lambda: lpips_metric.compute(source_frames, edited_frames))
555
  except Exception as exc:
556
  row_error = repr(exc)
557
  result["error"] = append_error(result.get("error"), row_error)
benchmarks/edit/traditional_eval_notes.md CHANGED
@@ -519,6 +519,29 @@ python3 reference/benchmarks/edit/build_six_method_manifest.py \
519
  --source-root /path/to/source/videos
520
  ```
521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
  生成后快速检查路径:
523
 
524
  ```bash
 
519
  --source-root /path/to/source/videos
520
  ```
521
 
522
+ 如果当前机器上的源视频已经被重命名成 hash 文件名,需要提供一个 JSONL 映射文件,至少包含 `sample_id` 和当前视频路径:
523
+
524
+ ```jsonl
525
+ {"sample_id": "val_0000", "path": "/inspire/hdd/project/.../datas/ditto_face/low/0a1ec4e5fd6d9079ad1be0ea03cbcfed.mp4"}
526
+ ```
527
+
528
+ 然后生成 manifest:
529
+
530
+ ```bash
531
+ python3 reference/benchmarks/edit/build_six_method_manifest.py \
532
+ --repo-root . \
533
+ --output-dir out/edit_model_face_stage1/traditional_eval_manifests \
534
+ --source-map out/edit_model_face_stage1/source_video_map.jsonl
535
+ ```
536
+
537
+ `--source-map` 也支持这些字段名:
538
+
539
+ - 样本键:`sample_id` 或 `id`
540
+ - 当前视频路径:`path`、`video`、`source_video`、`source_path` 或 `control_video`
541
+ - 旧路径键:`old_path`、`old_video`、`control_video` 或 `source_video`
542
+
543
+ 注意:如果只有一个目录里一堆 hash mp4,但没有 `sample_id -> hash mp4` 或 `旧文件名 -> hash mp4` 映射,脚本不能安全自动匹配。此时要先从生成数据时的 records/metadata 找回映射。
544
+
545
  生成后快速检查路径:
546
 
547
  ```bash