Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (6)
- inference.py+139-117
- openenv.yaml+9-9
- server/graders.py+98-22
- server/reward_utils.pyAdded+67
- server/video_encode_environment.py+75-56
- video_analysis.py+6-2
69 unmodified lines70717273747534 unmodified lines1101111121131141155 unmodified lines121122123124125126127128129130131147 unmodified lines279280281282283284285286287288289290291292293294295296297298299300301302163 unmodified lines46646746846947047147244 unmodified lines5175185195205215225235245255265279 unmodified lines53753853954054154254311 unmodified lines55555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458511 unmodified lines59759859960060160260360460567 unmodified lines67367467567667767867968068168268368468568668768868969069169211 unmodified lines7047057067077087097107117127137147157167178 unmodified lines72672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679725 unmodified lines82382482582682782882969 unmodified linesimport subprocessimport sysimport textwrapfrom typing import Any, List, Optionalfrom openai import OpenAI34 unmodified lines)SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.85"))# Normalize score: assume typical |reward| per step ≤ this for rough [0,1] scaling_MAX_REWARD_ABS_PER_STEP = float(os.getenv("VIDEO_ENCODE_SCORE_MAX_ABS_REWARD_PER_STEP", "3.0"))5 unmodified lines_WS_MESSAGE_TIMEOUT_SEC = float(os.getenv("VIDEO_ENCODE_WS_MESSAGE_TIMEOUT_SEC", "600"))_PRINT_USER_PROMPT = os.getenv("VIDEO_ENCODE_PRINT_USER_PROMPT", "1").strip().lower() not in ("0","false","no",)class ExtendedReadyLocalDockerProvider(LocalDockerProvider):147 unmodified linesrepo_id: Optional[str],) -> None:"""Log where the Video Encode RL server is reached (HF Space URL, repo, local, or Docker)."""if docker_image:# print(f"[ENV] mode=docker_image image={docker_image}", flush=True)passelif repo_id:# print(f"[ENV] mode=hf_repo repo_id={repo_id} (OpenEnv from_env)", flush=True)passelif base_url:# print(f"[ENV] mode=http url={base_url}", flush=True)passelse:# print("[ENV] mode=unknown", flush=True)passdef log_user_prompt(step: int, user_prompt: str) -> None:if not _PRINT_USER_PROMPT:return# print(f"[USER_PROMPT] step={step}\n{user_prompt}\n", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:163 unmodified lines"""if message is None:return "", ""#print(f"[DEBUG] Model message: {message!r}", flush=True)# 1) content (string or part list)c = _normalize_assistant_text_field(getattr(message, "content", None))if c:44 unmodified linesresponse_format={"type": "json_object"},)except Exception as exc:# print(# f"[DEBUG] response_format json_object failed ({exc!r}); retrying without it",# flush=True,# )passreturn client.chat.completions.create(**kwargs)9 unmodified linesuser_prompt = build_user_prompt(step, observation_dict, last_reward, history, max_tokens=MAX_TOKENS)#log_user_prompt(step, user_prompt)try:completion = _chat_completion_create(client,11 unmodified linestext, text_source = _completion_message_text(msg)text = text.strip()fr = getattr(choice, "finish_reason", None)# print(# f"[DEBUG] Assistant text: source={text_source!r} chars={len(text)} finish_reason={fr!r}",# flush=True,# )if not text:raise ValueError("empty assistant message: no text in content, reasoning, or other known fields")# if fr == "length":# print(# "[DEBUG] Stopped at max_tokens — JSON may be truncated. Increase MAX_TOKENS or shorten JSON.",# flush=True,# )# if len(text) > 500:# print(f"[DEBUG] Model text (head): {text}...", flush=True)# else:# print(f"[DEBUG] Model text: {text!r}", flush=True)return parse_model_output_to_action(text, num_videos, task_id)except Exception as exc:# print(f"[DEBUG] Model request or parse failed: {exc}", flush=True)# print(# "[DEBUG] Using fallback action: crf=23, preset=medium, video_index=0 "# "(or null when no videos). Fix MODEL_NAME/API_BASE_URL/HF_TOKEN or model output.",# flush=True,# )return fallback_action(num_videos)11 unmodified linesnh = h.replace("_", "-")new_netloc = p.netloc.replace(h, nh, 1)out = urlunparse(p._replace(netloc=new_netloc)).rstrip("/")if out != u.rstrip("/"):pass# print(f"[DEBUG] Normalized HF Space URL (use hyphens, not underscores): {u!r} -> {out!r}", flush=True)return out67 unmodified linesdef _observation_error(obs: Any) -> Optional[str]:md = getattr(obs, "metadata", None) or {}if isinstance(md, dict) and md.get("error"):return str(md["error"])return Noneasync def run_inference(args: argparse.Namespace) -> None:if not API_KEY:# print(# "Warning: Set HF_TOKEN (or OPENAI_API_KEY) to your Hugging Face token for "# "google/flan-t5-small on router.huggingface.co — requests may fail without it.",# file=sys.stderr,# )pass# HF router accepts Bearer token; placeholder only for local smoke without network.client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY or "hf")11 unmodified linesfrom_env_ready = 600.0env: VideoEncodeEnv | None = Nonemax_steps = max(0, args.max_steps)rewards: List[float] = []steps_taken = 0score = 0.0success = Falsehistory: List[str] = []log_start(task=TASK_NAME, env_name=BENCHMARK, model=MODEL_NAME)log_env_endpoint(docker_image, base_url, repo_id)try:8 unmodified linesobs = result.observationlast_reward = float(result.reward or 0.0)episode_policy = {"easy": [0.0,0.5],"medium": [0.5,0.8],"hard": [0.8,1.0]}for step in range(1, max_steps + 1):percent_idx = step / (max_steps+1)task_id = "easy"for task, pc in episode_policy.items():if pc[0] <= percent_idx <= pc[1]:task_id = taskbreakif getattr(result, "done", False):breakobs_dict = obs.model_dump()# print(obs_dict)action = get_model_action(client,step,obs_dict,last_reward,history,obs.num_videos,task_id)action_str = _action_to_log_str(action)result = await env.step(action)obs = result.observationreward = float(result.reward if result.reward is not None else 0.00001)done = bool(result.done)err = _observation_error(obs)rewards.append(reward)steps_taken = steplast_reward = rewardlog_step(step=step, action=action_str, reward=reward, done=done, error=err)history.append(_history_line(step, action, reward))if done:breakmean_r = sum(rewards) / len(rewards)# Map roughly into [0,1] using typical scale (tunable via env)score = abs(mean_r)score = min(max(score, 0.0), 1.0)success = Trueexcept Exception as e:# print(f"[DEBUG] inference loop error: {e}", flush=True)success = Falsefinally:if env is not None:try:await env.close()except Exception as e:pass# print(f"[DEBUG] env.close() error: {e}", flush=True)log_end(success=success, steps=steps_taken, score=score, rewards=rewards)def main() -> int:25 unmodified linestry:asyncio.run(run_inference(args))except ValueError as e:# print(f"Error: {e}", file=sys.stderr)return 2return 069 unmodified lines70717273747576777834 unmodified lines1131141151161171181191201215 unmodified lines127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159147 unmodified lines307308309310311312313314315316317318319320321322323324325326327328163 unmodified lines49249349449549649749849944 unmodified lines5445455465475485495505519 unmodified lines56156256356456556656711 unmodified lines57958058158258358458558658758858959059159259359459559659759859960060160260360460560611 unmodified lines61861962062162262362462567 unmodified lines69369469569669769869970070170270370470570670770870971071111 unmodified lines7237247257267277287297308 unmodified lines73974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781825 unmodified lines84484584684784884985085169 unmodified linesimport subprocessimport sysimport textwrapfrom pathlib import Pathimport yamlfrom typing import Any, List, Optionalfrom openai import OpenAI34 unmodified lines)SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.85"))# Set INFERENCE_DEBUG=1 to print observations, model replies, and other debug info to stdout.DEBUG = os.getenv("INFERENCE_DEBUG", "0").strip().lower() not in ("0", "false", "no")# Normalize score: assume typical |reward| per step ≤ this for rough [0,1] scaling_MAX_REWARD_ABS_PER_STEP = float(os.getenv("VIDEO_ENCODE_SCORE_MAX_ABS_REWARD_PER_STEP", "3.0"))5 unmodified lines_WS_MESSAGE_TIMEOUT_SEC = float(os.getenv("VIDEO_ENCODE_WS_MESSAGE_TIMEOUT_SEC", "600"))_PRINT_USER_PROMPT = False# Number of segment loops to run (each loop = one full pass over all tasks = steps_per_segment steps)NUM_SEGMENT_LOOPS = int(os.getenv("VIDEO_ENCODE_NUM_SEGMENT_LOOPS", "2"))# Path to openenv.yaml (resolved relative to this file's directory)_OPENENV_YAML = Path(__file__).parent / "openenv.yaml"def _load_tasks() -> list[dict]:"""Parse tasks from openenv.yaml; each entry has 'difficulty' and 'max_steps'."""try:with open(_OPENENV_YAML) as f:data = yaml.safe_load(f)tasks = data.get("tasks", [])# Filter to entries that have both required fieldsreturn [t for t in tasks if "difficulty" in t and "max_steps" in t]except Exception as exc:if DEBUG:print(f"[DEBUG] Could not load {_OPENENV_YAML}: {exc}", flush=True)# Fallback: one hard task with MAX_STEPS stepsreturn [{"difficulty": "hard", "max_steps": MAX_STEPS}]# _PRINT_USER_PROMPT = os.getenv("VIDEO_ENCODE_PRINT_USER_PROMPT", "1").strip().lower() not in (# "0",# "false",# "no",# )class ExtendedReadyLocalDockerProvider(LocalDockerProvider):147 unmodified linesrepo_id: Optional[str],) -> None:"""Log where the Video Encode RL server is reached (HF Space URL, repo, local, or Docker)."""if not DEBUG:returnif docker_image:print(f"[ENV] mode=docker_image image={docker_image}", flush=True)elif repo_id:print(f"[ENV] mode=hf_repo repo_id={repo_id} (OpenEnv from_env)", flush=True)elif base_url:print(f"[ENV] mode=http url={base_url}", flush=True)else:print("[ENV] mode=unknown", flush=True)def log_user_prompt(step: int, user_prompt: str) -> None:if not DEBUG or not _PRINT_USER_PROMPT:returnprint(f"[USER_PROMPT] step={step}\n{user_prompt}\n", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:163 unmodified lines"""if message is None:return "", ""if DEBUG:print(f"[DEBUG] Model message: {message!r}", flush=True)# 1) content (string or part list)c = _normalize_assistant_text_field(getattr(message, "content", None))if c:44 unmodified linesresponse_format={"type": "json_object"},)except Exception as exc:if DEBUG:print(f"[DEBUG] response_format json_object failed ({exc!r}); retrying without it", flush=True)return client.chat.completions.create(**kwargs)9 unmodified linesuser_prompt = build_user_prompt(step, observation_dict, last_reward, history, max_tokens=MAX_TOKENS)log_user_prompt(step, user_prompt)try:completion = _chat_completion_create(client,11 unmodified linestext, text_source = _completion_message_text(msg)text = text.strip()fr = getattr(choice, "finish_reason", None)# if DEBUG:# print(f"[DEBUG] Assistant text: source={text_source!r} chars={len(text)} finish_reason={fr!r}", flush=True)if not text:raise ValueError("empty assistant message: no text in content, reasoning, or other known fields")if DEBUG:if fr == "length":print("[DEBUG] Stopped at max_tokens — JSON may be truncated. Increase MAX_TOKENS or shorten JSON.", flush=True)# if len(text) > 500:# print(f"[DEBUG] Model text (head): {text[:500]}...", flush=True)# else:# print(f"[DEBUG] Model text: {text!r}", flush=True)return parse_model_output_to_action(text, num_videos, task_id)except Exception as exc:if DEBUG:print(f"[DEBUG] Model request or parse failed: {exc}", flush=True)print("[DEBUG] Using fallback action: crf=23, preset=medium, video_index=0 ""(or null when no videos). Fix MODEL_NAME/API_BASE_URL/HF_TOKEN or model output.",flush=True,)return fallback_action(num_videos)11 unmodified linesnh = h.replace("_", "-")new_netloc = p.netloc.replace(h, nh, 1)out = urlunparse(p._replace(netloc=new_netloc)).rstrip("/")if DEBUG and out != u.rstrip("/"):print(f"[DEBUG] Normalized HF Space URL (use hyphens, not underscores): {u!r} -> {out!r}", flush=True)return out67 unmodified linesdef _observation_error(obs: Any) -> Optional[str]:msg = getattr(obs, "echoed_message", None) or ""if msg and msg != "ok":return msgreturn Noneasync def run_inference(args: argparse.Namespace) -> None:if not API_KEY and DEBUG:print("Warning: Set HF_TOKEN (or OPENAI_API_KEY) to your Hugging Face token for ""the model on router.huggingface.co — requests may fail without it.",file=sys.stderr,)# HF router accepts Bearer token; placeholder only for local smoke without network.client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY or "hf")11 unmodified linesfrom_env_ready = 600.0env: VideoEncodeEnv | None = Nonehistory: List[str] = []log_env_endpoint(docker_image, base_url, repo_id)try:8 unmodified linesobs = result.observationlast_reward = float(result.reward or 0.0)tasks = _load_tasks()global_step = 0done = Falsefor _seg in range(NUM_SEGMENT_LOOPS):if done:breakfor task in tasks:if done:breaktask_id: str = task["difficulty"]task_name: str = task.get("id", task_id)task_rewards: List[float] = []task_step = 0task_success = Falselog_start(task=task_name, env_name=BENCHMARK, model=MODEL_NAME)try:for _ in range(task["max_steps"]):global_step += 1task_step += 1if getattr(result, "done", False):done = Truebreakobs_dict = obs.model_dump()if DEBUG:print(f"[DEBUG] Observation: {json.dumps(obs_dict, indent=2, default=str)}", flush=True)action = get_model_action(client,global_step,obs_dict,last_reward,history,obs.num_videos,task_id,)action_str = _action_to_log_str(action)result = await env.step(action)obs = result.observationreward = float(result.reward if result.reward is not None else 0.00001)done = bool(result.done)err = _observation_error(obs)task_rewards.append(reward)last_reward = rewardlog_step(step=task_step, action=action_str, reward=reward, done=done, error=err)history.append(_history_line(global_step, action, reward))if done:breaktask_success = Trueexcept Exception as task_exc:if DEBUG:print(f"[DEBUG] task {task_name} error: {task_exc}", flush=True)task_score = min(max(abs(sum(task_rewards) / len(task_rewards)), 0.0), 1.0) if task_rewards else 0.0log_end(success=task_success, steps=task_step, score=task_score, rewards=task_rewards)except Exception as e:if DEBUG:print(f"[DEBUG] inference loop error: {e}", flush=True)finally:if env is not None:try:await env.close()except Exception as e:if DEBUG:print(f"[DEBUG] env.close() error: {e}", flush=True)def main() -> int:25 unmodified linestry:asyncio.run(run_inference(args))except ValueError as e:if DEBUG:print(f"Error: {e}", file=sys.stderr)return 2return 0
8 unmodified lines91011121314151617181920212223242526272829308 unmodified linestasks:- id: task_easydifficulty: easymax_steps: 10grader:type: llmprompt_template: "Score this response 0.0 to 1.0 based on accuracy..."- id: task_mediumdifficulty: mediummax_steps: 15grader:type: llmprompt_template: "Score this response 0.0 to 1.0 based on..."- id: task_harddifficulty: hardmax_steps: 20grader:type: llmprompt_template: "Score this response 0.0 to 1.0 based on..."8 unmodified lines91011121314151617181920212223242526272829308 unmodified linestasks:- id: task_easydifficulty: easymax_steps: 3grader:type: functiongrader_name: grader_easy- id: task_mediumdifficulty: mediummax_steps: 3grader:type: functiongrader_name: grader_easy- id: task_harddifficulty: hardmax_steps: 4grader:type: functiongrader_name: grader_hard
9 unmodified lines10111213141516171819202122232425262728293031323334353637383940414243444546474849505152535413 unmodified lines6869709 unmodified linesEach returns a score in [0, 1] based on a single step's measurable outcomes.These are verifiable, Markovian signals suitable for use as shaped training rewards.easy_step_score — structural validity: encode success + minimum watchable qualitymedium_step_score — rate-distortion efficiency: quality-per-bit tradeoff"""from __future__ import annotationsdef easy_step_score(vmaf: float | None,encoding_time_sec: float | None,segment_duration_sec: float,encode_aborted: bool,*,vmaf_floor: float = 45.0,time_budget_multiplier: float = 2.0,) -> float:"""Score in [0, 1] for structural validity of one encode step.Deductions (result clipped to [0, 1]):encode_aborted or vmaf is None → −0.5 (encode did not complete)vmaf < vmaf_floor → −0.3 (video is unwatchable)enc_time > multiplier × seg_len → −0.2 (encode far too slow)"""score = 1.0if encode_aborted or vmaf is None:score -= 0.5elif vmaf < vmaf_floor:score -= 0.3if (encoding_time_sec is not Noneand segment_duration_sec > 0and encoding_time_sec > time_budget_multiplier * segment_duration_sec):score -= 0.2return max(0.0, min(1.0, score))def medium_step_score(vmaf: float | None,bitrate_kbps: float | None,*,13 unmodified linesq = max(0.0, min(1.0, vmaf / vmaf_max))s = max(0.0, min(1.0, bitrate_kbps / bitrate_cap_kbps))return q * (1.0 - s)9 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585913 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451469 unmodified linesEach returns a score in [0, 1] based on a single step's measurable outcomes.These are verifiable, Markovian signals suitable for use as shaped training rewards.grader_easy — structural validity: encode success + minimum watchable qualitygrader_medium — rate-distortion efficiency: quality-per-bit tradeoffgrader_hard — full quality-time-bitrate reward (R = λ_Q·Q̄ − λ_T·T̄ − λ_S·S̄ − λ_C·C̄)"""from __future__ import annotationsfrom typing import Anydef grader_easy(vmaf: float | None,encoding_time_sec: float | None,segment_duration_sec: float,encode_aborted: bool,*,vmaf_floor: float = 45.0,vmaf_target: float = 93.0,time_budget_multiplier: float = 2.0,) -> float:"""Score in [0, 1] for watchability of one encode step.- encode_aborted or vmaf is None → 0.0 (hard fail)- otherwise: 0.5 × quality_term + 0.5 × speed_termquality_term = clip((vmaf - vmaf_floor) / (vmaf_target - vmaf_floor), 0, 1)speed_term = 1.0 if enc_time ≤ budget, else decays linearly to 0 at 3× budget"""if encode_aborted or vmaf is None:return 0.0quality = max(0.0, min(1.0, (vmaf - vmaf_floor) / max(vmaf_target - vmaf_floor, 1.0)))if encoding_time_sec is None or segment_duration_sec <= 0:speed = 1.0else:budget = time_budget_multiplier * segment_duration_secif encoding_time_sec <= budget:speed = 1.0else:# linear decay: 1.0 at budget, 0.0 at 3× budgetspeed = max(0.0, 1.0 - (encoding_time_sec - budget) / (budget * 2.0))return 0.5 * quality + 0.5 * speeddef grader_medium(vmaf: float | None,bitrate_kbps: float | None,*,13 unmodified linesq = max(0.0, min(1.0, vmaf / vmaf_max))s = max(0.0, min(1.0, bitrate_kbps / bitrate_cap_kbps))return q * (1.0 - s)def grader_hard(*,vmaf: float | None,ssim: float | None,encoding_time_sec: float,bitrate_kbps: float,lambda_q: float,lambda_t: float,lambda_s: float,crf: int = 0,prev_crf_avg: float | None = None,lambda_c: float = 0.0,crf_instability_relative_threshold: float = 0.5,vmaf_max: float = 100.0,time_max_sec: float = 60.0,bitrate_max_kbps: float = 20_000.0,) -> tuple[float, dict[str, Any]]:"""Return (reward, components) where components holds normalized terms for logging.R = λ_Q · Q̄ − λ_T · T̄ − λ_S · S̄ − λ_C · C̄"""try:from .reward_utils import (normalized_bitrate,normalized_crf_instability,normalized_encode_time,normalized_quality,)except ImportError:from server.reward_utils import (normalized_bitrate,normalized_crf_instability,normalized_encode_time,normalized_quality,)q_bar = normalized_quality(vmaf, ssim, vmaf_max=vmaf_max)t_bar = normalized_encode_time(encoding_time_sec, time_max_sec=time_max_sec)s_bar = normalized_bitrate(bitrate_kbps, bitrate_max_kbps=bitrate_max_kbps)c_bar = normalized_crf_instability(crf,prev_crf_avg,relative_threshold=crf_instability_relative_threshold,)reward = (lambda_q * q_bar- lambda_t * t_bar- lambda_s * s_bar- lambda_c * c_bar)return reward, {"q_bar": q_bar,"t_bar": t_bar,"s_bar": s_bar,"c_bar": c_bar,"lambda_q": lambda_q,"lambda_t": lambda_t,"lambda_s": lambda_s,"lambda_c": lambda_c,"term_q": lambda_q * q_bar,"term_t": -lambda_t * t_bar,"term_s": -lambda_s * s_bar,"term_c": -lambda_c * c_bar,"prev_crf_avg": prev_crf_avg,"crf_instability_relative_threshold": crf_instability_relative_threshold,}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Normalisation helpers used by grader_hard (server/graders.py).
Q̄: quality in [0, 1] from VMAF (÷ VMAF_MAX) or SSIM when VMAF is missing T̄: encode time in [0, 1] via min(time / TIME_MAX, 1) S̄: bitrate cost in [0, 1] via min(bitrate_kbps / BITRATE_MAX, 1) C̄: CRF instability vs previous segment mean crf_avg"""
from __future__ import annotations
def _clip01(x: float) -> float: return max(0.0, min(1.0, x))
def normalized_quality( vmaf: float | None, ssim: float | None, *, vmaf_max: float = 100.0,) -> float: """Map VMAF or SSIM to [0, 1]. Prefer VMAF when present.""" if vmaf is not None and vmaf_max > 0: return _clip01(vmaf / vmaf_max) if ssim is not None: return _clip01(ssim) return 0.0
def normalized_encode_time(encoding_time_sec: float, *, time_max_sec: float) -> float: if time_max_sec <= 0: return 0.0 return _clip01(encoding_time_sec / time_max_sec)
def normalized_bitrate(bitrate_kbps: float, *, bitrate_max_kbps: float) -> float: """Bitrate cost term S̄ (higher bitrate → higher penalty weight).""" if bitrate_max_kbps <= 0: return 0.0 return _clip01(bitrate_kbps / bitrate_max_kbps)
def normalized_crf_instability( crf: int, prev_crf_avg: float | None, *, relative_threshold: float = 0.5,) -> float: """ Penalty term C̄ in [0, 1] when current CRF differs from the previous segment's mean CRF by more than ``relative_threshold`` (relative, e.g. 0.5 = 50%). """ if prev_crf_avg is None or prev_crf_avg <= 0: return 0.0 rel_dev = abs(float(crf) - prev_crf_avg) / prev_crf_avg if rel_dev <= relative_threshold: return 0.0 # map excess in (0, ...] to (0, 1]; cap at 1 excess = rel_dev - relative_threshold return min(1.0, excess / max(1e-9, 1.0 - relative_threshold))50 unmodified lines51525354555657583 unmodified lines6263646566676869707172733 unmodified lines77787980818283100 unmodified lines18418518618718818922 unmodified lines2122132142152162174 unmodified lines22222322422522622768 unmodified lines29629729829930030130212 unmodified lines31531631731831932032128 unmodified lines35035135235335435535615 unmodified lines37237337437537637737818 unmodified lines39739839940040140240318 unmodified lines42242342442542642742818 unmodified lines44744844945045145245327 unmodified lines48148248348448548648723 unmodified lines51151251351451551651728 unmodified lines5465475485495505515522 unmodified lines55555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460550 unmodified linestry:from ..models import VideoEncodeAction, VideoEncodeObservationfrom .graders import easy_step_score, medium_step_scorefrom .reward import compute_segment_rewardfrom ..segment_utils import (encode_segment,extract_segment,3 unmodified linesssim_score,vmaf_score,)from ..video_analysis import analyze_segment_clip, load_whole_video_analysis_for_observationfrom ..video_paths import load_video_pathsexcept ImportError:from models import VideoEncodeAction, VideoEncodeObservationfrom server.graders import easy_step_score, medium_step_scorefrom server.reward import compute_segment_rewardfrom segment_utils import (encode_segment,extract_segment,3 unmodified linesssim_score,vmaf_score,)from video_analysis import analyze_segment_clip, load_whole_video_analysis_for_observationfrom video_paths import load_video_pathslogger = logging.getLogger(__name__)100 unmodified lineselse None),)self._segment_duration_sec = float(segment_duration_secif segment_duration_sec is not None22 unmodified linesself._prev_segment_summary: dict[str, Any] | None = Noneself._segment_step_metrics: list[dict[str, Any]] = []def _reload_video_paths_from_disk(self) -> None:"""Rescan ``VIDEO_ENCODE_VIDEOS_DIR`` / list file so runtime uploads are visible."""self._video_paths = load_video_paths(4 unmodified lineselse None),)def _observation(self,68 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.0,)self._current_video_idx = (self._reset_count - 1) % n12 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.0,metadata={"video_path": key, "steps_per_segment": self._steps_per_segment},)28 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.0,)idx = action.video_index if action.video_index is not None else self._current_video_idx15 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.0,)ref_video = self._video_paths[idx]18 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.0,metadata={"error": str(e)},)18 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.0,)prev_for_obs = copy.deepcopy(self._prev_segment_summary)18 unmodified linestry:extract_segment(ref_video, start_sec, seg_len, ref_clip, timeout=to)ew, eh = ffprobe_video_size(ref_clip)seg_analysis = analyze_segment_clip(ref_clip, timeout=to)encode_budget = _encode_time_budget_sec(seg_len, to)try:enc_time = encode_segment(27 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=float(encode_budget),reward=0.0,metadata={"encode_aborted": True,"reason": "encode_timeout_vs_segment",23 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=enc_time,reward=0.0,metadata={"encode_aborted": True,"reason": "encode_slower_than_segment",28 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.0,metadata={"error": str(e)},)2 unmodified linesif self._prev_segment_summary is not Noneelse None)# time_max_sec: use explicit env override if set, otherwise 3× the segment duration# so the T̄ term has meaningful gradient for typical short segments._raw_tmax = os.environ.get("VIDEO_ENCODE_REWARD_TIME_MAX_SEC")time_max_sec = float(_raw_tmax) if _raw_tmax else 3.0 * seg_lenhard_reward, r_components = compute_segment_reward(vmaf=vmaf,ssim=ssim,encoding_time_sec=enc_time,bitrate_kbps=bitrate,lambda_q=self._reward_cfg["lambda_q"],lambda_t=self._reward_cfg["lambda_t"],lambda_s=self._reward_cfg["lambda_s"],lambda_c=self._reward_cfg["lambda_c"],crf=action.crf,prev_crf_avg=prev_crf_avg,vmaf_max=self._reward_cfg["vmaf_max"],time_max_sec=time_max_sec,bitrate_max_kbps=self._reward_cfg["bitrate_max_kbps"],)g_easy = easy_step_score(vmaf=vmaf,encoding_time_sec=enc_time,segment_duration_sec=seg_len,encode_aborted=False,)g_medium = medium_step_score(vmaf=vmaf,bitrate_kbps=bitrate,bitrate_cap_kbps=self._reward_cfg["grader_medium_bitrate_cap_kbps"],vmaf_max=self._reward_cfg["vmaf_max"],)r_components["easy_score"] = g_easyr_components["medium_score"] = g_mediumr_components["task_id"] = action.task_idif action.task_id == "easy":reward = g_easyelif action.task_id == "medium":reward = g_mediumelse: # "hard"reward = hard_rewardif reward <= 0.0:reward = 0.0001if reward == 1.0:reward = 0.9999logger.debug("step: reward=%s components=%s", reward, r_components)self._segment_step_metrics.append(50 unmodified lines515253545556573 unmodified lines616263646566676869707172737475763 unmodified lines808182838485868788899091100 unmodified lines19219319419519619719822 unmodified lines2212222232242252262272282292302312322332342352362372382394 unmodified lines24424524624724824925068 unmodified lines31932032132232332432512 unmodified lines33833934034134234334428 unmodified lines37337437537637737837915 unmodified lines39539639739839940040118 unmodified lines42042142242342442542618 unmodified lines44544644744844945045118 unmodified lines47047147247347447547627 unmodified lines50450550650750850951023 unmodified lines53453553653753853954028 unmodified lines5695705715725735745752 unmodified lines57857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362450 unmodified linestry:from ..models import VideoEncodeAction, VideoEncodeObservationfrom .graders import grader_easy, grader_hard, grader_mediumfrom ..segment_utils import (encode_segment,extract_segment,3 unmodified linesssim_score,vmaf_score,)from ..video_analysis import (analyze_segment_clip,analyze_video,load_whole_video_analysis_for_observation,store_whole_video_analysis,)from ..video_paths import load_video_pathsexcept ImportError:from models import VideoEncodeAction, VideoEncodeObservationfrom server.graders import grader_easy, grader_hard, grader_mediumfrom segment_utils import (encode_segment,extract_segment,3 unmodified linesssim_score,vmaf_score,)from video_analysis import (analyze_segment_clip,analyze_video,load_whole_video_analysis_for_observation,store_whole_video_analysis,)from video_paths import load_video_pathslogger = logging.getLogger(__name__)100 unmodified lineselse None),)self._analyze_new_videos()self._segment_duration_sec = float(segment_duration_secif segment_duration_sec is not None22 unmodified linesself._prev_segment_summary: dict[str, Any] | None = Noneself._segment_step_metrics: list[dict[str, Any]] = []def _analyze_new_videos(self) -> None:"""Run ``analyze_video`` on any path not yet in the in-process cache."""timeout = float(os.environ.get("VIDEO_ENCODE_UPLOAD_ANALYSIS_TIMEOUT_SEC", "600"))for path in self._video_paths:if load_whole_video_analysis_for_observation(path):continue # already cachedtry:analysis = analyze_video(path, complexity_timeout_sec=timeout)store_whole_video_analysis(path, analysis)logger.debug("Analyzed video for observation cache: %s", path.name)except Exception as exc: # noqa: BLE001logger.warning("Could not analyze %s: %s", path.name, exc)def _reload_video_paths_from_disk(self) -> None:"""Rescan ``VIDEO_ENCODE_VIDEOS_DIR`` / list file so runtime uploads are visible."""self._video_paths = load_video_paths(4 unmodified lineselse None),)self._analyze_new_videos()def _observation(self,68 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.01,)self._current_video_idx = (self._reset_count - 1) % n12 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.01,metadata={"video_path": key, "steps_per_segment": self._steps_per_segment},)28 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.01,)idx = action.video_index if action.video_index is not None else self._current_video_idx15 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.01,)ref_video = self._video_paths[idx]18 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.01,metadata={"error": str(e)},)18 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.01,)prev_for_obs = copy.deepcopy(self._prev_segment_summary)18 unmodified linestry:extract_segment(ref_video, start_sec, seg_len, ref_clip, timeout=to)ew, eh = ffprobe_video_size(ref_clip)seg_analysis = {}encode_budget = _encode_time_budget_sec(seg_len, to)try:enc_time = encode_segment(27 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=float(encode_budget),reward=0.01,metadata={"encode_aborted": True,"reason": "encode_timeout_vs_segment",23 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=enc_time,reward=0.01,metadata={"encode_aborted": True,"reason": "encode_slower_than_segment",28 unmodified linesssim_score=None,bitrate_kbps=None,encoding_time_sec=None,reward=0.01,metadata={"error": str(e)},)2 unmodified linesif self._prev_segment_summary is not Noneelse None)r_components: dict[str, Any] = {"task_id": action.task_id}if action.task_id == "easy":reward = grader_easy(vmaf=vmaf,encoding_time_sec=enc_time,segment_duration_sec=seg_len,encode_aborted=False,)elif action.task_id == "medium":reward = grader_medium(vmaf=vmaf,bitrate_kbps=bitrate,bitrate_cap_kbps=self._reward_cfg["grader_medium_bitrate_cap_kbps"],vmaf_max=self._reward_cfg["vmaf_max"],)else: # "hard"# time_max_sec: use explicit env override if set, otherwise 3× the segment duration# so the T̄ term has meaningful gradient for typical short segments._raw_tmax = os.environ.get("VIDEO_ENCODE_REWARD_TIME_MAX_SEC")time_max_sec = float(_raw_tmax) if _raw_tmax else 3.0 * seg_lenreward, r_components = grader_hard(vmaf=vmaf,ssim=ssim,encoding_time_sec=enc_time,bitrate_kbps=bitrate,lambda_q=self._reward_cfg["lambda_q"],lambda_t=self._reward_cfg["lambda_t"],lambda_s=self._reward_cfg["lambda_s"],lambda_c=self._reward_cfg["lambda_c"],crf=action.crf,prev_crf_avg=prev_crf_avg,vmaf_max=self._reward_cfg["vmaf_max"],time_max_sec=time_max_sec,bitrate_max_kbps=self._reward_cfg["bitrate_max_kbps"],)r_components["task_id"] = action.task_idif reward <= 0.0:reward = 0.01if reward >= 1.0:reward = 0.99logger.debug("step: reward=%s components=%s", reward, r_components)self._segment_step_metrics.append(
374 unmodified lines3753763773783793803818 unmodified lines390391392393394395396374 unmodified linesexcept RuntimeError:out["duration_sec"] = Noneout["fps"] = ffprobe_avg_frame_rate(path)try:out["bitrate_kbps"] = ffprobe_bitrate_kbps(path)8 unmodified linesif compute_complexity:# Cap the per-segment complexity pass at 30 s regardless of the global timeout.# A well-extracted 3 s clip typically finishes well under 5 s.complexity_timeout = min(30.0, float(timeout)) if timeout is not None else 30.0try:metrics = _run_ffmpeg_luma_complexity_metrics(path,374 unmodified lines3753763773783793803813823833848 unmodified lines393394395396397398399400374 unmodified linesexcept RuntimeError:out["duration_sec"] = Nonetry:out["fps"] = ffprobe_avg_frame_rate(path)except Exception:out["fps"] = Nonetry:out["bitrate_kbps"] = ffprobe_bitrate_kbps(path)8 unmodified linesif compute_complexity:# Cap the per-segment complexity pass at 30 s regardless of the global timeout.# A well-extracted 3 s clip typically finishes well under 5 s.# complexity_timeout = min(30.0, float(timeout)) if timeout is not None else 30.0complexity_timeout = 600try:metrics = _run_ffmpeg_luma_complexity_metrics(path,
inference.py+139-117
openenv.yaml+9-9
server/graders.py+98-22
server/reward_utils.pyAdded+67
server/video_encode_environment.py+75-56
video_analysis.py+6-2