| from __future__ import annotations |
|
|
| import argparse |
| import hashlib |
| import json |
| import sys |
| import time |
| import warnings |
| from collections import defaultdict |
| from pathlib import Path |
|
|
| PROJECT_ROOT = Path(__file__).resolve().parents[3] |
| SRC_ROOT = PROJECT_ROOT / "src" |
| if str(SRC_ROOT) not in sys.path: |
| sys.path.insert(0, str(SRC_ROOT)) |
|
|
| import torch |
| from torch import nn |
| import torch.nn.functional as F |
| from torch.utils.data import DataLoader, TensorDataset |
| from transformers import AutoModelForImageTextToText, AutoProcessor |
|
|
| try: |
| from torch.utils.tensorboard import SummaryWriter |
| except Exception: |
| SummaryWriter = None |
|
|
| from peft import LoraConfig, PeftModel, get_peft_model |
|
|
| from qwen_vl_utils import process_vision_info |
|
|
| from critic.prompts import ( |
| build_critic_identity_prefix, |
| build_edit_evaluator_system_prompt, |
| build_edit_evaluator_user_prompt, |
| ) |
| from vlm.local_qwen import local_model_path |
| from vlm.openrouter import extract_frames as extract_frames_jpg |
|
|
| warnings.filterwarnings( |
| "ignore", |
| message=r"`torch\.cpu\.amp\.autocast\(args\.\.\.\)` is deprecated", |
| category=FutureWarning, |
| module=r"torch\.utils\.checkpoint", |
| ) |
|
|
| STAGE_ALIASES = { |
| "evaluator_implicit_sft": "evaluator_sft", |
| "reflector_implicit_sft": "reflection_sft", |
| "pairwise_implicit_rm": "pairwise_rm", |
| } |
|
|
| STAGE_CHOICES = [ |
| "evaluator_sft", |
| "evaluator_implicit_sft", |
| "evaluator_regression", |
| "pairwise_rm", |
| "pairwise_implicit_rm", |
| "reflection_sft", |
| "reflector_implicit_sft", |
| "replay_calibration", |
| ] |
|
|
| STAGE_DATASET_CANDIDATES = { |
| "evaluator_sft": ["evaluator_sft.jsonl", "evaluator_implicit_sft.jsonl", "memory_episodes.jsonl"], |
| "evaluator_implicit_sft": ["evaluator_implicit_sft.jsonl", "memory_episodes.jsonl", "evaluator_sft.jsonl"], |
| "evaluator_regression": ["evaluator_sft.jsonl", "evaluator_implicit_sft.jsonl", "memory_episodes.jsonl"], |
| "pairwise_rm": ["pairwise_rm.jsonl", "pairwise_implicit_rm.jsonl", "memory_episodes.jsonl"], |
| "pairwise_implicit_rm": ["pairwise_implicit_rm.jsonl", "memory_episodes.jsonl", "pairwise_rm.jsonl"], |
| "reflection_sft": ["reflection_sft.jsonl", "reflector_implicit_sft.jsonl", "memory_episodes.jsonl"], |
| "reflector_implicit_sft": ["reflector_implicit_sft.jsonl", "memory_episodes.jsonl", "reflection_sft.jsonl"], |
| "replay_calibration": ["replay_calibration.jsonl", "memory_episodes.jsonl", "evaluator_implicit_sft.jsonl", "evaluator_sft.jsonl"], |
| } |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser() |
| parser.add_argument( |
| "--dataset", |
| type=Path, |
| required=True, |
| help=( |
| "Training rows JSONL file, or a views directory from build_training_views.py " |
| "(auto-resolves stage-specific dataset file)." |
| ), |
| ) |
| parser.add_argument("--output-dir", type=Path, required=True) |
| parser.add_argument("--base-model", default="qwen-vl-local-critic") |
| parser.add_argument( |
| "--stage", |
| choices=STAGE_CHOICES, |
| default="evaluator_sft", |
| ) |
| parser.add_argument("--max-samples", type=int, default=0) |
| parser.add_argument("--run-smoke", action="store_true") |
| parser.add_argument("--run-real-sft", action="store_true") |
| parser.add_argument("--epochs", type=int, default=3) |
| parser.add_argument("--batch-size", type=int, default=4) |
| parser.add_argument("--lr", type=float, default=1e-3) |
| parser.add_argument("--frames-per-video", type=int, default=2) |
| parser.add_argument("--real-model-path", default="") |
| parser.add_argument("--lora-r", type=int, default=8) |
| parser.add_argument("--lora-alpha", type=int, default=16) |
| parser.add_argument("--lora-dropout", type=float, default=0.05) |
| parser.add_argument("--max-train-steps", type=int, default=0) |
| parser.add_argument( |
| "--resume-from", |
| default="", |
| help="Checkpoint directory to resume from, or 'latest' to use output-dir/real_sft_latest_checkpoint.txt.", |
| ) |
| parser.add_argument( |
| "--init-from-checkpoint", |
| default="", |
| help=( |
| "Initialize model weights from an earlier critic checkpoint without resuming optimizer/epoch state. " |
| "Intended for cross-stage handoff such as evaluator_sft -> pairwise_rm." |
| ), |
| ) |
| parser.add_argument( |
| "--save-every-steps", |
| type=int, |
| default=0, |
| help="Optionally save an intermediate checkpoint every N optimizer steps during run-real-sft.", |
| ) |
| parser.add_argument( |
| "--log-every-steps", |
| type=int, |
| default=10, |
| help="Print one training progress line every N optimizer steps during run-real-sft.", |
| ) |
| parser.add_argument( |
| "--tensorboard", |
| action="store_true", |
| help="Write TensorBoard event files under output-dir/tensorboard during run-real-sft.", |
| ) |
| parser.add_argument( |
| "--tensorboard-dir", |
| default="", |
| help="Optional TensorBoard log dir. Defaults to <output-dir>/tensorboard.", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def _canonical_stage(stage: str) -> str: |
| return STAGE_ALIASES.get(stage, stage) |
|
|
|
|
| def _is_implicit_stage(stage: str) -> bool: |
| return stage in STAGE_ALIASES |
|
|
|
|
| def _memory_required_labels() -> list[str]: |
| return [ |
| "history_window", |
| "teacher_explicit_memory", |
| "routing_target", |
| "local_positive_teacher", |
| "local_negative_teacher", |
| "global_positive_teacher", |
| "global_negative_teacher", |
| ] |
|
|
|
|
| def _stage_objective(stage: str) -> str: |
| canonical = _canonical_stage(stage) |
| if canonical == "evaluator_sft": |
| prefix = "train memory-aware structured multi-dimensional evaluation outputs from teacher labels" if _is_implicit_stage(stage) else "train structured multi-dimensional evaluation outputs from teacher labels" |
| return prefix |
| if canonical == "evaluator_regression": |
| return "train direct multi-score regression head for fast evaluator inference" |
| if canonical == "pairwise_rm": |
| return ( |
| "train memory-aware relative preference judgment between candidate edited videos" |
| if _is_implicit_stage(stage) |
| else "train relative preference judgment between candidate edited videos" |
| ) |
| if canonical == "reflection_sft": |
| return ( |
| "train memory-aware accept/local_refine/global_replan policy from structured diagnostics" |
| if _is_implicit_stage(stage) |
| else "train accept/local_refine/global_replan policy from structured diagnostics" |
| ) |
| return "adapt critic to online replay distribution without rebuilding the base objective" |
|
|
|
|
| def _stage_required_labels(stage: str) -> list[str]: |
| canonical = _canonical_stage(stage) |
| if canonical in {"evaluator_sft", "evaluator_regression"}: |
| required = ["teacher_scores", "failure_tags", "reflection_hints"] |
| return required + _memory_required_labels() if _is_implicit_stage(stage) else required |
| if canonical == "pairwise_rm": |
| required = ["candidate_a_video_path", "candidate_b_video_path", "winner", "preference_reason"] |
| return required + _memory_required_labels() if _is_implicit_stage(stage) else required |
| if canonical == "reflection_sft": |
| required = ["teacher_scores", "failure_tags", "reflection_hints", "teacher_reflection_action"] |
| return required + _memory_required_labels() if _is_implicit_stage(stage) else required |
| return ["online_evaluation_result", "online_reflection_result"] |
|
|
|
|
| def _stage_training_config(args: argparse.Namespace, sample_count: int) -> dict: |
| canonical = _canonical_stage(args.stage) |
| common = { |
| "base_model": args.base_model, |
| "dataset": str(args.dataset), |
| "sample_count": sample_count, |
| "max_samples": args.max_samples, |
| "vision_input": { |
| "low_frames": 3, |
| "edited_frames": 3, |
| "high_frames": 3, |
| "max_total_frames": 9, |
| }, |
| "required_labels": _stage_required_labels(args.stage), |
| } |
| if _is_implicit_stage(args.stage): |
| common["memory_context"] = { |
| "enabled": True, |
| "history_window_field": "history_window", |
| "teacher_memory_field": "teacher_explicit_memory", |
| "routing_target_field": "routing_target", |
| "positive_negative_teacher_fields": [ |
| "local_positive_teacher", |
| "local_negative_teacher", |
| "global_positive_teacher", |
| "global_negative_teacher", |
| ], |
| } |
|
|
| if canonical == "evaluator_sft": |
| return { |
| **common, |
| "training_type": "supervised_finetuning", |
| "target_format": "structured_text_or_json_scores", |
| "vision_input": { |
| "low_frames": 3, |
| "edited_frames": 3, |
| "high_frames": 0, |
| "max_total_frames": 6, |
| }, |
| "losses": ["cross_entropy_on_structured_output"], |
| "optimization": { |
| "learning_rate": 2e-5, |
| "weight_decay": 0.01, |
| "warmup_ratio": 0.03, |
| "epochs": 2, |
| "global_batch_size": 16, |
| }, |
| "focus": [ |
| "prompt_alignment", |
| "structure_preservation", |
| "transformation_strength", |
| "carrier_grounding", |
| "world_realization", |
| "temporal_coherence", |
| "artifact_penalty", |
| "overall_score", |
| ], |
| } |
| if canonical == "evaluator_regression": |
| return { |
| **common, |
| "training_type": "direct_multimodal_regression", |
| "target_format": "8_score_vector", |
| "losses": ["mse_on_teacher_scores"], |
| "optimization": { |
| "learning_rate": 1e-4, |
| "weight_decay": 0.01, |
| "warmup_ratio": 0.03, |
| "epochs": 2, |
| "global_batch_size": 8, |
| }, |
| "focus": [ |
| "fast_runtime_scoring", |
| "prompt_alignment", |
| "structure_preservation", |
| "transformation_strength", |
| "carrier_grounding", |
| "world_realization", |
| "temporal_coherence", |
| "artifact_penalty", |
| "overall_score", |
| ], |
| } |
| if canonical == "pairwise_rm": |
| return { |
| **common, |
| "training_type": "pairwise_reward_modeling", |
| "target_format": "scalar_reward_difference", |
| "losses": ["bradley_terry_pairwise_logistic"], |
| "optimization": { |
| "learning_rate": 1e-5, |
| "weight_decay": 0.01, |
| "warmup_ratio": 0.05, |
| "epochs": 1, |
| "global_batch_size": 8, |
| }, |
| "focus": [ |
| "fine_grained_preference", |
| "relative_quality_ranking", |
| "closer_to_high_cost_target", |
| ], |
| } |
| if canonical == "reflection_sft": |
| return { |
| **common, |
| "training_type": "supervised_policy_learning", |
| "target_format": "action_plus_patch_or_directives", |
| "losses": ["cross_entropy_on_action_and_structured_response"], |
| "optimization": { |
| "learning_rate": 2e-5, |
| "weight_decay": 0.01, |
| "warmup_ratio": 0.03, |
| "epochs": 2, |
| "global_batch_size": 16, |
| }, |
| "focus": [ |
| "accept_boundary", |
| "local_refine_boundary", |
| "global_replan_boundary", |
| "actionable_prompt_patch", |
| ], |
| } |
| return { |
| **common, |
| "training_type": "domain_adaptation", |
| "target_format": "calibrated_online_judgment", |
| "losses": ["cross_entropy", "preference_distillation"], |
| "optimization": { |
| "learning_rate": 5e-6, |
| "weight_decay": 0.01, |
| "warmup_ratio": 0.05, |
| "epochs": 1, |
| "global_batch_size": 8, |
| }, |
| "focus": [ |
| "online_distribution_shift", |
| "critic_calibration", |
| "planner_edit_replay_alignment", |
| ], |
| } |
|
|
|
|
| def _load_rows(path: Path, max_samples: int) -> list[dict]: |
| rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] |
| if max_samples > 0: |
| rows = rows[:max_samples] |
| return rows |
|
|
|
|
| def _resolve_stage_dataset_path(dataset: Path, stage: str) -> Path: |
| path = dataset.expanduser().resolve() |
| if path.is_file(): |
| return path |
| if not path.exists(): |
| raise FileNotFoundError(f"Dataset path not found: {path}") |
| if not path.is_dir(): |
| raise RuntimeError(f"Dataset path must be a JSONL file or directory: {path}") |
|
|
| candidates = list(STAGE_DATASET_CANDIDATES.get(stage, [])) |
| if not candidates: |
| canonical = _canonical_stage(stage) |
| candidates = list(STAGE_DATASET_CANDIDATES.get(canonical, [])) |
| if not candidates: |
| candidates = [f"{stage}.jsonl"] |
|
|
| for name in candidates: |
| candidate_path = path / name |
| if candidate_path.exists() and candidate_path.is_file(): |
| return candidate_path |
|
|
| available = sorted(item.name for item in path.glob("*.jsonl")) |
| raise FileNotFoundError( |
| "No stage dataset file found under " |
| f"{path} for stage={stage}. Tried={candidates}. Available={available}" |
| ) |
|
|
|
|
| def _has_teacher_scores(row: dict) -> bool: |
| return bool(row.get("teacher_scores")) |
|
|
|
|
| def _has_teacher_signal(row: dict) -> bool: |
| return bool( |
| row.get("teacher_scores") |
| or row.get("failure_tags") |
| or row.get("reflection_hints") |
| or row.get("teacher_reflection_action") |
| ) |
|
|
|
|
| def _derive_reflection_action(row: dict) -> str: |
| if row.get("teacher_reflection_action"): |
| return str(row["teacher_reflection_action"]) |
| scores = row.get("teacher_scores") or {} |
| overall = float(scores.get("overall_score", 0.0) or 0.0) |
| if overall >= 0.8: |
| return "accept" |
| if overall >= 0.45: |
| return "local_refine_prompt" |
| return "global_replan" |
|
|
|
|
| def _normalize_pairwise_winner(value: object) -> str: |
| raw = str(value or "").strip().lower() |
| mapping = { |
| "a": "a", |
| "candidate_a": "a", |
| "candidate-a": "a", |
| "left": "a", |
| "0": "a", |
| "b": "b", |
| "candidate_b": "b", |
| "candidate-b": "b", |
| "right": "b", |
| "1": "b", |
| } |
| return mapping.get(raw, "") |
|
|
|
|
| def _is_explicit_pairwise_row(row: dict) -> bool: |
| return bool( |
| row.get("low_video_path") |
| and row.get("prompt") |
| and row.get("candidate_a_video_path") |
| and row.get("candidate_b_video_path") |
| and _normalize_pairwise_winner(row.get("winner")) |
| ) |
|
|
|
|
| def _materialize_explicit_pairwise_records(rows: list[dict]) -> list[dict]: |
| pairwise_records: list[dict] = [] |
| for idx, row in enumerate(rows, start=1): |
| if not _is_explicit_pairwise_row(row): |
| continue |
| normalized = dict(row) |
| normalized["pair_id"] = str(row.get("pair_id", "") or f"pairwise_explicit_{idx:04d}") |
| normalized["pair_source_mode"] = str(row.get("pair_source_mode", "") or "explicit_pair_rows") |
| normalized["sample_a_id"] = str( |
| row.get("sample_a_id", "") |
| or row.get("candidate_a_id", "") |
| or row.get("sample_id", "") |
| ) |
| normalized["sample_b_id"] = str( |
| row.get("sample_b_id", "") |
| or row.get("candidate_b_id", "") |
| or row.get("sample_id", "") |
| ) |
| normalized["candidate_a_prompt"] = str(row.get("candidate_a_prompt", "") or row.get("prompt", "") or "") |
| normalized["candidate_b_prompt"] = str(row.get("candidate_b_prompt", "") or row.get("prompt", "") or "") |
| normalized["candidate_a_scores"] = row.get("candidate_a_scores", {}) or {} |
| normalized["candidate_b_scores"] = row.get("candidate_b_scores", {}) or {} |
| normalized["winner"] = _normalize_pairwise_winner(row.get("winner")) |
| normalized["preference_reason"] = str(row.get("preference_reason", "") or "") |
| pairwise_records.append(normalized) |
| return pairwise_records |
|
|
|
|
| def _derive_pairwise_records(rows: list[dict]) -> list[dict]: |
| rows = [row for row in rows if _has_teacher_scores(row)] |
| grouped_prompt: dict[tuple[str, str], list[dict]] = defaultdict(list) |
| for row in rows: |
| key_prompt = ( |
| str(row.get("low_video_path", "")), |
| str(row.get("prompt", "")), |
| ) |
| grouped_prompt[key_prompt].append(row) |
|
|
| pairwise_records: list[dict] = [] |
| pair_idx = 1 |
|
|
| def append_pairs(groups: dict, source_mode: str, start_idx: int) -> int: |
| pair_idx_local = start_idx |
| for _, group in groups.items(): |
| if len(group) < 2: |
| continue |
| ordered = sorted( |
| group, |
| key=lambda item: float((item.get("teacher_scores") or {}).get("overall_score", 0.0) or 0.0), |
| reverse=True, |
| ) |
| best = ordered[0] |
| for other in ordered[1:]: |
| best_score = float((best.get("teacher_scores") or {}).get("overall_score", 0.0) or 0.0) |
| other_score = float((other.get("teacher_scores") or {}).get("overall_score", 0.0) or 0.0) |
| if best_score == other_score and best.get("edited_video_path") == other.get("edited_video_path"): |
| continue |
| pairwise_records.append( |
| { |
| "pair_id": f"pairwise_{pair_idx_local:04d}", |
| "pair_source_mode": source_mode, |
| "sample_a_id": best.get("sample_id", ""), |
| "sample_b_id": other.get("sample_id", ""), |
| "low_video_path": best.get("low_video_path", ""), |
| "high_video_path": best.get("high_video_path", ""), |
| "prompt": best.get("prompt", ""), |
| "candidate_a_video_path": best.get("edited_video_path", ""), |
| "candidate_b_video_path": other.get("edited_video_path", ""), |
| "candidate_a_prompt": best.get("prompt", ""), |
| "candidate_b_prompt": other.get("prompt", ""), |
| "candidate_a_scores": best.get("teacher_scores", {}), |
| "candidate_b_scores": other.get("teacher_scores", {}), |
| "winner": "a" if best_score >= other_score else "b", |
| "preference_reason": ( |
| "candidate_a has higher teacher overall_score and is treated as the stronger edited result" |
| if best_score >= other_score |
| else "candidate_b has higher teacher overall_score and is treated as the stronger edited result" |
| ), |
| } |
| ) |
| pair_idx_local += 1 |
| return pair_idx_local |
|
|
| pair_idx = append_pairs(grouped_prompt, "same_low_and_prompt", pair_idx) |
| if pairwise_records: |
| return pairwise_records |
|
|
| grouped_low: dict[str, list[dict]] = defaultdict(list) |
| for row in rows: |
| grouped_low[str(row.get("low_video_path", ""))].append(row) |
| pair_idx = append_pairs(grouped_low, "same_low_fallback", pair_idx) |
| return pairwise_records |
|
|
|
|
| def _materialize_stage_records(stage: str, rows: list[dict]) -> list[dict]: |
| canonical = _canonical_stage(stage) |
| if canonical in {"evaluator_sft", "evaluator_regression"}: |
| return [ |
| row |
| for row in rows |
| if row.get("low_video_path") and row.get("edited_video_path") and row.get("prompt") and row.get("teacher_scores") |
| ] |
|
|
| if canonical == "pairwise_rm": |
| explicit_pairwise_rows = _materialize_explicit_pairwise_records(rows) |
| if explicit_pairwise_rows: |
| return explicit_pairwise_rows |
| return _derive_pairwise_records(rows) |
|
|
| if canonical == "reflection_sft": |
| reflection_rows: list[dict] = [] |
| for row in rows: |
| if not _has_teacher_signal(row): |
| continue |
| if not row.get("low_video_path") or not row.get("edited_video_path") or not row.get("prompt"): |
| continue |
| item = dict(row) |
| item["teacher_reflection_action"] = _derive_reflection_action(row) |
| reflection_rows.append(item) |
| return reflection_rows |
|
|
| return rows |
|
|
|
|
| def _write_jsonl(path: Path, rows: list[dict]) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| with path.open("w", encoding="utf-8") as f: |
| for row in rows: |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") |
|
|
|
|
| def _split_rows(rows: list[dict]) -> tuple[list[dict], list[dict]]: |
| if not rows: |
| return [], [] |
| if len(rows) == 1: |
| return rows, [] |
| if len(rows) <= 4: |
| return rows[:-1], rows[-1:] |
| val_count = max(1, int(round(len(rows) * 0.2))) |
| return rows[:-val_count], rows[-val_count:] |
|
|
|
|
| def _format_scores_text(scores: dict) -> str: |
| if _is_aesthetic_score_schema(scores): |
| return _format_aesthetic_evaluator_target({"teacher_scores": scores}) |
| return "\n".join( |
| [ |
| f"PROMPT_ALIGNMENT: {float(scores.get('prompt_alignment', 0.0) or 0.0):.3f}", |
| f"STRUCTURE_PRESERVATION: {float(scores.get('structure_preservation', 0.0) or 0.0):.3f}", |
| f"TRANSFORMATION_STRENGTH: {float(scores.get('transformation_strength', 0.0) or 0.0):.3f}", |
| f"CARRIER_GROUNDING: {float(scores.get('carrier_grounding', 0.0) or 0.0):.3f}", |
| f"WORLD_REALIZATION: {float(scores.get('world_realization', 0.0) or 0.0):.3f}", |
| f"TEMPORAL_COHERENCE: {float(scores.get('temporal_coherence', 0.0) or 0.0):.3f}", |
| f"ARTIFACT_PENALTY: {float(scores.get('artifact_penalty', 0.0) or 0.0):.3f}", |
| f"OVERALL_SCORE: {float(scores.get('overall_score', 0.0) or 0.0):.3f}", |
| ] |
| ) |
|
|
|
|
| def _is_aesthetic_score_schema(scores: dict) -> bool: |
| return any( |
| key in (scores or {}) |
| for key in [ |
| "narrative_emotional_fit", |
| "style_world_consistency", |
| "composition_lighting_design", |
| "color_texture_refinement", |
| "visual_hierarchy_readability", |
| "overall_aesthetic_score", |
| ] |
| ) |
|
|
|
|
| def _format_aesthetic_scores_text(scores: dict) -> str: |
| return _format_aesthetic_evaluator_target({"teacher_scores": scores}) |
|
|
|
|
| def _clamp_aesthetic_dimension_score(value: object) -> int: |
| try: |
| score = int(round(float(value))) |
| except (TypeError, ValueError): |
| score = 1 |
| return max(1, min(4, score)) |
|
|
|
|
| def _clamp_aesthetic_overall_score(value: object) -> float: |
| try: |
| score = float(value) |
| except (TypeError, ValueError): |
| score = 1.0 |
| return max(1.0, min(4.0, score)) |
|
|
|
|
| def _build_aesthetic_evaluator_system_prompt() -> str: |
| return """You are a strict cinematic/VFX aesthetic rater. |
| You are doing pointwise standalone aesthetic scoring: you see sampled frames |
| from the edited video, but you do not see the source video. Use the editing |
| instruction only as weak context for the intended visual direction. Do not judge |
| whether the edit accurately followed the instruction, because the source video is |
| not provided. |
| |
| Scoring scale for every dimension: |
| 4 = excellent / strongly successful |
| 3 = good with minor issues |
| 2 = weak with clear issues |
| 1 = failed or harms the aesthetic goal |
| |
| Rules: |
| - Score each dimension independently. |
| - There is no neutral middle score. Choose 2 or 3 when uncertain between weak and good. |
| - If a video matches multiple descriptions, assign the lowest applicable score. |
| - For object removal, cleanup, denoising, de-watermarking, or other utility edits, |
| a seamless and visually natural result can be aesthetically successful even if |
| it is not dramatic or cinematic. |
| - Do not penalize a candidate because the requested edit removes an interesting |
| object or makes the scene simpler. |
| - Do not give high artistic scores just because the image is sharp or expensive-looking. |
| - Do not give high color scores just because colors are saturated. |
| - Penalize visible inpainting seams, visual clutter, incoherent style mixing, |
| cheap texture/filter look, and unclear focal hierarchy when they are visible in |
| the edited frames. |
| - Return valid JSON only, with no markdown. |
| """ |
|
|
|
|
| def _infer_aesthetic_task_type(instruction: str) -> str: |
| text = instruction.lower() |
| if any(word in text for word in ["remove", "erase", "delete", "hide", "clean up", "de-watermark", "watermark", "logo"]): |
| return "removal_or_cleanup" |
| if any(word in text for word in ["add", "insert", "place", "put ", "introduce", "include"]): |
| return "addition_or_insertion" |
| if any(word in text for word in ["replace", "swap", "change into", "turn into", "transform", "convert"]): |
| return "replacement_or_transformation" |
| if any(word in text for word in ["style", "aesthetic", "cinematic", "film", "color", "lighting", "tone", "grain", "texture"]): |
| return "style_or_look_change" |
| if any(word in text for word in ["enhance", "restore", "sharpen", "denoise", "improve", "refine"]): |
| return "quality_refinement" |
| return "general_edit" |
|
|
|
|
| def _build_aesthetic_evaluator_user_prompt(row: dict) -> str: |
| instruction = str(row.get("prompt", "") or "") |
| task_type = _infer_aesthetic_task_type(instruction) |
| return f"""Editing instruction / intended effect: |
| {instruction} |
| |
| Inferred task type: |
| {task_type} |
| |
| Important: you do not see the source video. Do not evaluate whether the edit was |
| completed relative to the source. Evaluate the final edited video as a standalone |
| visual result. For removal or cleanup tasks, invisible/seamless blending is a |
| positive aesthetic outcome. |
| |
| Evaluate the edited video frames on these five dimensions: |
| 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. |
| 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. |
| 3. composition_lighting_design: composition, contrast, lighting hierarchy, lens/cinematic design, and shot-level visual arrangement. |
| 4. color_texture_refinement: color harmony, saturation control, material/texture/filter refinement, and whether it avoids cheap or generic looks. |
| 5. visual_hierarchy_readability: whether the main visual intent is clear, focal hierarchy is readable, and important content is not obscured. |
| |
| "overall_aesthetic_score" should be a holistic assessment of final visual |
| quality from 1.0 to 4.0, not a simple mathematical average of the five |
| dimensions. |
| |
| Return this exact JSON schema: |
| {{ |
| "scores": {{ |
| "narrative_emotional_fit": 1, |
| "style_world_consistency": 1, |
| "composition_lighting_design": 1, |
| "color_texture_refinement": 1, |
| "visual_hierarchy_readability": 1 |
| }}, |
| "overall_aesthetic_score": 1.0, |
| "uncertain": false, |
| "reason": "one concise sentence" |
| }} |
| """ |
|
|
|
|
| def _format_aesthetic_evaluator_target(row: dict) -> str: |
| scores = row.get("teacher_scores", {}) or {} |
| raw_label = row.get("raw_label", {}) or {} |
| hints = row.get("reflection_hints", []) or [] |
| reason = str(raw_label.get("reason", "") or (hints[0] if hints else "") or "") |
| payload = { |
| "scores": { |
| "narrative_emotional_fit": _clamp_aesthetic_dimension_score(scores.get("narrative_emotional_fit", 1)), |
| "style_world_consistency": _clamp_aesthetic_dimension_score(scores.get("style_world_consistency", 1)), |
| "composition_lighting_design": _clamp_aesthetic_dimension_score(scores.get("composition_lighting_design", 1)), |
| "color_texture_refinement": _clamp_aesthetic_dimension_score(scores.get("color_texture_refinement", 1)), |
| "visual_hierarchy_readability": _clamp_aesthetic_dimension_score(scores.get("visual_hierarchy_readability", 1)), |
| }, |
| "overall_aesthetic_score": _clamp_aesthetic_overall_score(scores.get("overall_aesthetic_score", raw_label.get("overall_aesthetic_score", 1.0))), |
| "uncertain": bool(raw_label.get("uncertain", False)), |
| "reason": reason, |
| } |
| return json.dumps(payload, ensure_ascii=False, indent=2) |
|
|
|
|
| def _format_evaluator_target(row: dict) -> str: |
| scores = row.get("teacher_scores", {}) or {} |
| if _is_aesthetic_score_schema(scores): |
| return _format_aesthetic_evaluator_target(row) |
| failure_tags = row.get("failure_tags", []) or [] |
| reflection_hints = row.get("reflection_hints", []) or [] |
| notes = row.get("teacher_replan_directives", []) or [] |
| return "\n".join( |
| [ |
| _format_scores_text(scores), |
| "FAILURE_TAGS: " + ", ".join(str(tag) for tag in failure_tags), |
| "REFLECTION_HINTS: " + ", ".join(str(hint) for hint in reflection_hints), |
| "NOTES: " + ", ".join(str(item) for item in notes), |
| ] |
| ).strip() |
|
|
|
|
| def _format_reflection_target(row: dict) -> str: |
| action = str(row.get("teacher_reflection_action", "global_replan") or "global_replan") |
| prompt_patch = row.get("teacher_prompt_patch", []) or [] |
| replan_directives = row.get("teacher_replan_directives", []) or [] |
| reason = "" |
| hints = row.get("reflection_hints", []) or [] |
| if hints: |
| reason = str(hints[0]) |
| elif action == "accept": |
| reason = "Teacher judged the edit acceptable." |
| elif action == "local_refine_prompt": |
| reason = "Teacher judged the result directionally correct but still locally improvable." |
| else: |
| reason = "Teacher judged the current plan too weak and recommended replanning." |
| return json.dumps( |
| { |
| "action": action, |
| "reason": reason, |
| "prompt_patch": prompt_patch, |
| "replan_directives": replan_directives, |
| }, |
| ensure_ascii=False, |
| ) |
|
|
|
|
| def _coerce_optional_dict(value: object) -> dict: |
| if isinstance(value, dict): |
| return value |
| if isinstance(value, str): |
| text = value.strip() |
| if text.startswith("{") and text.endswith("}"): |
| try: |
| parsed = json.loads(text) |
| except json.JSONDecodeError: |
| return {} |
| if isinstance(parsed, dict): |
| return parsed |
| return {} |
|
|
|
|
| def _compact_memory_history(row: dict, *, limit: int = 3) -> list[dict]: |
| history = row.get("history_window", []) or [] |
| compact: list[dict] = [] |
| for item in history[:limit]: |
| if not isinstance(item, dict): |
| continue |
| compact.append( |
| { |
| "attempt_index": int(item.get("attempt_index", 0) or 0), |
| "overall_score": float(item.get("overall_score", 0.0) or 0.0), |
| "action": str(item.get("action", "") or ""), |
| "style_family": str(item.get("style_family", "") or ""), |
| "scene_archetype": str(item.get("scene_archetype", "") or ""), |
| "selected_strategy": str(item.get("selected_strategy", "") or ""), |
| "primary_fx_carriers": list(item.get("primary_fx_carriers", []) or [])[:4], |
| "failure_tags": list(item.get("failure_tags", []) or [])[:6], |
| } |
| ) |
| return compact |
|
|
|
|
| def _compact_teacher_memory(row: dict) -> dict: |
| teacher = row.get("teacher_explicit_memory", {}) or {} |
| if not isinstance(teacher, dict): |
| return {} |
| return { |
| "scene_archetypes": list(teacher.get("scene_archetypes", []) or [])[:3], |
| "failure_patterns": list(teacher.get("failure_patterns", []) or [])[:4], |
| "style_convertibility_priors": list(teacher.get("style_convertibility_priors", []) or [])[:3], |
| "prompt_compilation_recipe_candidates": list(teacher.get("prompt_compilation_recipe_candidates", []) or [])[:3], |
| "custom_skill_records": list(teacher.get("custom_skill_records", []) or [])[:4], |
| } |
|
|
|
|
| def _compact_memory_side(row: dict, key: str) -> dict: |
| payload = row.get(key, {}) or {} |
| if not isinstance(payload, dict): |
| return {} |
| compact: dict[str, object] = {} |
| for field in [ |
| "recommended_carriers", |
| "anchor_hints", |
| "stable_strategies", |
| "prompt_patch_hints", |
| "failure_tags", |
| "fragile_carriers", |
| "weak_dimensions", |
| "style_families", |
| "archetypes", |
| "strategies", |
| "replan_directives", |
| ]: |
| value = payload.get(field) |
| if isinstance(value, list): |
| compact[field] = value[:6] |
| return compact |
|
|
|
|
| def _format_implicit_memory_context(row: dict) -> str: |
| payload = { |
| "routing_target": str(row.get("routing_target", "") or ""), |
| "history_window": _compact_memory_history(row), |
| "teacher_explicit_memory": _compact_teacher_memory(row), |
| "local_positive_teacher": _compact_memory_side(row, "local_positive_teacher"), |
| "local_negative_teacher": _compact_memory_side(row, "local_negative_teacher"), |
| "global_positive_teacher": _compact_memory_side(row, "global_positive_teacher"), |
| "global_negative_teacher": _compact_memory_side(row, "global_negative_teacher"), |
| } |
| return "隐式记忆教师上下文(仅供模型吸收历史信号):\n" + json.dumps(payload, ensure_ascii=False, indent=2) |
|
|
|
|
| def _format_user_text_for_stage(stage: str, row: dict) -> str: |
| canonical = _canonical_stage(stage) |
| if canonical == "evaluator_sft": |
| scores = row.get("teacher_scores", {}) or {} |
| if _is_aesthetic_score_schema(scores): |
| text = _build_aesthetic_evaluator_user_prompt(row) |
| if _is_implicit_stage(stage): |
| text += "\n\n" + _format_implicit_memory_context(row) |
| return text |
| text = build_edit_evaluator_user_prompt( |
| sample_id=str(row.get("sample_id", "") or ""), |
| prompt=str(row.get("prompt", "") or ""), |
| planner_summary=_coerce_optional_dict(row.get("planner_summary", {})), |
| edit_summary=_coerce_optional_dict(row.get("edit_summary", {})), |
| metric_hints=_coerce_optional_dict(row.get("metric_hints", {})), |
| ) |
| if _is_implicit_stage(stage): |
| text += "\n\n" + _format_implicit_memory_context(row) |
| return text |
| if canonical == "reflection_sft": |
| scores = row.get("teacher_scores", {}) or {} |
| common = ( |
| f"sample_id: {row.get('sample_id', '')}\n" |
| f"prompt: {row.get('prompt', '')}\n" |
| f"low_video_path: {row.get('low_video_path', '')}\n" |
| f"edited_video_path: {row.get('edited_video_path', '')}\n" |
| f"high_video_path: {row.get('high_video_path', '')}\n" |
| "图片顺序如下:前半部分是 low video 抽帧,接着是 edited video 抽帧,最后是 high video 抽帧。\n" |
| ) |
| text = ( |
| build_critic_identity_prefix() |
| + "请根据已有的结构化评估结果,决定 accept、local_refine_prompt 或 global_replan。\n" |
| + common |
| + "已知评估分数如下:\n" |
| + _format_scores_text(scores) |
| + "\nfailure_tags: " |
| + ", ".join(str(tag) for tag in (row.get("failure_tags", []) or [])) |
| + "\nreflection_hints: " |
| + ", ".join(str(hint) for hint in (row.get("reflection_hints", []) or [])) |
| ) |
| if _is_implicit_stage(stage): |
| text += "\n" + _format_implicit_memory_context(row) |
| return text |
| raise ValueError(f"real SFT does not support stage={stage}") |
|
|
|
|
| def _build_multimodal_messages(stage: str, row: dict, image_paths: list[str]) -> tuple[list[dict], str]: |
| user_content = [{"type": "text", "text": _format_user_text_for_stage(stage, row)}] |
| for image_path in image_paths: |
| user_content.append({"type": "image", "image": str(image_path)}) |
| assistant_text = _format_evaluator_target(row) if _canonical_stage(stage) == "evaluator_sft" else _format_reflection_target(row) |
| messages: list[dict] = [] |
| if _canonical_stage(stage) == "evaluator_sft": |
| scores = row.get("teacher_scores", {}) or {} |
| system_text = _build_aesthetic_evaluator_system_prompt() if _is_aesthetic_score_schema(scores) else build_edit_evaluator_system_prompt() |
| messages.append({"role": "system", "content": [{"type": "text", "text": system_text}]}) |
| messages.extend( |
| [ |
| {"role": "user", "content": user_content}, |
| {"role": "assistant", "content": [{"type": "text", "text": assistant_text}]}, |
| ] |
| ) |
| return messages, assistant_text |
|
|
|
|
| def _build_pairwise_messages(row: dict, image_paths: list[str]) -> list[dict]: |
| prompt = str(row.get("prompt", "") or "") |
| preference_reason = str(row.get("preference_reason", "") or "") |
| user_text = ( |
| build_critic_identity_prefix() |
| + |
| "请比较 candidate A 和 candidate B,判断哪个 edited result 更接近目标 high-cost 结果。\n" |
| f"prompt: {prompt}\n" |
| f"candidate_a_prompt: {row.get('candidate_a_prompt', '')}\n" |
| f"candidate_b_prompt: {row.get('candidate_b_prompt', '')}\n" |
| f"preference_reason_hint: {preference_reason}\n" |
| "图片顺序如下:先是 low video 抽帧,再是 high video 抽帧,然后是 candidate A 抽帧,最后是 candidate B 抽帧。\n" |
| "只需要在内部判断 winner,不需要生成文本。" |
| ) |
| user_content = [{"type": "text", "text": user_text}] |
| for image_path in image_paths: |
| user_content.append({"type": "image", "image": str(image_path)}) |
| return [{"role": "user", "content": user_content}] |
|
|
|
|
| def _build_pairwise_reward_messages(stage: str, row: dict, *, candidate_key: str, image_paths: list[str]) -> list[dict]: |
| prompt = str(row.get("prompt", "") or "") |
| candidate_prompt = str(row.get(f"candidate_{candidate_key}_prompt", "") or prompt) |
| user_text = ( |
| build_critic_identity_prefix() |
| + |
| "请根据 low、high 和单个 edited candidate 的抽帧,对该 candidate 的整体质量形成内部 reward 表征。\n" |
| f"prompt: {prompt}\n" |
| f"candidate_prompt: {candidate_prompt}\n" |
| "图片顺序如下:先是 low video 抽帧,再是 high video 抽帧,最后是该 edited candidate 抽帧。\n" |
| "只需要在内部形成单个标量 reward,不需要生成文本。" |
| ) |
| if _is_implicit_stage(stage): |
| user_text += "\n" + _format_implicit_memory_context(row) |
| user_content = [{"type": "text", "text": user_text}] |
| for image_path in image_paths: |
| user_content.append({"type": "image", "image": str(image_path)}) |
| return [{"role": "user", "content": user_content}] |
|
|
|
|
| def _build_evaluator_regression_messages(row: dict, image_paths: list[str]) -> list[dict]: |
| user_text = ( |
| build_critic_identity_prefix() |
| + |
| "请根据 low video 和 edited video 的抽帧,以及目标 prompt,对编辑结果做快速多维判断。\n" |
| f"prompt: {row.get('prompt', '')}\n" |
| f"scene_archetype: {row.get('scene_archetype', '')}\n" |
| f"style_family: {row.get('style_family', '')}\n" |
| "图片顺序如下:先是 low video 抽帧,然后是 edited video 抽帧,最后是 high video 抽帧(如果存在)。\n" |
| "内部关注维度:prompt_alignment, structure_preservation, transformation_strength, carrier_grounding, " |
| "world_realization, temporal_coherence, artifact_penalty, overall_score。\n" |
| "不要生成文本,只做内部表征和分数回归。" |
| ) |
| user_content = [{"type": "text", "text": user_text}] |
| for image_path in image_paths: |
| user_content.append({"type": "image", "image": str(image_path)}) |
| return [{"role": "user", "content": user_content}] |
|
|
|
|
| def _extract_training_frames(row: dict, frames_per_video: int, *, include_high: bool = True) -> list[str]: |
| image_paths: list[str] = [] |
| frame_keys = ["low_video_path", "edited_video_path"] |
| if include_high: |
| frame_keys.append("high_video_path") |
| for key in frame_keys: |
| value = str(row.get(key, "") or "").strip() |
| if not value: |
| continue |
| image_paths.extend(str(p) for p in extract_frames_jpg(value, frame_count=frames_per_video)) |
| return image_paths |
|
|
|
|
| def _extract_aesthetic_training_frames(row: dict, frames_per_video: int) -> list[str]: |
| value = str(row.get("edited_video_path", "") or "").strip() |
| if not value: |
| return [] |
| return [str(p) for p in extract_frames_jpg(value, frame_count=frames_per_video)] |
|
|
|
|
| def _extract_pairwise_frames(row: dict, frames_per_video: int) -> list[str]: |
| image_paths: list[str] = [] |
| for key in ["low_video_path", "high_video_path", "candidate_a_video_path", "candidate_b_video_path"]: |
| value = str(row.get(key, "") or "").strip() |
| if not value: |
| continue |
| image_paths.extend(str(p) for p in extract_frames_jpg(value, frame_count=frames_per_video)) |
| return image_paths |
|
|
|
|
| def _extract_pairwise_candidate_frames(row: dict, *, candidate_key: str, frames_per_video: int) -> list[str]: |
| image_paths: list[str] = [] |
| candidate_video_key = f"candidate_{candidate_key}_video_path" |
| for key in ["low_video_path", "high_video_path", candidate_video_key]: |
| value = str(row.get(key, "") or "").strip() |
| if not value: |
| continue |
| image_paths.extend(str(p) for p in extract_frames_jpg(value, frame_count=frames_per_video)) |
| return image_paths |
|
|
|
|
| def _make_peft_model(model, args: argparse.Namespace): |
| lora_config = LoraConfig( |
| r=args.lora_r, |
| lora_alpha=args.lora_alpha, |
| lora_dropout=args.lora_dropout, |
| bias="none", |
| task_type="CAUSAL_LM", |
| target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], |
| ) |
| peft_model = get_peft_model(model, lora_config) |
| peft_model.print_trainable_parameters() |
| return peft_model |
|
|
|
|
| def _resolve_resume_checkpoint(output_dir: Path, resume_from: str) -> Path | None: |
| return _resolve_checkpoint_reference( |
| str(resume_from or "").strip(), |
| default_output_dir=output_dir, |
| argument_name="--resume-from", |
| ) |
|
|
|
|
| def _resolve_checkpoint_reference( |
| raw_value: str, |
| *, |
| default_output_dir: Path | None, |
| argument_name: str, |
| ) -> Path | None: |
| value = str(raw_value or "").strip() |
| if not value: |
| return None |
| if value == "latest": |
| if default_output_dir is None: |
| raise RuntimeError(f"{argument_name}=latest requires a checkpoint output directory.") |
| latest_pointer = default_output_dir / "real_sft_latest_checkpoint.txt" |
| if not latest_pointer.exists(): |
| raise FileNotFoundError(f"Latest checkpoint pointer not found: {latest_pointer}") |
| value = latest_pointer.read_text(encoding="utf-8").strip() |
| if not value: |
| raise RuntimeError(f"Latest checkpoint pointer is empty: {latest_pointer}") |
|
|
| checkpoint_dir = Path(value).expanduser() |
| if not checkpoint_dir.exists(): |
| raise FileNotFoundError(f"Checkpoint reference not found for {argument_name}: {checkpoint_dir}") |
| if not checkpoint_dir.is_dir(): |
| raise NotADirectoryError(f"Checkpoint reference for {argument_name} must be a directory: {checkpoint_dir}") |
|
|
| if (checkpoint_dir / "trainer_state.json").exists(): |
| return checkpoint_dir |
|
|
| latest_pointer = checkpoint_dir / "real_sft_latest_checkpoint.txt" |
| if latest_pointer.exists(): |
| latest_value = latest_pointer.read_text(encoding="utf-8").strip() |
| if not latest_value: |
| raise RuntimeError(f"Latest checkpoint pointer is empty: {latest_pointer}") |
| resolved = Path(latest_value).expanduser() |
| if not resolved.exists(): |
| raise FileNotFoundError(f"Checkpoint referenced by {latest_pointer} does not exist: {resolved}") |
| if not resolved.is_dir(): |
| raise NotADirectoryError(f"Checkpoint referenced by {latest_pointer} is not a directory: {resolved}") |
| return resolved |
|
|
| final_checkpoint = checkpoint_dir / "real_sft_checkpoint" |
| if (final_checkpoint / "trainer_state.json").exists(): |
| return final_checkpoint |
|
|
| if (checkpoint_dir / "adapter_config.json").exists(): |
| return checkpoint_dir |
|
|
| raise FileNotFoundError( |
| f"Could not resolve a usable checkpoint from {argument_name}={checkpoint_dir}. " |
| "Expected a checkpoint dir, an output dir with real_sft_latest_checkpoint.txt, " |
| "or an output dir with real_sft_checkpoint/." |
| ) |
|
|
|
|
| def _resolve_init_checkpoint(init_from: str) -> Path | None: |
| return _resolve_checkpoint_reference( |
| str(init_from or "").strip(), |
| default_output_dir=None, |
| argument_name="--init-from-checkpoint", |
| ) |
|
|
|
|
| def _load_trainer_state_if_available(checkpoint_dir: Path | None) -> dict: |
| if checkpoint_dir is None: |
| return {} |
| trainer_state_path = checkpoint_dir / "trainer_state.json" |
| if not trainer_state_path.exists(): |
| return {} |
| return json.loads(trainer_state_path.read_text(encoding="utf-8")) |
|
|
|
|
| def _supports_cross_stage_init(*, target_stage: str, init_stage: str) -> bool: |
| target_canonical = _canonical_stage(target_stage) |
| init_canonical = _canonical_stage(init_stage) |
| if not init_stage or init_stage == target_stage or (target_canonical == init_canonical and init_canonical): |
| return True |
| return target_canonical == "pairwise_rm" and init_canonical == "evaluator_sft" |
|
|
|
|
| def _processor_source_path(*, model_path: str, checkpoint_dir: Path | None) -> str: |
| if checkpoint_dir is None: |
| return model_path |
| processor_markers = [ |
| "preprocessor_config.json", |
| "processor_config.json", |
| "tokenizer_config.json", |
| ] |
| if any((checkpoint_dir / marker).exists() for marker in processor_markers): |
| return str(checkpoint_dir) |
| return model_path |
|
|
|
|
| def _checkpoint_base_model_path(checkpoint_dir: Path | None) -> str: |
| if checkpoint_dir is None: |
| return "" |
| path = checkpoint_dir / "base_model_path.txt" |
| if not path.exists(): |
| return "" |
| return path.read_text(encoding="utf-8").strip() |
|
|
|
|
| def _init_metadata( |
| *, |
| init_checkpoint: Path | None, |
| init_state: dict, |
| ) -> dict: |
| return { |
| "init_from_checkpoint": str(init_checkpoint) if init_checkpoint is not None else "", |
| "init_from_stage": str(init_state.get("stage", "") or ""), |
| "init_from_model_path": _checkpoint_base_model_path(init_checkpoint), |
| } |
|
|
|
|
| def _effective_model_path( |
| *, |
| explicit_model_path: str, |
| resume_checkpoint: Path | None, |
| init_checkpoint: Path | None, |
| ) -> str: |
| if explicit_model_path: |
| return explicit_model_path |
| for candidate in [ |
| _checkpoint_base_model_path(resume_checkpoint), |
| _checkpoint_base_model_path(init_checkpoint), |
| ]: |
| if candidate: |
| return candidate |
| return str(local_model_path()) |
|
|
|
|
| def _build_stage_mismatch_resume_error(*, resume_checkpoint: Path, expected_stage: str, actual_stage: str) -> RuntimeError: |
| message = f"Resume checkpoint stage mismatch: expected {expected_stage}, got {actual_stage}" |
| if _canonical_stage(expected_stage) == "pairwise_rm" and _canonical_stage(actual_stage) == "evaluator_sft": |
| message += ( |
| f". To start pairwise training from the evaluator critic weights, use " |
| f"--init-from-checkpoint {resume_checkpoint} instead of --resume-from." |
| ) |
| return RuntimeError(message) |
|
|
|
|
| def _optimizer_to_device(optimizer: torch.optim.Optimizer, device: torch.device) -> None: |
| for state in optimizer.state.values(): |
| for key, value in state.items(): |
| if torch.is_tensor(value): |
| state[key] = value.to(device) |
|
|
|
|
| def _format_duration(seconds: float) -> str: |
| total_seconds = max(0, int(round(seconds))) |
| hours, remainder = divmod(total_seconds, 3600) |
| minutes, secs = divmod(remainder, 60) |
| if hours > 0: |
| return f"{hours}h{minutes:02d}m{secs:02d}s" |
| if minutes > 0: |
| return f"{minutes}m{secs:02d}s" |
| return f"{secs}s" |
|
|
|
|
| def _run_real_sft( |
| *, |
| args: argparse.Namespace, |
| stage: str, |
| train_rows: list[dict], |
| val_rows: list[dict], |
| output_dir: Path, |
| ) -> dict: |
| canonical_stage = _canonical_stage(stage) |
|
|
| def _match_head_input_dtype(hidden_states: torch.Tensor, head: nn.Linear) -> torch.Tensor: |
| return hidden_states.to(device=head.weight.device, dtype=head.weight.dtype) |
|
|
| metrics_path = output_dir / "real_sft_metrics.jsonl" |
| if not args.resume_from or not metrics_path.exists(): |
| metrics_path.write_text("", encoding="utf-8") |
| checkpoint_dir = output_dir / "real_sft_checkpoint" |
| checkpoints_root = output_dir / "real_sft_checkpoints" |
| latest_checkpoint_path = output_dir / "real_sft_latest_checkpoint.txt" |
| real_sft_status_path = output_dir / "real_sft_status.json" |
| real_sft_error_path = output_dir / "real_sft_error.json" |
| if args.resume_from and args.init_from_checkpoint: |
| raise RuntimeError("--resume-from and --init-from-checkpoint cannot be used together.") |
| resume_checkpoint = _resolve_resume_checkpoint(output_dir, args.resume_from) |
| init_checkpoint = _resolve_init_checkpoint(args.init_from_checkpoint) |
|
|
| if not train_rows: |
| status = { |
| "stage": stage, |
| "status": "skipped", |
| "reason": "no_train_samples", |
| } |
| real_sft_status_path.write_text(json.dumps(status, ensure_ascii=False, indent=2), encoding="utf-8") |
| return status |
|
|
| model = None |
| processor = None |
| optimizer = None |
| pairwise_head = None |
| evaluator_head = None |
| summary_writer = None |
| global_step = 0 |
| completed_epochs = 0 |
| start_epoch = 1 |
| start_row_index = 0 |
| model_path = "" |
| init_state: dict = {} |
| init_stage = "" |
|
|
| try: |
| resume_state: dict = {} |
| init_state = _load_trainer_state_if_available(init_checkpoint) |
| init_stage = str(init_state.get("stage", "") or "") |
| if resume_checkpoint is not None: |
| trainer_state_path = resume_checkpoint / "trainer_state.json" |
| if not trainer_state_path.exists(): |
| raise FileNotFoundError(f"trainer_state.json not found in resume checkpoint: {resume_checkpoint}") |
| resume_state = json.loads(trainer_state_path.read_text(encoding="utf-8")) |
| resume_stage = str(resume_state.get("stage", "") or "") |
| if resume_stage and _canonical_stage(resume_stage) != canonical_stage: |
| raise _build_stage_mismatch_resume_error( |
| resume_checkpoint=resume_checkpoint, |
| expected_stage=stage, |
| actual_stage=resume_stage, |
| ) |
|
|
| if init_checkpoint is not None and not _supports_cross_stage_init(target_stage=stage, init_stage=init_stage): |
| raise RuntimeError( |
| f"Unsupported cross-stage initialization: target stage={stage}, init stage={init_stage or 'unknown'}" |
| ) |
| if init_checkpoint is not None and canonical_stage == "evaluator_regression": |
| raise RuntimeError( |
| "--init-from-checkpoint is not supported for evaluator_regression. " |
| "That stage only trains a standalone fast score head; use --resume-from for same-stage continuation." |
| ) |
|
|
| model_path = _effective_model_path( |
| explicit_model_path=str(args.real_model_path or "").strip(), |
| resume_checkpoint=resume_checkpoint, |
| init_checkpoint=init_checkpoint, |
| ) |
| processor_path = _processor_source_path( |
| model_path=model_path, |
| checkpoint_dir=resume_checkpoint or init_checkpoint, |
| ) |
|
|
| if args.tensorboard: |
| if SummaryWriter is None: |
| raise RuntimeError("TensorBoard logging requested, but torch.utils.tensorboard is unavailable.") |
| tensorboard_dir = Path(args.tensorboard_dir).expanduser() if args.tensorboard_dir else (output_dir / "tensorboard") |
| summary_writer = SummaryWriter(log_dir=str(tensorboard_dir)) |
| print( |
| ( |
| f"[real_sft] stage={stage} train_rows={len(train_rows)} val_rows={len(val_rows)} " |
| f"epochs={args.epochs} frames_per_video={args.frames_per_video} lr={args.lr} " |
| f"save_every_steps={args.save_every_steps} log_every_steps={args.log_every_steps} " |
| f"resume_from={resume_checkpoint or 'none'} init_from={init_checkpoint or 'none'} " |
| f"init_stage={init_stage or 'unknown'} tensorboard={'on' if summary_writer is not None else 'off'}" |
| ), |
| flush=True, |
| ) |
|
|
| processor = AutoProcessor.from_pretrained(processor_path, trust_remote_code=True) |
| model = AutoModelForImageTextToText.from_pretrained( |
| model_path, |
| torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32, |
| trust_remote_code=True, |
| ) |
| if torch.cuda.is_available(): |
| model = model.to("cuda") |
|
|
| if canonical_stage == "evaluator_regression": |
| for param in model.parameters(): |
| param.requires_grad = False |
| model.eval() |
| else: |
| if hasattr(model, "gradient_checkpointing_enable"): |
| model.gradient_checkpointing_enable() |
| if resume_checkpoint is not None: |
| adapter_config_path = resume_checkpoint / "adapter_config.json" |
| if not adapter_config_path.exists(): |
| raise FileNotFoundError( |
| f"adapter_config.json not found in resume checkpoint: {resume_checkpoint}" |
| ) |
| model = PeftModel.from_pretrained(model, str(resume_checkpoint), is_trainable=True) |
| elif init_checkpoint is not None: |
| adapter_config_path = init_checkpoint / "adapter_config.json" |
| if not adapter_config_path.exists(): |
| raise FileNotFoundError( |
| f"adapter_config.json not found in init checkpoint: {init_checkpoint}" |
| ) |
| model = PeftModel.from_pretrained(model, str(init_checkpoint), is_trainable=True) |
| else: |
| model = _make_peft_model(model, args) |
| model.train() |
| optimizer = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=args.lr) |
|
|
| pairwise_criterion = None |
| regression_criterion = None |
| if canonical_stage == "pairwise_rm": |
| hidden_size = getattr(getattr(model, "config", None), "hidden_size", None) |
| if hidden_size is None: |
| hidden_size = getattr(getattr(model, "config", None), "text_config", None) |
| hidden_size = getattr(hidden_size, "hidden_size", None) |
| if hidden_size is None: |
| raise RuntimeError("Unable to infer hidden_size for pairwise reward head.") |
| pairwise_head = nn.Linear(int(hidden_size), 1) |
| if torch.cuda.is_available(): |
| pairwise_head = pairwise_head.to("cuda") |
| if resume_checkpoint is not None: |
| reward_head_path = resume_checkpoint / "reward_head.pt" |
| legacy_pairwise_head_path = resume_checkpoint / "pairwise_head.pt" |
| if reward_head_path.exists(): |
| pairwise_head.load_state_dict(torch.load(reward_head_path, map_location="cpu")) |
| elif legacy_pairwise_head_path.exists(): |
| raise RuntimeError( |
| "Found legacy pairwise_head.pt in resume checkpoint, but pairwise_rm now expects reward_head.pt " |
| "with a scalar reward head. Re-train pairwise_rm from evaluator_sft or resume from a new-format checkpoint." |
| ) |
| else: |
| raise FileNotFoundError( |
| f"reward_head.pt not found in resume checkpoint: {resume_checkpoint}" |
| ) |
| pairwise_head.train() |
| pairwise_criterion = "bradley_terry_pairwise_logistic" |
| optimizer = torch.optim.AdamW(list(model.parameters()) + list(pairwise_head.parameters()), lr=args.lr) |
| elif canonical_stage == "evaluator_regression": |
| hidden_size = getattr(getattr(model, "config", None), "hidden_size", None) |
| if hidden_size is None: |
| hidden_size = getattr(getattr(model, "config", None), "text_config", None) |
| hidden_size = getattr(hidden_size, "hidden_size", None) |
| if hidden_size is None: |
| raise RuntimeError("Unable to infer hidden_size for evaluator regression head.") |
| evaluator_head = nn.Linear(int(hidden_size), 8) |
| if torch.cuda.is_available(): |
| evaluator_head = evaluator_head.to("cuda") |
| if resume_checkpoint is not None: |
| evaluator_head_path = resume_checkpoint / "evaluator_head.pt" |
| if not evaluator_head_path.exists(): |
| raise FileNotFoundError(f"evaluator_head.pt not found in resume checkpoint: {resume_checkpoint}") |
| evaluator_head.load_state_dict(torch.load(evaluator_head_path, map_location="cpu")) |
| evaluator_head.train() |
| regression_criterion = nn.MSELoss() |
| optimizer = torch.optim.AdamW(list(evaluator_head.parameters()), lr=args.lr) |
|
|
| if resume_checkpoint is not None and optimizer is not None: |
| optimizer_state_path = resume_checkpoint / "optimizer.pt" |
| if not optimizer_state_path.exists(): |
| raise FileNotFoundError(f"optimizer.pt not found in resume checkpoint: {resume_checkpoint}") |
| optimizer.load_state_dict(torch.load(optimizer_state_path, map_location="cpu")) |
| _optimizer_to_device(optimizer, next(model.parameters()).device) |
|
|
| if resume_state: |
| global_step = int(resume_state.get("global_step", 0) or 0) |
| completed_epochs = int(resume_state.get("completed_epochs", 0) or 0) |
| start_epoch = max(1, int(resume_state.get("next_epoch", 1) or 1)) |
| start_row_index = max(0, int(resume_state.get("next_row_index", 0) or 0)) |
| if start_row_index >= len(train_rows): |
| start_epoch += 1 |
| start_row_index = 0 |
|
|
| if start_epoch > args.epochs: |
| status = { |
| "stage": stage, |
| "status": "completed", |
| "message": "resume checkpoint already reached or exceeded requested epochs", |
| "model_path": model_path, |
| "train_count": len(train_rows), |
| "val_count": len(val_rows), |
| "epochs": args.epochs, |
| "batch_size": 1, |
| "lr": args.lr, |
| "checkpoint_dir": str(resume_checkpoint) if resume_checkpoint is not None else str(checkpoint_dir), |
| "metrics_path": str(metrics_path), |
| "frames_per_video": args.frames_per_video, |
| "max_train_steps": args.max_train_steps, |
| "global_step": global_step, |
| "completed_epochs": completed_epochs, |
| "resume_from": str(resume_checkpoint) if resume_checkpoint is not None else "", |
| "init_from": str(init_checkpoint) if init_checkpoint is not None else "", |
| "init_from_stage": init_stage, |
| } |
| real_sft_status_path.write_text(json.dumps(status, ensure_ascii=False, indent=2), encoding="utf-8") |
| return status |
|
|
| def _write_running_status( |
| *, |
| latest_dir: Path | None, |
| epoch: int, |
| row_index: int, |
| completed_epoch_count: int, |
| status: str = "running", |
| ) -> None: |
| payload = { |
| "stage": stage, |
| "status": status, |
| "model_path": model_path, |
| "train_count": len(train_rows), |
| "val_count": len(val_rows), |
| "epochs": args.epochs, |
| "batch_size": 1, |
| "lr": args.lr, |
| "checkpoint_dir": str(checkpoint_dir), |
| "checkpoint_root_dir": str(checkpoints_root), |
| "latest_checkpoint_dir": str(latest_dir) if latest_dir is not None else "", |
| "metrics_path": str(metrics_path), |
| "frames_per_video": args.frames_per_video, |
| "max_train_steps": args.max_train_steps, |
| "global_step": global_step, |
| "current_epoch": epoch, |
| "next_row_index": row_index, |
| "completed_epochs": completed_epoch_count, |
| "resume_from": str(resume_checkpoint) if resume_checkpoint is not None else "", |
| "init_from": str(init_checkpoint) if init_checkpoint is not None else "", |
| "init_from_stage": init_stage, |
| } |
| real_sft_status_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") |
|
|
| def _save_checkpoint( |
| *, |
| save_dir: Path, |
| next_epoch: int, |
| next_row_index: int, |
| completed_epoch_count: int, |
| reason: str, |
| include_processor: bool, |
| ) -> None: |
| save_dir.mkdir(parents=True, exist_ok=True) |
| checkpoints_root.mkdir(parents=True, exist_ok=True) |
| (save_dir / "base_model_path.txt").write_text(str(model_path), encoding="utf-8") |
| if include_processor: |
| processor.save_pretrained(save_dir) |
| if canonical_stage != "evaluator_regression": |
| model.save_pretrained(save_dir) |
| if pairwise_head is not None: |
| torch.save(pairwise_head.state_dict(), save_dir / "reward_head.pt") |
| (save_dir / "reward_head_config.json").write_text( |
| json.dumps( |
| { |
| "loss": "bradley_terry_pairwise_logistic", |
| "output": "scalar_reward", |
| }, |
| ensure_ascii=False, |
| indent=2, |
| ), |
| encoding="utf-8", |
| ) |
| if evaluator_head is not None: |
| torch.save(evaluator_head.state_dict(), save_dir / "evaluator_head.pt") |
| (save_dir / "evaluator_head_config.json").write_text( |
| json.dumps( |
| { |
| "score_names": [ |
| "prompt_alignment", |
| "structure_preservation", |
| "transformation_strength", |
| "carrier_grounding", |
| "world_realization", |
| "temporal_coherence", |
| "artifact_penalty", |
| "overall_score", |
| ] |
| }, |
| ensure_ascii=False, |
| indent=2, |
| ), |
| encoding="utf-8", |
| ) |
| if optimizer is not None: |
| torch.save(optimizer.state_dict(), save_dir / "optimizer.pt") |
| trainer_state = { |
| "stage": stage, |
| "model_path": model_path, |
| "global_step": global_step, |
| "completed_epochs": completed_epoch_count, |
| "next_epoch": next_epoch, |
| "next_row_index": next_row_index, |
| "train_count": len(train_rows), |
| "val_count": len(val_rows), |
| "reason": reason, |
| "frames_per_video": args.frames_per_video, |
| "max_train_steps": args.max_train_steps, |
| **_init_metadata( |
| init_checkpoint=init_checkpoint, |
| init_state=init_state, |
| ), |
| } |
| (save_dir / "trainer_state.json").write_text( |
| json.dumps(trainer_state, ensure_ascii=False, indent=2), |
| encoding="utf-8", |
| ) |
| latest_checkpoint_path.write_text(str(save_dir), encoding="utf-8") |
| _write_running_status( |
| latest_dir=save_dir, |
| epoch=min(next_epoch, args.epochs), |
| row_index=next_row_index, |
| completed_epoch_count=completed_epoch_count, |
| ) |
| print( |
| f"[checkpoint] reason={reason} step={global_step} saved={save_dir} " |
| f"next_epoch={next_epoch} next_row_index={next_row_index}", |
| flush=True, |
| ) |
|
|
| _write_running_status( |
| latest_dir=resume_checkpoint, |
| epoch=start_epoch, |
| row_index=start_row_index, |
| completed_epoch_count=completed_epochs, |
| ) |
|
|
| train_limit = args.max_train_steps if args.max_train_steps > 0 else None |
| last_next_epoch = start_epoch |
| last_next_row_index = start_row_index |
| terminated_early = False |
| interval_loss_sum = 0.0 |
| interval_steps = 0 |
| interval_start_time = time.time() |
| run_start_time = time.time() |
| run_steps_completed = 0 |
| total_planned_steps = len(train_rows) * max(args.epochs - start_epoch + 1, 0) |
| if start_row_index > 0 and total_planned_steps > 0: |
| total_planned_steps -= start_row_index |
| for epoch in range(start_epoch, args.epochs + 1): |
| epoch_loss = 0.0 |
| epoch_steps = 0 |
| epoch_row_start = start_row_index if epoch == start_epoch else 0 |
| reached_train_limit = False |
| for row_index in range(epoch_row_start, len(train_rows)): |
| row = train_rows[row_index] |
| device = next(model.parameters()).device |
|
|
| optimizer.zero_grad() |
| if canonical_stage == "pairwise_rm": |
| candidate_scores: dict[str, torch.Tensor] = {} |
| for candidate_key in ("a", "b"): |
| image_paths = _extract_pairwise_candidate_frames( |
| row, |
| candidate_key=candidate_key, |
| frames_per_video=args.frames_per_video, |
| ) |
| messages = _build_pairwise_reward_messages( |
| stage, |
| row, |
| candidate_key=candidate_key, |
| image_paths=image_paths, |
| ) |
| text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) |
| image_inputs, video_inputs = process_vision_info(messages) |
| model_inputs = processor( |
| text=[text], |
| images=image_inputs, |
| videos=video_inputs, |
| padding=True, |
| return_tensors="pt", |
| ) |
| model_inputs = model_inputs.to(device) |
| outputs = model(**model_inputs, output_hidden_states=True) |
| hidden = outputs.hidden_states[-1] |
| last_token_index = model_inputs["attention_mask"].sum(dim=1) - 1 |
| pooled = hidden[torch.arange(hidden.shape[0], device=device), last_token_index] |
| pooled = _match_head_input_dtype(pooled, pairwise_head) |
| candidate_scores[candidate_key] = pairwise_head(pooled).view(-1) |
| score_a = candidate_scores["a"] |
| score_b = candidate_scores["b"] |
| winner = str(row.get("winner", "a") or "a").strip().lower() |
| if winner == "a": |
| margin = score_a - score_b |
| elif winner == "b": |
| margin = score_b - score_a |
| else: |
| raise ValueError(f"Unsupported pairwise winner label: {winner}") |
| loss = -F.logsigmoid(margin).mean() |
| elif canonical_stage == "evaluator_regression": |
| image_paths = _extract_training_frames(row, args.frames_per_video) |
| messages = _build_evaluator_regression_messages(row, image_paths) |
| text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) |
| image_inputs, video_inputs = process_vision_info(messages) |
| model_inputs = processor( |
| text=[text], |
| images=image_inputs, |
| videos=video_inputs, |
| padding=True, |
| return_tensors="pt", |
| ) |
| model_inputs = model_inputs.to(device) |
| with torch.inference_mode(): |
| outputs = model(**model_inputs, output_hidden_states=True) |
| hidden = outputs.hidden_states[-1] |
| last_token_index = model_inputs["attention_mask"].sum(dim=1) - 1 |
| pooled = hidden[torch.arange(hidden.shape[0], device=device), last_token_index] |
| pooled = _match_head_input_dtype(pooled, evaluator_head) |
| preds = evaluator_head(pooled) |
| scores = row.get("teacher_scores", {}) or {} |
| target = torch.tensor( |
| [[ |
| float(scores.get("prompt_alignment", 0.0) or 0.0), |
| float(scores.get("structure_preservation", 0.0) or 0.0), |
| float(scores.get("transformation_strength", 0.0) or 0.0), |
| float(scores.get("carrier_grounding", 0.0) or 0.0), |
| float(scores.get("world_realization", 0.0) or 0.0), |
| float(scores.get("temporal_coherence", 0.0) or 0.0), |
| float(scores.get("artifact_penalty", 0.0) or 0.0), |
| float(scores.get("overall_score", 0.0) or 0.0), |
| ]], |
| dtype=torch.float32, |
| device=device, |
| ) |
| loss = regression_criterion(preds, target) |
| else: |
| scores = row.get("teacher_scores", {}) or {} |
| if canonical_stage == "evaluator_sft" and _is_aesthetic_score_schema(scores): |
| image_paths = _extract_aesthetic_training_frames(row, args.frames_per_video) |
| else: |
| image_paths = _extract_training_frames( |
| row, |
| args.frames_per_video, |
| include_high=canonical_stage != "evaluator_sft", |
| ) |
| messages, _ = _build_multimodal_messages(stage, row, image_paths) |
| prompt_messages = messages[:-1] |
| full_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) |
| prompt_text = processor.apply_chat_template(prompt_messages, tokenize=False, add_generation_prompt=True) |
| image_inputs, video_inputs = process_vision_info(prompt_messages) |
| full_inputs = processor( |
| text=[full_text], |
| images=image_inputs, |
| videos=video_inputs, |
| padding=True, |
| return_tensors="pt", |
| ) |
| prompt_inputs = processor( |
| text=[prompt_text], |
| images=image_inputs, |
| videos=video_inputs, |
| padding=True, |
| return_tensors="pt", |
| ) |
| full_inputs = full_inputs.to(device) |
| prompt_inputs = prompt_inputs.to(device) |
| labels = full_inputs["input_ids"].clone() |
| prompt_len = prompt_inputs["input_ids"].shape[1] |
| labels[:, :prompt_len] = -100 |
| full_inputs["labels"] = labels |
| outputs = model(**full_inputs) |
| loss = outputs.loss |
| loss.backward() |
| optimizer.step() |
|
|
| global_step += 1 |
| run_steps_completed += 1 |
| epoch_steps += 1 |
| loss_value = float(loss.item()) |
| epoch_loss += loss_value |
| interval_loss_sum += loss_value |
| interval_steps += 1 |
| if summary_writer is not None: |
| summary_writer.add_scalar("train/loss_step", loss_value, global_step) |
|
|
| next_epoch = epoch |
| next_row_index = row_index + 1 |
| completed_epoch_count = epoch - 1 |
| if next_row_index >= len(train_rows): |
| next_epoch = epoch + 1 |
| next_row_index = 0 |
| completed_epoch_count = epoch |
| last_next_epoch = next_epoch |
| last_next_row_index = next_row_index |
|
|
| if args.save_every_steps > 0 and global_step % args.save_every_steps == 0: |
| _save_checkpoint( |
| save_dir=checkpoints_root / f"step_{global_step:08d}", |
| next_epoch=next_epoch, |
| next_row_index=next_row_index, |
| completed_epoch_count=completed_epoch_count, |
| reason="step", |
| include_processor=False, |
| ) |
|
|
| if args.log_every_steps > 0 and global_step % args.log_every_steps == 0: |
| interval_elapsed = max(time.time() - interval_start_time, 1e-6) |
| avg_interval_loss = interval_loss_sum / max(interval_steps, 1) |
| seconds_per_step = interval_elapsed / max(interval_steps, 1) |
| total_elapsed = max(time.time() - run_start_time, 1e-6) |
| average_seconds_per_step = total_elapsed / max(run_steps_completed, 1) |
| remaining_steps = max(total_planned_steps - run_steps_completed, 0) |
| if train_limit is not None: |
| remaining_steps = min(remaining_steps, max(train_limit - global_step, 0)) |
| eta_seconds = remaining_steps * average_seconds_per_step |
| eta_done_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() + eta_seconds)) |
| print( |
| ( |
| f"[train] epoch={epoch}/{args.epochs} step={global_step} " |
| f"row={row_index + 1}/{len(train_rows)} " |
| f"loss={loss_value:.6f} avg_loss={avg_interval_loss:.6f} " |
| f"{seconds_per_step:.2f}s/step " |
| f"eta={_format_duration(eta_seconds)} " |
| f"done_at={eta_done_at}" |
| ), |
| flush=True, |
| ) |
| if summary_writer is not None: |
| summary_writer.add_scalar("train/loss_interval_avg", avg_interval_loss, global_step) |
| summary_writer.add_scalar("train/seconds_per_step", seconds_per_step, global_step) |
| summary_writer.add_scalar("train/eta_seconds", eta_seconds, global_step) |
| interval_loss_sum = 0.0 |
| interval_steps = 0 |
| interval_start_time = time.time() |
|
|
| if train_limit is not None and global_step >= train_limit: |
| reached_train_limit = True |
| break |
|
|
| avg_train_loss = epoch_loss / max(epoch_steps, 1) |
| with metrics_path.open("a", encoding="utf-8") as f: |
| f.write( |
| json.dumps( |
| {"epoch": epoch, "train_loss": avg_train_loss, "global_step": global_step}, |
| ensure_ascii=False, |
| ) |
| + "\n" |
| ) |
| print( |
| f"[epoch] epoch={epoch}/{args.epochs} global_step={global_step} train_loss={avg_train_loss:.6f}", |
| flush=True, |
| ) |
| if summary_writer is not None: |
| summary_writer.add_scalar("train/epoch_loss", avg_train_loss, epoch) |
|
|
| if reached_train_limit: |
| terminated_early = True |
| completed_epochs = epoch if row_index + 1 >= len(train_rows) else epoch - 1 |
| last_next_epoch = epoch if row_index + 1 < len(train_rows) else epoch + 1 |
| last_next_row_index = 0 if row_index + 1 >= len(train_rows) else row_index + 1 |
| _save_checkpoint( |
| save_dir=checkpoints_root / f"step_{global_step:08d}", |
| next_epoch=last_next_epoch, |
| next_row_index=last_next_row_index, |
| completed_epoch_count=completed_epochs, |
| reason="train_limit", |
| include_processor=False, |
| ) |
| break |
|
|
| completed_epochs = epoch |
| last_next_epoch = epoch + 1 |
| last_next_row_index = 0 |
| _save_checkpoint( |
| save_dir=checkpoints_root / f"epoch_{epoch:04d}", |
| next_epoch=last_next_epoch, |
| next_row_index=last_next_row_index, |
| completed_epoch_count=completed_epochs, |
| reason="epoch", |
| include_processor=True, |
| ) |
|
|
| completed_epochs = min(completed_epochs, args.epochs) |
| _save_checkpoint( |
| save_dir=checkpoint_dir, |
| next_epoch=last_next_epoch if terminated_early else args.epochs + 1, |
| next_row_index=last_next_row_index if terminated_early else 0, |
| completed_epoch_count=completed_epochs, |
| reason="final", |
| include_processor=True, |
| ) |
|
|
| status = { |
| "stage": stage, |
| "status": "completed", |
| "model_path": model_path, |
| "train_count": len(train_rows), |
| "val_count": len(val_rows), |
| "epochs": args.epochs, |
| "batch_size": 1, |
| "lr": args.lr, |
| "checkpoint_dir": str(checkpoint_dir), |
| "checkpoint_root_dir": str(checkpoints_root), |
| "latest_checkpoint_path": str(latest_checkpoint_path), |
| "metrics_path": str(metrics_path), |
| "frames_per_video": args.frames_per_video, |
| "max_train_steps": args.max_train_steps, |
| "global_step": global_step, |
| "completed_epochs": completed_epochs, |
| "resume_from": str(resume_checkpoint) if resume_checkpoint is not None else "", |
| "init_from": str(init_checkpoint) if init_checkpoint is not None else "", |
| "init_from_stage": init_stage, |
| "save_every_steps": args.save_every_steps, |
| } |
| if canonical_stage == "pairwise_rm": |
| deploy_target = PROJECT_ROOT / "models" / "critic" / "pairwise" |
| deploy_command = f"ln -sfn '{checkpoint_dir}' '{deploy_target}'" |
| status["deploy_recommendation"] = { |
| "purpose": "Use the pairwise-sharpened critic as the runtime evaluator.", |
| "target_path": str(deploy_target), |
| "checkpoint_path": str(checkpoint_dir), |
| "symlink_command": deploy_command, |
| } |
| real_sft_status_path.write_text(json.dumps(status, ensure_ascii=False, indent=2), encoding="utf-8") |
| if real_sft_error_path.exists(): |
| real_sft_error_path.unlink() |
| if canonical_stage == "pairwise_rm": |
| deploy = status["deploy_recommendation"] |
| print( |
| ( |
| f"[deploy] pairwise_rm finished. Point runtime evaluator to the sharpened critic:\n" |
| f"[deploy] {deploy['symlink_command']}" |
| ), |
| flush=True, |
| ) |
| print( |
| f"[done] stage={stage} global_step={global_step} completed_epochs={completed_epochs} checkpoint={checkpoint_dir}", |
| flush=True, |
| ) |
| return status |
| except Exception as exc: |
| error_payload = { |
| "stage": stage, |
| "status": "failed", |
| "error_type": type(exc).__name__, |
| "error": str(exc), |
| "metrics_path": str(metrics_path), |
| "checkpoint_dir": str(checkpoint_dir), |
| "checkpoint_root_dir": str(checkpoints_root), |
| "global_step": global_step, |
| "completed_epochs": completed_epochs, |
| "resume_from": str(resume_checkpoint) if resume_checkpoint is not None else "", |
| "init_from": str(init_checkpoint) if init_checkpoint is not None else "", |
| "init_from_stage": init_stage, |
| } |
| real_sft_error_path.write_text(json.dumps(error_payload, ensure_ascii=False, indent=2), encoding="utf-8") |
| real_sft_status_path.write_text(json.dumps(error_payload, ensure_ascii=False, indent=2), encoding="utf-8") |
| raise |
| finally: |
| if summary_writer is not None: |
| summary_writer.close() |
|
|
|
|
| def _hash_features(text: str, *, dims: int = 8) -> list[float]: |
| digest = hashlib.sha256(text.encode("utf-8")).digest() |
| return [digest[i] / 255.0 for i in range(dims)] |
|
|
|
|
| def _common_features(row: dict) -> list[float]: |
| prompt = str(row.get("prompt", "") or "") |
| normalized_prompt = str(row.get("normalized_prompt", "") or "") |
| compiled_prompt = str(row.get("compiled_edit_prompt", "") or "") |
| joined = " || ".join( |
| [ |
| prompt, |
| normalized_prompt, |
| compiled_prompt, |
| str(row.get("low_video_path", "") or ""), |
| str(row.get("edited_video_path", "") or ""), |
| str(row.get("high_video_path", "") or ""), |
| ] |
| ) |
| return [ |
| min(len(prompt) / 500.0, 1.0), |
| min(len(normalized_prompt) / 500.0, 1.0), |
| min(len(compiled_prompt) / 1000.0, 1.0), |
| float(bool(row.get("scene_archetype"))), |
| float(bool(row.get("style_family"))), |
| ] + _hash_features(joined, dims=8) |
|
|
|
|
| def _implicit_memory_features(row: dict) -> list[float]: |
| history = row.get("history_window", []) or [] |
| teacher = row.get("teacher_explicit_memory", {}) or {} |
| routing = str(row.get("routing_target", "") or "") |
| routing_flags = [ |
| 1.0 if routing == "accept" else 0.0, |
| 1.0 if routing == "local_refine_prompt" else 0.0, |
| 1.0 if routing == "global_replan" else 0.0, |
| ] |
| return [ |
| min(len(history) / 4.0, 1.0), |
| min(len((teacher.get("failure_patterns", []) if isinstance(teacher, dict) else [])) / 6.0, 1.0), |
| min(len((teacher.get("custom_skill_records", []) if isinstance(teacher, dict) else [])) / 6.0, 1.0), |
| min(len((teacher.get("prompt_compilation_recipe_candidates", []) if isinstance(teacher, dict) else [])) / 4.0, 1.0), |
| min(len((row.get("local_negative_teacher", {}) or {}).get("failure_tags", []) or []) / 6.0, 1.0), |
| min(len((row.get("global_positive_teacher", {}) or {}).get("strategies", []) or []) / 4.0, 1.0), |
| ] + routing_flags |
|
|
|
|
| def _build_smoke_tensors(stage: str, rows: list[dict]) -> tuple[torch.Tensor, torch.Tensor]: |
| canonical = _canonical_stage(stage) |
| if canonical == "evaluator_sft": |
| feature_rows = [] |
| target_rows = [] |
| for row in rows: |
| features = _common_features(row) |
| if _is_implicit_stage(stage): |
| features += _implicit_memory_features(row) |
| feature_rows.append(features) |
| scores = row.get("teacher_scores", {}) or {} |
| target_rows.append( |
| [ |
| float(scores.get("prompt_alignment", 0.0) or 0.0), |
| float(scores.get("structure_preservation", 0.0) or 0.0), |
| float(scores.get("transformation_strength", 0.0) or 0.0), |
| float(scores.get("carrier_grounding", 0.0) or 0.0), |
| float(scores.get("world_realization", 0.0) or 0.0), |
| float(scores.get("temporal_coherence", 0.0) or 0.0), |
| float(scores.get("artifact_penalty", 0.0) or 0.0), |
| float(scores.get("overall_score", 0.0) or 0.0), |
| ] |
| ) |
| return torch.tensor(feature_rows, dtype=torch.float32), torch.tensor(target_rows, dtype=torch.float32) |
|
|
| if canonical == "reflection_sft": |
| action_to_id = {"accept": 0, "local_refine_prompt": 1, "global_replan": 2} |
| feature_rows = [] |
| target_rows = [] |
| for row in rows: |
| scores = row.get("teacher_scores", {}) or {} |
| features = _common_features(row) + [ |
| float(scores.get("overall_score", 0.0) or 0.0), |
| float(scores.get("prompt_alignment", 0.0) or 0.0), |
| float(scores.get("world_realization", 0.0) or 0.0), |
| float(len(row.get("failure_tags", []) or [])), |
| ] |
| if _is_implicit_stage(stage): |
| features += _implicit_memory_features(row) |
| feature_rows.append(features) |
| target_rows.append(action_to_id[str(row.get("teacher_reflection_action", "global_replan"))]) |
| return torch.tensor(feature_rows, dtype=torch.float32), torch.tensor(target_rows, dtype=torch.long) |
|
|
| if canonical == "pairwise_rm": |
| feature_rows = [] |
| target_rows = [] |
| for row in rows: |
| prompt = str(row.get("prompt", "") or "") |
| a_scores = row.get("candidate_a_scores", {}) or {} |
| b_scores = row.get("candidate_b_scores", {}) or {} |
| joined = " || ".join( |
| [ |
| prompt, |
| str(row.get("candidate_a_video_path", "") or ""), |
| str(row.get("candidate_b_video_path", "") or ""), |
| ] |
| ) |
| feature_rows.append( |
| [ |
| min(len(prompt) / 500.0, 1.0), |
| float(a_scores.get("overall_score", 0.0) or 0.0), |
| float(b_scores.get("overall_score", 0.0) or 0.0), |
| float(a_scores.get("world_realization", 0.0) or 0.0), |
| float(b_scores.get("world_realization", 0.0) or 0.0), |
| ] |
| + _hash_features(joined, dims=8) |
| + (_implicit_memory_features(row) if _is_implicit_stage(stage) else []) |
| ) |
| target_rows.append(1.0 if str(row.get("winner", "a")) == "a" else -1.0) |
| return torch.tensor(feature_rows, dtype=torch.float32), torch.tensor(target_rows, dtype=torch.float32) |
|
|
| return torch.zeros((0, 1), dtype=torch.float32), torch.zeros((0,), dtype=torch.float32) |
|
|
|
|
| def _run_smoke_training( |
| *, |
| stage: str, |
| train_rows: list[dict], |
| val_rows: list[dict], |
| output_dir: Path, |
| epochs: int, |
| batch_size: int, |
| lr: float, |
| ) -> dict: |
| train_x, train_y = _build_smoke_tensors(stage, train_rows) |
| val_x, val_y = _build_smoke_tensors(stage, val_rows) |
| canonical = _canonical_stage(stage) |
|
|
| if train_x.numel() == 0: |
| status = { |
| "stage": stage, |
| "status": "skipped", |
| "reason": "no_train_samples", |
| "train_count": len(train_rows), |
| "val_count": len(val_rows), |
| } |
| (output_dir / "smoke_status.json").write_text(json.dumps(status, ensure_ascii=False, indent=2), encoding="utf-8") |
| return status |
|
|
| input_dim = train_x.shape[1] |
| if canonical == "evaluator_sft": |
| output_dim = train_y.shape[1] |
| model = nn.Sequential(nn.Linear(input_dim, 32), nn.ReLU(), nn.Linear(32, output_dim)) |
| criterion = nn.MSELoss() |
| elif canonical == "pairwise_rm": |
| model = nn.Sequential(nn.Linear(input_dim, 32), nn.ReLU(), nn.Linear(32, 1)) |
| criterion = None |
| else: |
| num_classes = 3 if canonical == "reflection_sft" else 2 |
| model = nn.Sequential(nn.Linear(input_dim, 32), nn.ReLU(), nn.Linear(32, num_classes)) |
| criterion = nn.CrossEntropyLoss() |
|
|
| optimizer = torch.optim.Adam(model.parameters(), lr=lr) |
| train_loader = DataLoader(TensorDataset(train_x, train_y), batch_size=min(batch_size, len(train_rows)), shuffle=True) |
| metrics_path = output_dir / "smoke_metrics.jsonl" |
| metrics_path.write_text("", encoding="utf-8") |
|
|
| for epoch in range(1, epochs + 1): |
| model.train() |
| train_loss_sum = 0.0 |
| train_batches = 0 |
| for batch_x, batch_y in train_loader: |
| optimizer.zero_grad() |
| pred = model(batch_x) |
| if canonical == "pairwise_rm": |
| reward_margin = pred.view(-1) |
| loss = -F.logsigmoid(batch_y * reward_margin).mean() |
| else: |
| loss = criterion(pred, batch_y) |
| loss.backward() |
| optimizer.step() |
| train_loss_sum += float(loss.item()) |
| train_batches += 1 |
|
|
| train_loss = train_loss_sum / max(train_batches, 1) |
| val_loss = None |
| if val_x.numel() > 0: |
| model.eval() |
| with torch.no_grad(): |
| val_pred = model(val_x) |
| if canonical == "pairwise_rm": |
| val_loss = float((-F.logsigmoid(val_y * val_pred.view(-1)).mean()).item()) |
| else: |
| val_loss = float(criterion(val_pred, val_y).item()) |
|
|
| with metrics_path.open("a", encoding="utf-8") as f: |
| f.write( |
| json.dumps( |
| { |
| "epoch": epoch, |
| "train_loss": train_loss, |
| "val_loss": val_loss, |
| }, |
| ensure_ascii=False, |
| ) |
| + "\n" |
| ) |
|
|
| checkpoint_path = output_dir / "smoke_checkpoint.pt" |
| torch.save({"stage": stage, "model_state_dict": model.state_dict()}, checkpoint_path) |
| status = { |
| "stage": stage, |
| "status": "completed", |
| "train_count": len(train_rows), |
| "val_count": len(val_rows), |
| "epochs": epochs, |
| "batch_size": batch_size, |
| "lr": lr, |
| "checkpoint_path": str(checkpoint_path), |
| "metrics_path": str(metrics_path), |
| } |
| (output_dir / "smoke_status.json").write_text(json.dumps(status, ensure_ascii=False, indent=2), encoding="utf-8") |
| return status |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| dataset_path = _resolve_stage_dataset_path(args.dataset, args.stage) |
| rows = _load_rows(dataset_path, args.max_samples) |
| stage_rows = _materialize_stage_records(args.stage, rows) |
| train_rows, val_rows = _split_rows(stage_rows) |
|
|
| args.output_dir.mkdir(parents=True, exist_ok=True) |
| datasets_dir = args.output_dir / "datasets" |
| train_path = datasets_dir / "train.jsonl" |
| val_path = datasets_dir / "val.jsonl" |
| _write_jsonl(train_path, train_rows) |
| _write_jsonl(val_path, val_rows) |
|
|
| train_config = _stage_training_config(args, len(stage_rows)) |
| train_config["materialized_stage_dataset"] = { |
| "train_path": str(train_path), |
| "val_path": str(val_path), |
| "train_count": len(train_rows), |
| "val_count": len(val_rows), |
| } |
| train_config["checkpoint_flow"] = { |
| "resume_from": str(args.resume_from or ""), |
| "init_from_checkpoint": str(args.init_from_checkpoint or ""), |
| } |
| plan = { |
| "stage": args.stage, |
| "base_model": args.base_model, |
| "raw_sample_count": len(rows), |
| "sample_count": len(stage_rows), |
| "dataset": str(args.dataset), |
| "resolved_dataset_path": str(dataset_path), |
| "resume_from": str(args.resume_from or ""), |
| "init_from_checkpoint": str(args.init_from_checkpoint or ""), |
| "objective": _stage_objective(args.stage), |
| "required_labels": train_config["required_labels"], |
| "config_path": str(args.output_dir / "train_config.json"), |
| "train_dataset_path": str(train_path), |
| "val_dataset_path": str(val_path), |
| "next_step": "replace this stub with actual critic fine-tuning / reward-model training entrypoint", |
| } |
| (args.output_dir / "train_config.json").write_text( |
| json.dumps(train_config, ensure_ascii=False, indent=2), |
| encoding="utf-8", |
| ) |
| (args.output_dir / "train_plan.json").write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8") |
| if args.run_smoke: |
| smoke_status = _run_smoke_training( |
| stage=args.stage, |
| train_rows=train_rows, |
| val_rows=val_rows, |
| output_dir=args.output_dir, |
| epochs=args.epochs, |
| batch_size=args.batch_size, |
| lr=args.lr, |
| ) |
| plan["smoke_status_path"] = str(args.output_dir / "smoke_status.json") |
| plan["smoke_status"] = smoke_status.get("status", "") |
| (args.output_dir / "train_plan.json").write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8") |
| if args.run_real_sft: |
| real_sft_status = _run_real_sft( |
| args=args, |
| stage=args.stage, |
| train_rows=train_rows, |
| val_rows=val_rows, |
| output_dir=args.output_dir, |
| ) |
| plan["real_sft_status_path"] = str(args.output_dir / "real_sft_status.json") |
| plan["real_sft_status"] = real_sft_status.get("status", "") |
| (args.output_dir / "train_plan.json").write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8") |
| print(json.dumps(plan, ensure_ascii=False, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|