Distilled_handvqa / code /build_sft_data.py
Joshkn's picture
Add 750 distilled HanDyVQA training samples and provenance
0a24277 verified
Raw History Blame Contribute Delete
9.42 kB
#!/usr/bin/env python3
"""Build the supplied script's four-round, five-field SFT schema for HanDyVQA.
Input: build_input.jsonl emitted by distill_handyvqa.py. Explicit stage paths
replace the supplied script's machine-specific /u -> /work/nvme path rewriting.
Tool targets use seeded, task-aware templates or the legacy fixed texts. The final
target is the actual Stage 3 response. No anomaly/severity labels are fabricated.
Stage 2 observations omit tracking-frame indices, second timestamps, change
types and local object indices. Source-frame indices and descriptions remain unchanged.
"""
import argparse
from pathlib import Path
from task_data import atomic_text, dumps, file_hash, loads, no_private, read, unwrap, validate
from task_prompts import SYSTEM_PROMPT, instruction
from sft_templates import DEFAULT_SEED, add_template_arguments, template_metadata, tool_reasons
def stage_path(row, key, base):
value = row.get(key)
if not isinstance(value, str) or not value:
raise ValueError(f"Missing {key}. Use build_input.jsonl from the distillation runner")
path = Path(value)
return path if path.is_absolute() else base / path
def load_bundle(row, base):
for key in ("question", "video_path"):
if not isinstance(row.get(key), str) or not row[key].strip():
raise ValueError(f"Missing {key}")
options = row.get("options")
if not isinstance(options, list) or len(options) < 2 or any(not isinstance(s, str) or not s.strip() for s in options):
raise ValueError("Expected at least two answer options")
video = Path(row["video_path"])
video = video if video.is_absolute() else base / video
if not video.is_file():
raise ValueError(f"Video does not exist: {video}")
objects = read(stage_path(row, "obj_path", base))
first = read(stage_path(row, "stage1_path", base))
second = read(stage_path(row, "stage2_path", base))
report = read(stage_path(row, "report_path", base))
if not isinstance(objects, list) or not objects or any(not isinstance(s, str) or not s.strip() for s in objects):
raise ValueError("obj.json must contain a nonempty list of object names")
if first.get("recognized_objects") != objects:
raise ValueError("obj.json and Stage 1 disagree")
validate(first["grounding"], "grounding")
validate(second["structured_state"], "state")
final = {key: report[key] for key in ("report", "answer", "confidence")}
validate(final, "report", len(options))
if report.get("video_sha256") != file_hash(video):
raise ValueError("The source video changed after distillation")
if not isinstance(report.get("run_signature"), str) or not report["run_signature"]:
raise ValueError("The report has no run signature")
threshold = report.get("min_confidence")
if type(threshold) not in (int, float) or not 0 <= threshold <= 1:
raise ValueError("Invalid minimum confidence in the report")
if (report.get("status") != "accepted" or report.get("question_id") != row.get("question_id")
or report.get("question") != row["question"] or report.get("options") != options
or Path(report.get("video_path", "")).resolve() != video.resolve()):
raise ValueError("The report is not an accepted result for this question and video")
if (first.get("question_id") != row.get("question_id")
or second.get("question_id") != row.get("question_id")
or first.get("run_signature") != report.get("run_signature")
or second.get("run_signature") != report.get("run_signature")):
raise ValueError("The stage files belong to different samples or runs")
if (report.get("caption") != first.get("caption")
or report.get("grounding") != first["grounding"]
or report.get("structured_state") != second["structured_state"]
or report.get("state_changes") != second.get("state_changes")
or report.get("identified_events") != second.get("identified_events")):
raise ValueError("The stage files and flat report disagree")
if not isinstance(first.get("caption"), str) or not first["caption"].strip():
raise ValueError("Stage 1 has no caption")
if type(first.get("recommended_fps")) is not int or not 2 <= first["recommended_fps"] <= 10:
raise ValueError("Stage 1 has an invalid FPS")
if type(first.get("num_recognition_frames")) is not int or first["num_recognition_frames"] < 1:
raise ValueError("Stage 1 has an invalid recognition frame count")
for key in ("state_changes", "identified_events"):
if not isinstance(second.get(key), list):
raise ValueError(f"Stage 2 has no {key} list")
if loads(unwrap(report["final_response"])) != final:
raise ValueError("The final VLM response and parsed report disagree")
if report.get("system") != SYSTEM_PROMPT:
raise ValueError("The report uses a different system prompt")
accepted = row.get("answer_idx")
if (not isinstance(accepted, list) or not accepted
or any(type(i) is not int or not 0 <= i < len(options) for i in accepted)):
raise ValueError("Invalid accepted answer indices in the manifest")
if report["answer"] not in accepted:
raise ValueError("The final answer does not match accepted answer indices")
if report["confidence"] < report["min_confidence"]:
raise ValueError("The final confidence is below the acceptance threshold")
return video.resolve(), objects, first, second, report
def stage2_observation(second):
"""Create an export-only view without changing the validated stage records."""
omitted = {"start_frame", "end_frame", "start_time_seconds", "end_time_seconds",
"change_type", "object_idx"}
def clean(value):
if isinstance(value, dict):
return {key: clean(item) for key, item in value.items() if key not in omitted}
if isinstance(value, list):
return [clean(item) for item in value]
return value
return {key: clean(second[key]) for key in ("state_changes", "identified_events", "structured_state")}
def make_samples(row, base, *, template_mode="varied", seed=DEFAULT_SEED):
reasons = tool_reasons(row, template_mode=template_mode, seed=seed)
video, objects, first, second, report = load_bundle(row, base)
def tool(reason, name, arguments):
return f"<think>{reason}</think> <tool>\n{dumps({'name': name, 'arguments': arguments}, indent=2)}\n</tool>"
targets = [
tool(reasons[0], "recog",
{"num_scan_frames": first["num_recognition_frames"]}),
tool(reasons[1], "caption", {"objects": objects}),
tool(reasons[2], "track",
{"fps": first["recommended_fps"]}),
report["final_response"],
]
observations = [objects, {"caption": first["caption"], "grounding": first["grounding"]},
stage2_observation(second)]
history, samples = [], []
for index, output in enumerate(targets):
sample = {"system": SYSTEM_PROMPT, "instruction": instruction(row), "input": str(video),
"history": list(history), "output": output}
no_private(dumps(sample))
samples.append(sample)
if index < 3:
history.append([output, "<information>" + dumps(observations[index]) + "</information>"])
return samples
def create_multi_round_dataset(input_jsonl, output_jsonl, *, template_mode="varied", seed=DEFAULT_SEED):
templates = template_metadata(template_mode, seed)
source, target = Path(input_jsonl).resolve(), Path(output_jsonl).resolve()
if source == target:
raise ValueError("Input and output paths must differ")
if target.exists():
raise FileExistsError(f"Output already exists: {target}. Choose a new output path")
samples, seen, excluded = [], set(), 0
for number, line in enumerate(source.read_text(encoding="utf-8").splitlines(), 1):
if not line.strip():
continue
try:
row = loads(line)
if row.get("split") != "train" or row.get("status") != "accepted":
excluded += 1
continue
question_id = row.get("question_id")
if not question_id or question_id in seen:
raise ValueError("Missing or duplicate question_id")
samples.extend(make_samples(row, source.parent, template_mode=template_mode, seed=seed))
seen.add(question_id)
except (ValueError, KeyError, TypeError, OSError) as exc:
raise ValueError(f"Input line {number}: {exc}") from exc
if not samples:
raise ValueError("No accepted training samples. No output file was written")
atomic_text(target, "".join(dumps(sample) + "\n" for sample in samples))
return {"videos": len(seen), "sft_samples": len(samples), "excluded": excluded, "output": str(target), **templates}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-i", "--input_path", required=True)
parser.add_argument("-o", "--output_path", required=True)
add_template_arguments(parser)
args = parser.parse_args()
print(dumps(create_multi_round_dataset(args.input_path, args.output_path,
template_mode=args.template_mode, seed=args.seed), indent=2))