Ouzhang commited on
Commit
4e26cf6
·
verified ·
1 Parent(s): c7577ad

Upload scripts/training/critic-agent/train.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/training/critic-agent/train.py +138 -60
scripts/training/critic-agent/train.py CHANGED
@@ -571,7 +571,7 @@ def _split_rows(rows: list[dict]) -> tuple[list[dict], list[dict]]:
571
 
572
  def _format_scores_text(scores: dict) -> str:
573
  if _is_aesthetic_score_schema(scores):
574
- return _format_aesthetic_scores_text(scores)
575
  return "\n".join(
576
  [
577
  f"PROMPT_ALIGNMENT: {float(scores.get('prompt_alignment', 0.0) or 0.0):.3f}",
@@ -601,70 +601,137 @@ def _is_aesthetic_score_schema(scores: dict) -> bool:
601
 
602
 
603
  def _format_aesthetic_scores_text(scores: dict) -> str:
604
- return "\n".join(
605
- [
606
- f"NARRATIVE_EMOTIONAL_FIT: {float(scores.get('narrative_emotional_fit', 0.0) or 0.0):.3f}",
607
- f"STYLE_WORLD_CONSISTENCY: {float(scores.get('style_world_consistency', 0.0) or 0.0):.3f}",
608
- f"COMPOSITION_LIGHTING_DESIGN: {float(scores.get('composition_lighting_design', 0.0) or 0.0):.3f}",
609
- f"COLOR_TEXTURE_REFINEMENT: {float(scores.get('color_texture_refinement', 0.0) or 0.0):.3f}",
610
- f"VISUAL_HIERARCHY_READABILITY: {float(scores.get('visual_hierarchy_readability', 0.0) or 0.0):.3f}",
611
- f"OVERALL_AESTHETIC_SCORE: {float(scores.get('overall_aesthetic_score', 0.0) or 0.0):.3f}",
612
- ]
613
- )
 
 
 
 
 
 
 
614
 
615
 
616
  def _build_aesthetic_evaluator_system_prompt() -> str:
617
- return (
618
- build_critic_identity_prefix()
619
- + "你负责低质量到高质量视频编辑结果的美学质量评估。\n"
620
- "你需要对比低质量视频帧和编辑后视频帧,判断编辑后结果是否形成高质量、连贯、有审美完成度的视觉效果。\n"
621
- "仅以纯文本形式回复,不要输出JSON,不要添加markdown代码块标记。\n"
622
- "分数使用1到5的整数或小数,1表示很差,5表示优秀。\n"
623
- "不要包含思维链、逐步推理、自我修正或重复分析。\n"
624
- "直接以NARRATIVE_EMOTIONAL_FIT:开头,不要在标题前添加任何前言。\n"
625
- "每个分数标题必须在同一行只包含一个数值。\n"
626
- "FAILURE_TAGS必须是单行的逗号分隔蛇形命名标签。\n"
627
- "REFLECTION_HINTS必须是单行,包含1-3个简短建议,用逗号分隔。\n"
628
- "NOTES必须是单行,最多3个简短事实观察,用逗号分隔。\n"
629
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630
 
631
 
632
  def _build_aesthetic_evaluator_user_prompt(row: dict) -> str:
633
- return (
634
- f"sample_id: {row.get('sample_id', '')}\n"
635
- f"target_edit_prompt: {row.get('prompt', '')}\n"
636
- "图像顺序:\n"
637
- "- 前半部分是 low/source video 抽帧。\n"
638
- "- 后半部分是 edited video 抽帧。\n"
639
- "请按照以下5个美学维度评估 edited video:\n"
640
- "- narrative_emotional_fit: 视觉结果是否服务于提示词的叙事、情绪和审美意图。\n"
641
- "- style_world_consistency: 风格、世界观、材质和场景设定是否统一可信。\n"
642
- "- composition_lighting_design: 构图、光照、景深、镜头观感是否有设计感。\n"
643
- "- color_texture_refinement: 色彩、纹理、细节、材质是否精致且不廉价。\n"
644
- "- visual_hierarchy_readability: 主体层次、可读性、视觉焦点是否清晰。\n"
645
- "overall_aesthetic_score 是综合美学评分。\n"
646
- "失败标签应使用简短蛇形命名标签,如: artifact_heavy, incoherent_style, weak_composition, poor_lighting, muddy_texture, unreadable_focus。\n"
647
- "格式规则:\n"
648
- "- 立即以NARRATIVE_EMOTIONAL_FIT:开头,不要引言、不要推理。\n"
649
- "- 每个标题后只放一个数字在同一行。\n"
650
- "- FAILURE_TAGS: 仅限逗号分隔蛇形命名标签。\n"
651
- "- REFLECTION_HINTS: 仅限1到3个简短改进建议。\n"
652
- "- NOTES: 最多3个简短事实观察。\n"
653
- "返回以下精确的标题:\n"
654
- "NARRATIVE_EMOTIONAL_FIT:\n"
655
- "STYLE_WORLD_CONSISTENCY:\n"
656
- "COMPOSITION_LIGHTING_DESIGN:\n"
657
- "COLOR_TEXTURE_REFINEMENT:\n"
658
- "VISUAL_HIERARCHY_READABILITY:\n"
659
- "OVERALL_AESTHETIC_SCORE:\n"
660
- "FAILURE_TAGS:\n"
661
- "REFLECTION_HINTS:\n"
662
- "NOTES:\n"
663
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664
 
665
 
666
  def _format_evaluator_target(row: dict) -> str:
667
  scores = row.get("teacher_scores", {}) or {}
 
 
668
  failure_tags = row.get("failure_tags", []) or []
669
  reflection_hints = row.get("reflection_hints", []) or []
670
  notes = row.get("teacher_replan_directives", []) or []
@@ -926,6 +993,13 @@ def _extract_training_frames(row: dict, frames_per_video: int, *, include_high:
926
  return image_paths
927
 
928
 
 
 
 
 
 
 
 
929
  def _extract_pairwise_frames(row: dict, frames_per_video: int) -> list[str]:
930
  image_paths: list[str] = []
931
  for key in ["low_video_path", "high_video_path", "candidate_a_video_path", "candidate_b_video_path"]:
@@ -1577,11 +1651,15 @@ def _run_real_sft(
1577
  )
1578
  loss = regression_criterion(preds, target)
1579
  else:
1580
- image_paths = _extract_training_frames(
1581
- row,
1582
- args.frames_per_video,
1583
- include_high=canonical_stage != "evaluator_sft",
1584
- )
 
 
 
 
1585
  messages, _ = _build_multimodal_messages(stage, row, image_paths)
1586
  prompt_messages = messages[:-1]
1587
  full_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
 
571
 
572
  def _format_scores_text(scores: dict) -> str:
573
  if _is_aesthetic_score_schema(scores):
574
+ return _format_aesthetic_evaluator_target({"teacher_scores": scores})
575
  return "\n".join(
576
  [
577
  f"PROMPT_ALIGNMENT: {float(scores.get('prompt_alignment', 0.0) or 0.0):.3f}",
 
601
 
602
 
603
  def _format_aesthetic_scores_text(scores: dict) -> str:
604
+ return _format_aesthetic_evaluator_target({"teacher_scores": scores})
605
+
606
+
607
+ def _clamp_aesthetic_dimension_score(value: object) -> int:
608
+ try:
609
+ score = int(round(float(value)))
610
+ except (TypeError, ValueError):
611
+ score = 1
612
+ return max(1, min(4, score))
613
+
614
+
615
+ def _clamp_aesthetic_overall_score(value: object) -> float:
616
+ try:
617
+ score = float(value)
618
+ except (TypeError, ValueError):
619
+ score = 1.0
620
+ return max(1.0, min(4.0, score))
621
 
622
 
623
  def _build_aesthetic_evaluator_system_prompt() -> str:
624
+ return """You are a strict cinematic/VFX aesthetic rater.
625
+ You are doing pointwise standalone aesthetic scoring: you see sampled frames
626
+ from the edited video, but you do not see the source video. Use the editing
627
+ instruction only as weak context for the intended visual direction. Do not judge
628
+ whether the edit accurately followed the instruction, because the source video is
629
+ not provided.
630
+
631
+ Scoring scale for every dimension:
632
+ 4 = excellent / strongly successful
633
+ 3 = good with minor issues
634
+ 2 = weak with clear issues
635
+ 1 = failed or harms the aesthetic goal
636
+
637
+ Rules:
638
+ - Score each dimension independently.
639
+ - There is no neutral middle score. Choose 2 or 3 when uncertain between weak and good.
640
+ - If a video matches multiple descriptions, assign the lowest applicable score.
641
+ - For object removal, cleanup, denoising, de-watermarking, or other utility edits,
642
+ a seamless and visually natural result can be aesthetically successful even if
643
+ it is not dramatic or cinematic.
644
+ - Do not penalize a candidate because the requested edit removes an interesting
645
+ object or makes the scene simpler.
646
+ - Do not give high artistic scores just because the image is sharp or expensive-looking.
647
+ - Do not give high color scores just because colors are saturated.
648
+ - Penalize visible inpainting seams, visual clutter, incoherent style mixing,
649
+ cheap texture/filter look, and unclear focal hierarchy when they are visible in
650
+ the edited frames.
651
+ - Return valid JSON only, with no markdown.
652
+ """
653
+
654
+
655
+ def _infer_aesthetic_task_type(instruction: str) -> str:
656
+ text = instruction.lower()
657
+ if any(word in text for word in ["remove", "erase", "delete", "hide", "clean up", "de-watermark", "watermark", "logo"]):
658
+ return "removal_or_cleanup"
659
+ if any(word in text for word in ["add", "insert", "place", "put ", "introduce", "include"]):
660
+ return "addition_or_insertion"
661
+ if any(word in text for word in ["replace", "swap", "change into", "turn into", "transform", "convert"]):
662
+ return "replacement_or_transformation"
663
+ if any(word in text for word in ["style", "aesthetic", "cinematic", "film", "color", "lighting", "tone", "grain", "texture"]):
664
+ return "style_or_look_change"
665
+ if any(word in text for word in ["enhance", "restore", "sharpen", "denoise", "improve", "refine"]):
666
+ return "quality_refinement"
667
+ return "general_edit"
668
 
669
 
670
  def _build_aesthetic_evaluator_user_prompt(row: dict) -> str:
671
+ instruction = str(row.get("prompt", "") or "")
672
+ task_type = _infer_aesthetic_task_type(instruction)
673
+ return f"""Editing instruction / intended effect:
674
+ {instruction}
675
+
676
+ Inferred task type:
677
+ {task_type}
678
+
679
+ Important: you do not see the source video. Do not evaluate whether the edit was
680
+ completed relative to the source. Evaluate the final edited video as a standalone
681
+ visual result. For removal or cleanup tasks, invisible/seamless blending is a
682
+ positive aesthetic outcome.
683
+
684
+ Evaluate the edited video frames on these five dimensions:
685
+ 1. narrative_emotional_fit: whether the final edited result naturally integrates with the scene mood, emotional tone, and visual context without artificial or distracting anomalies.
686
+ 2. style_world_consistency: whether the final visual style fits the world, era, genre, and style language such as classical, wuxia, sci-fi, realistic, fantasy, or cinematic.
687
+ 3. composition_lighting_design: composition, contrast, lighting hierarchy, lens/cinematic design, and shot-level visual arrangement.
688
+ 4. color_texture_refinement: color harmony, saturation control, material/texture/filter refinement, and whether it avoids cheap or generic looks.
689
+ 5. visual_hierarchy_readability: whether the main visual intent is clear, focal hierarchy is readable, and important content is not obscured.
690
+
691
+ "overall_aesthetic_score" should be a holistic assessment of final visual
692
+ quality from 1.0 to 4.0, not a simple mathematical average of the five
693
+ dimensions.
694
+
695
+ Return this exact JSON schema:
696
+ {{
697
+ "scores": {{
698
+ "narrative_emotional_fit": 1,
699
+ "style_world_consistency": 1,
700
+ "composition_lighting_design": 1,
701
+ "color_texture_refinement": 1,
702
+ "visual_hierarchy_readability": 1
703
+ }},
704
+ "overall_aesthetic_score": 1.0,
705
+ "uncertain": false,
706
+ "reason": "one concise sentence"
707
+ }}
708
+ """
709
+
710
+
711
+ def _format_aesthetic_evaluator_target(row: dict) -> str:
712
+ scores = row.get("teacher_scores", {}) or {}
713
+ raw_label = row.get("raw_label", {}) or {}
714
+ hints = row.get("reflection_hints", []) or []
715
+ reason = str(raw_label.get("reason", "") or (hints[0] if hints else "") or "")
716
+ payload = {
717
+ "scores": {
718
+ "narrative_emotional_fit": _clamp_aesthetic_dimension_score(scores.get("narrative_emotional_fit", 1)),
719
+ "style_world_consistency": _clamp_aesthetic_dimension_score(scores.get("style_world_consistency", 1)),
720
+ "composition_lighting_design": _clamp_aesthetic_dimension_score(scores.get("composition_lighting_design", 1)),
721
+ "color_texture_refinement": _clamp_aesthetic_dimension_score(scores.get("color_texture_refinement", 1)),
722
+ "visual_hierarchy_readability": _clamp_aesthetic_dimension_score(scores.get("visual_hierarchy_readability", 1)),
723
+ },
724
+ "overall_aesthetic_score": _clamp_aesthetic_overall_score(scores.get("overall_aesthetic_score", raw_label.get("overall_aesthetic_score", 1.0))),
725
+ "uncertain": bool(raw_label.get("uncertain", False)),
726
+ "reason": reason,
727
+ }
728
+ return json.dumps(payload, ensure_ascii=False, indent=2)
729
 
730
 
731
  def _format_evaluator_target(row: dict) -> str:
732
  scores = row.get("teacher_scores", {}) or {}
733
+ if _is_aesthetic_score_schema(scores):
734
+ return _format_aesthetic_evaluator_target(row)
735
  failure_tags = row.get("failure_tags", []) or []
736
  reflection_hints = row.get("reflection_hints", []) or []
737
  notes = row.get("teacher_replan_directives", []) or []
 
993
  return image_paths
994
 
995
 
996
+ def _extract_aesthetic_training_frames(row: dict, frames_per_video: int) -> list[str]:
997
+ value = str(row.get("edited_video_path", "") or "").strip()
998
+ if not value:
999
+ return []
1000
+ return [str(p) for p in extract_frames_jpg(value, frame_count=frames_per_video)]
1001
+
1002
+
1003
  def _extract_pairwise_frames(row: dict, frames_per_video: int) -> list[str]:
1004
  image_paths: list[str] = []
1005
  for key in ["low_video_path", "high_video_path", "candidate_a_video_path", "candidate_b_video_path"]:
 
1651
  )
1652
  loss = regression_criterion(preds, target)
1653
  else:
1654
+ scores = row.get("teacher_scores", {}) or {}
1655
+ if canonical_stage == "evaluator_sft" and _is_aesthetic_score_schema(scores):
1656
+ image_paths = _extract_aesthetic_training_frames(row, args.frames_per_video)
1657
+ else:
1658
+ image_paths = _extract_training_frames(
1659
+ row,
1660
+ args.frames_per_video,
1661
+ include_high=canonical_stage != "evaluator_sft",
1662
+ )
1663
  messages, _ = _build_multimodal_messages(stage, row, image_paths)
1664
  prompt_messages = messages[:-1]
1665
  full_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)