Upload folder using huggingface_hub (part 2)
Browse filesFiles changed (9)
- questions/answer_vocab.jsonAdded+48
- questions/questions_train.json
- questions/questions_val.json
- questions/taxonomy.json+263-134
- scripts/crosscheck_answers.pyAdded+129
- scripts/questions_v2.pyAdded+314
- scripts/regenerate_descriptive.pyAdded+207
- scripts/resolution_check.pyAdded+103
- scripts/verify_descriptive.pyAdded+105
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "answer_vocab": [ "0", "1", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "2", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "3", "30", "31", "4", "5", "6", "7", "8", "9", "bob", "jumps", "large", "left", "light", "medium", "no", "right", "small", "smooth", "still", "yes" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137{"question_types": {"descriptive": [{"template": "q_release_side","doc": ""},{"template": "q_bottom_passes","doc": ""},{"template": "q_end_motion","doc": ""},{"template": "q_envelope","doc": ""},{"template": "q_shadow_direction","doc": ""},{"template": "q_light_motion","doc": ""},{"template": "q_energy_shape","doc": ""},{"template": "q_fastest_point","doc": ""}],"explanatory": [{"template": "q_why_decay","doc": ""},{"template": "q_why_stop_top","doc": ""},{"template": "q_shadow_cause","doc": ""},{"template": "q_no_return","doc": ""},{"template": "q_fastest_bottom_why","doc": ""},{"template": "q_beats_cause","doc": ""},{"template": "q_large_angle_slow","doc": ""}],"predictive": [{"template": "q_next_peak","doc": ""},{"template": "q_eventual","doc": ""},{"template": "q_after_direction","doc": ""},{"template": "q_cross_next_second","doc": ""},{"template": "q_shadow_future","doc": ""}],"counterfactual": [{"template": "q_cf_no_damping","doc": ""},{"template": "q_cf_add_damping","doc": ""},{"template": "q_cf_gravity","doc": ""},{"template": "q_cf_rod","doc": ""},{"template": "q_cf_mass","doc": ""},{"template": "q_cf_light","doc": ""},{"template": "q_cf_steeper","doc": ""},{"template": "q_cf_double_damping","doc": ""},{"template": "q_cf_drive_off","doc": ""},{"template": "q_cf_vacuum_quad","doc": ""},{"template": "q_cf_gravity_planet","doc": ""}]},"answer_convention": "descriptive = free-form string; explanatory/predictive/counterfactual = index into choices"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266{"descriptive_style": "CLEVRER-style: open-ended, single-word, family-indexed, sub-typed, answer-balanced","descriptive_families": [{"question_family_index": 6,"question_subtype": "query_amplitude","question_family": "query_mid_amplitude","question_templates": ["How wide is the bob's swing halfway through the video?","Around the middle of the video, how wide is the swing?","How wide is the swing at the midpoint of the video?"],"answers": ["large","medium","small"]},{"question_family_index": 1,"question_subtype": "count","question_family": "count_swing_very_wide","question_templates": ["Count the swings that reach more than 20 degrees in this video.","How many swings in this video are wider than 20 degrees?","How many of the bob's swings in this video exceed 20 degrees?"],"answers": ["0","1","10","12","13","14","2","3","4","5","6","7","8","9"]},{"question_family_index": 7,"question_subtype": "query_direction","question_family": "query_end_direction","question_templates": ["Which way is the bob moving during the final second of the video?","Which way is the bob swinging as the video ends?","In the last second, which direction is the bob travelling?"],"answers": ["left","right","still"]},{"question_family_index": 5,"question_subtype": "query_amplitude","question_family": "query_release_amplitude","question_templates": ["How large is the bob's initial swing?","How wide is the swing the bob starts with?","How wide is the bob's first swing?"],"answers": ["large","medium","small"]},{"question_family_index": 9,"question_subtype": "query_light","question_family": "query_light_travel","question_templates": ["How much does the orange light source move in this video?","How far does the orange light source travel during the video?","Over the video, how large is the light source's sweep?"],"answers": ["large","medium","small"]},{"question_family_index": 4,"question_subtype": "query_direction","question_family": "query_initial_direction","question_templates": ["Which way is the bob moving at the very start of the video?","At the first frame, which direction is the bob travelling?","Which way does the bob set off at the start of the video?"],"answers": ["left","right","still"]},{"question_family_index": 0,"question_subtype": "count","question_family": "count_swing_wide","question_templates": ["Count the swings that reach more than 15 degrees in this video.","How many of the bob's swings in this video exceed 15 degrees?","How many swings in this video are wider than 15 degrees?"],"answers": ["0","1","10","11","12","13","14","2","3","4","5","6","7","8","9"]},{"question_family_index": 3,"question_subtype": "query_side","question_family": "query_release_side","question_templates": ["At the beginning of the video, is the bob on the left or the right?","Which side of the pivot was the bob released from at the start of the video?","Which side of the pivot does the bob start on?"],"answers": ["left","right"]},{"question_family_index": 10,"question_subtype": "query_direction","question_family": "query_light_direction","question_templates": ["At the beginning, which direction is the light source moving?","Which way is the orange light source drifting at the start of the video?","Which way does the light source set off at the start?"],"answers": ["left","right"]},{"question_family_index": 12,"question_subtype": "exist","question_family": "exist_still_swinging","question_templates": ["Is the bob still moving when the video ends?","At the end of the video, is the bob still swinging?","Is the bob still visibly swinging at the end of the video?"],"answers": ["no","yes"]},{"question_family_index": 2,"question_subtype": "count","question_family": "count_turning_points","question_templates": ["How many turning points does the bob reach in this video?","How many times does the bob stop and turn around in this video?","Count the moments when the bob reverses direction in this video."],"answers": ["11","12","13","14","15","16","18","20","21","5","6","8","9"]},{"question_family_index": 8,"question_subtype": "query_position","question_family": "query_end_side","question_templates": ["Which side of the pivot is the bob on in the last frame of the video?","At the end of the video, is the bob on the left or the right?","Which side of the pivot does the bob finish on?"],"answers": ["left","right"]}],"other_question_types": ["explanatory","predictive","counterfactual"],"answer_convention": "descriptive: single-word string from answer_vocab.json; others: index into 'choices'","answer_vocab": ["0","1","10","11","12","13","14","15","16","17","18","19","2","20","21","22","23","24","25","26","27","28","29","3","30","31","4","5","6","7","8","9","bob","jumps","large","left","light","medium","no","right","small","smooth","still","yes"]}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129#!/usr/bin/env python3"""Cross-check emitted descriptive answers against INDEPENDENT ground truth.
python3 crosscheck_answers.py
Deliberately does NOT import questions_v2. It recomputes every answer straightfrom the shipped frame-aligned CSVs using a different peak-detection method(local maxima of |theta| via neighbour comparison, instead of omega signchanges), so agreement is real evidence rather than the same code agreeingwith itself."""from __future__ import annotations
import csvimport jsonimport sysfrom pathlib import Path
import numpy as np
OMEGA_STILL = 0.196
def load(path, hi, lo=0): rows = list(csv.DictReader(open(path))) return {k: np.asarray([float(r[k]) for r in rows], dtype=float) for k in rows[0]}
def turning_points(theta_deg, omega0): """Frames where the bob reverses direction.
Independent of the integrated `omega_rad_s` series used by questions_v2: interior velocities come from finite differences of the angle series. Only the initial velocity is taken from the data (it cannot be differenced - there is no frame before it), which matters because a bob released at max displacement with a small outward velocity turns around *inside the first frame interval* and a pure-difference detector would miss it. """ n = len(theta_deg) v = np.empty(n) v[0] = omega0 v[1:] = np.diff(theta_deg) return np.array([i for i in range(n - 1) if v[i] == 0.0 or v[i] * v[i + 1] < 0.0], dtype=int)
def truth(A, hi, lo=0): th = A["theta_deg"][lo:hi] om = A["omega_rad_s"][lo:hi] lt = A["light_angle_deg"][lo:hi] pk = turning_points(th, float(om[0])) amps = np.maximum(np.abs(th[pk]), np.abs(th[pk + 1])) if len(pk) else np.array([])
def side(d): return "left" if d < 0 else "right"
def band(v, t1, t2): return "small" if v < t1 else ("medium" if v < t2 else "large")
t = {} t["count_swing_wide"] = str(int((amps > 15.0).sum())) t["count_swing_very_wide"] = str(int((amps > 20.0).sum())) t["count_turning_points"] = str(len(pk)) t["query_release_side"] = side(A["theta_deg"][lo]) t["query_initial_direction"] = ("left" if om[0] < -0.01 else "right" if om[0] > 0.01 else "still") t["query_release_amplitude"] = band(abs(A["theta_deg"][lo]), 23.0, 32.0) if len(pk) >= 3: t["query_mid_amplitude"] = band(float(amps[len(pk) // 2]), 8.0, 18.0) win = om[-12:] omax = float(np.max(np.abs(win))) j = int(np.argmax(np.abs(win))) t["query_end_direction"] = ("still" if omax < OMEGA_STILL else "left" if win[j] < 0 else "right") t["query_end_side"] = side(A["theta_deg"][hi - 1]) t["query_light_travel"] = band(float(lt.max() - lt.min()), 10.0, 20.0) t["query_light_direction"] = ("left" if lt[1] < lt[0] else "right") t["exist_still_swinging"] = "yes" if omax >= OMEGA_STILL else "no" return t
def main(): pairs = [("out/questions/questions_train.json", "root_ts/{}.csv", 0, 160), ("out/questions/questions_val.json", "root_ts/{}.csv", 0, 160), ("out/intervened/questions/questions_train.json", "itv_ts/{}.csv", 0, 96)] itv_kind = {r["video_id"]: r["intervention_type"] for r in csv.DictReader(open("intervened/index_intervention.csv"))} ITV_TRUTH = { "light_shift": {"query_intervention_target": "light", "query_intervention_invariant": "bob", "query_energy_at_cut": "smooth"}, "torque_push": {"query_intervention_target": "bob", "query_intervention_invariant": "light", "query_energy_at_cut": "jumps"}, }
n = bad = skipped = 0 for src, tpl, lo, hi in pairs: data = json.load(open(src)) sampled = [v for v in data["scene_annotation"] if Path(tpl.format(v["video_id"])).exists()] for v in sampled: A = load(tpl.format(v["video_id"]), hi, lo) t = dict(truth(A, hi, lo)) if v["video_id"] in itv_kind: t.update(ITV_TRUTH[itv_kind[v["video_id"]]]) for q in v["questions"]: if q["question_type"] != "descriptive": continue fam = q["question_family"] if fam not in t: # gated out for this window skipped += 1 continue n += 1 if str(q["answer"]) != str(t[fam]): bad += 1 if bad <= 10: print(f" MISMATCH {v['video_id']} {fam}: " f"emitted={q['answer']!r} truth={t[fam]!r}")
print(f"\nchecked {n} answers ({skipped} skipped as gated), " f"{bad} mismatches") print("ALL ANSWERS CORRECT" if not bad else f"{bad} WRONG") sys.exit(0 if not bad else 1)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314#!/usr/bin/env python3"""CLEVRER-style descriptive questions (v2).
Replaces the descriptive pool in questions.py. Follows CLEVRER's descriptiveconventions:
* open-ended - never multiple choice, no `choices` field * single word - every answer is one token from a closed vocabulary * sub-typed - `count` / `exist` / `query_*`, like CLEVRER's count / exist / query_color / query_material / query_shape * family id - `question_family_index` + `question_family` per question * balanced - answers are sampled to be near-uniform, so no phrasing has a majority answer that can be guessed without watching
Explanatory / predictive / counterfactual questions are NOT touched here; theregeneration script carries them over verbatim from the shipped files.
Facts are read from the shipped frame-aligned CSVs (or re-simulated fromindex.csv, which is bit-identical), so no video is needed."""from __future__ import annotations
import math
import numpy as np
FPS = 12FRAMES = 160CUT_FRAME = 96 # intervention boundary, t = 8.0 s
# ---------------------------------------------------------------------------# trajectory facts# ---------------------------------------------------------------------------
def _peaks(theta, omega, hi, lo): """Turning-point times/amplitudes (rad) inside frames [lo, hi).
The scan must stop at hi-1: comparing frames (hi-1, hi) would detect a turning point that falls *after* the last frame actually shown in the clip. """ times, amps = [], [] for i in range(lo, max(lo, hi - 1)): if omega[i] == 0.0 or omega[i] * omega[i + 1] < 0: frac = abs(omega[i]) / (abs(omega[i]) + abs(omega[i + 1]) + 1e-12) times.append((i + frac) / FPS) amps.append(max(abs(theta[i]), abs(theta[i + 1]))) return np.array(times), np.array(amps)
def analyze(A, hi=FRAMES, lo=0): """Fact table over frames [lo, hi). `hi < FRAMES` = pre-intervention only.""" th = A["theta_rad"] om = A["omega_rad_s"] en = A["energy_j_per_kg"] lt = A["light_angle_deg"]
f = {} f["window_frames"] = hi - lo f["theta0_deg"] = float(np.degrees(th[lo])) f["omega0"] = float(om[lo])
p_t, p_a = _peaks(th, om, hi, lo) f["n_peaks"] = len(p_a) f["peak_amps_deg"] = np.degrees(p_a) if len(p_a) else np.array([]) f["n_peaks_15"] = int((f["peak_amps_deg"] > 15.0).sum()) f["n_peaks_20"] = int((f["peak_amps_deg"] > 20.0).sum())
if len(p_a) >= 3: mid = len(p_a) // 2 f["mid_amp_deg"] = float(np.degrees(p_a[mid])) f["env_ratio"] = float(p_a[-1] / p_a[0])
last = hi - 1 win = om[max(lo, hi - 12):hi] omax = float(np.max(np.abs(win))) f["last_sec_omega_max"] = omax j = max(lo, hi - 12) + int(np.argmax(np.abs(win))) f["last_sec_sign"] = float(np.sign(om[j])) f["theta_end_deg"] = float(np.degrees(th[last]))
e0, e1 = float(en[lo]), float(en[last]) f["energy_end_ratio"] = e1 / e0 if e0 > 1e-12 else 1.0
# light source f["light_amp_deg"] = float(np.max(lt[lo:hi]) - np.min(lt[lo:hi])) / 2.0 f["light_travel_deg"] = float(np.max(lt[lo:hi]) - np.min(lt[lo:hi])) f["light_dir0"] = float(np.sign(lt[lo + 1] - lt[lo])) return f
# ---------------------------------------------------------------------------# single-word helpers# ---------------------------------------------------------------------------
def _side(deg): return "left" if deg < 0 else "right"
def _dir(sign): if sign > 0: return "right" if sign < 0: return "left" return "still"
def _band3(value, t1, t2): return "small" if value < t1 else ("medium" if value < t2 else "large")
def _band3_rev(value, t1, t2): """large when the value is small (e.g. energy still high).""" return "large" if value > t1 else ("medium" if value > t2 else "small")
# ---------------------------------------------------------------------------# descriptive families# ---------------------------------------------------------------------------# Each entry: (family_index, family_name, subtype, question_text, answer_fn)# answer_fn(f) -> one-word str, or None to skip the question for that video.
OMEGA_STILL = 0.196 # empirical median over train -> exactly 50/50 yes/no
# Skip a question when the deciding value sits this close to a threshold. Without# it, a peak at 19.9999 deg flips the answer under a change of integration# resolution (observed: video_10595, count_swing_very_wide, 4 vs 5 at 96/192 Hz).MARGIN_DEG = 0.25MARGIN_OMEGA = 0.01
def _near_edge(values, edges, margin): return any(abs(float(v) - e) < margin for v in values for e in edges)
FAMILIES = [ (0, "count_swing_wide", "count", ["How many swings in this video are wider than 15 degrees?", "Count the swings that reach more than 15 degrees in this video.", "How many of the bob's swings in this video exceed 15 degrees?"], lambda f: None if _near_edge(f["peak_amps_deg"], [15.0], MARGIN_DEG) else str(f["n_peaks_15"])),
(1, "count_swing_very_wide", "count", ["How many swings in this video are wider than 20 degrees?", "Count the swings that reach more than 20 degrees in this video.", "How many of the bob's swings in this video exceed 20 degrees?"], lambda f: None if _near_edge(f["peak_amps_deg"], [20.0], MARGIN_DEG) else str(f["n_peaks_20"])),
(2, "count_turning_points", "count", ["How many times does the bob stop and turn around in this video?", "Count the moments when the bob reverses direction in this video.", "How many turning points does the bob reach in this video?"], lambda f: str(f["n_peaks"]) if f["n_peaks"] >= 1 else None),
(3, "query_release_side", "query_side", ["Which side of the pivot was the bob released from at the start of the video?", "At the beginning of the video, is the bob on the left or the right?", "Which side of the pivot does the bob start on?"], lambda f: _side(f["theta0_deg"]) if abs(f["theta0_deg"]) >= 5.0 else None),
(4, "query_initial_direction", "query_direction", ["Which way is the bob moving at the very start of the video?", "At the first frame, which direction is the bob travelling?", "Which way does the bob set off at the start of the video?"], lambda f: _dir(np.sign(f["omega0"])) if abs(f["omega0"]) >= 0.01 else "still"),
(5, "query_release_amplitude", "query_amplitude", ["How wide is the bob's first swing?", "How large is the bob's initial swing?", "How wide is the swing the bob starts with?"], lambda f: None if abs(f["theta0_deg"]) < 5.0 or _near_edge([abs(f["theta0_deg"])], [23.0, 32.0], MARGIN_DEG) else _band3(abs(f["theta0_deg"]), 23.0, 32.0)),
(6, "query_mid_amplitude", "query_amplitude", ["How wide is the bob's swing halfway through the video?", "Around the middle of the video, how wide is the swing?", "How wide is the swing at the midpoint of the video?"], lambda f: None if "mid_amp_deg" not in f or _near_edge([f["mid_amp_deg"]], [8.0, 18.0], MARGIN_DEG) else _band3(f["mid_amp_deg"], 8.0, 18.0)),
(7, "query_end_direction", "query_direction", ["Which way is the bob moving during the final second of the video?", "In the last second, which direction is the bob travelling?", "Which way is the bob swinging as the video ends?"], lambda f: None if _near_edge([f["last_sec_omega_max"]], [OMEGA_STILL], MARGIN_OMEGA) else ("still" if f["last_sec_omega_max"] < OMEGA_STILL else _dir(f["last_sec_sign"]))),
(8, "query_end_side", "query_position", ["Which side of the pivot is the bob on in the last frame of the video?", "At the end of the video, is the bob on the left or the right?", "Which side of the pivot does the bob finish on?"], lambda f: _side(f["theta_end_deg"]) if abs(f["theta_end_deg"]) >= 1.0 else None),
(9, "query_light_travel", "query_light", ["How far does the orange light source travel during the video?", "How much does the orange light source move in this video?", "Over the video, how large is the light source's sweep?"], lambda f: None if _near_edge([f["light_travel_deg"]], [10.0, 20.0], MARGIN_DEG) else _band3(f["light_travel_deg"], 10.0, 20.0)),
(10, "query_light_direction", "query_direction", ["Which way is the orange light source drifting at the start of the video?", "At the beginning, which direction is the light source moving?", "Which way does the light source set off at the start?"], lambda f: _dir(f["light_dir0"]) if f["light_travel_deg"] >= 4.0 else None),
# NOTE: `query_energy_end` was dropped. Every train video loses 86-99.9% of # its energy (gamma in 0.15-0.50), so the answer is near-constant and the # question is guessable without watching.
(12, "exist_still_swinging", "exist", ["Is the bob still visibly swinging at the end of the video?", "Is the bob still moving when the video ends?", "At the end of the video, is the bob still swinging?"], # gated to full-length clips: over the 8 s pre-intervention window the bob # is always still swinging, which would make this constant. lambda f: None if f["window_frames"] < FRAMES or _near_edge([f["last_sec_omega_max"]], [OMEGA_STILL], MARGIN_OMEGA) else ("yes" if f["last_sec_omega_max"] >= OMEGA_STILL else "no")),]
# Intervention families (intervened/ subset only). Emitted for every video;# balanced by construction because the subset is 120 light_shift / 120 torque_push.INTERVENTION_FAMILIES = [ (20, "query_intervention_target", "query_type", "Around the 8-second mark, which part of the scene is directly changed?", lambda kind: "light" if kind == "light_shift" else "bob"),
(21, "query_intervention_invariant", "query_invariant", "Around the 8-second mark, which part of the scene stays the same?", lambda kind: "bob" if kind == "light_shift" else "light"),
(22, "query_energy_at_cut", "query_energy", "At the 8-second mark, what happens to the bob's mechanical energy?", lambda kind: "smooth" if kind == "light_shift" else "jumps"),]
# ---------------------------------------------------------------------------# balanced selection# ---------------------------------------------------------------------------
def build_descriptive(facts, rng, tally, n_desc=2, hi=FRAMES, lo=0, intervention_kind=None): """Pick `n_desc` descriptive questions, greedy-balancing the answer marginals.
`tally` is a dict {(family_name, answer): count} shared across the whole split, so the marginal answer distribution stays near-uniform. """ out = []
if intervention_kind is not None: for fidx, name, sub, text, fn in INTERVENTION_FAMILIES: ans = fn(intervention_kind) out.append(_mk(fidx, name, sub, text, ans)) tally[(name, ans)] = tally.get((name, ans), 0) + 1 n_desc = max(0, n_desc - len(INTERVENTION_FAMILIES))
# candidates for this video cands = [] for fidx, name, sub, phrasings, fn in FAMILIES: try: ans = fn(facts) except Exception: ans = None if ans is None: continue text = phrasings[int(rng.integers(len(phrasings)))] cands.append((fidx, name, sub, text, ans))
order = rng.permutation(len(cands)) for i in order: if len(out) >= n_desc + (len(INTERVENTION_FAMILIES) if intervention_kind else 0): break fidx, name, sub, text, ans = cands[i] if any(o["question_family"] == name for o in out): continue out.append(_mk(fidx, name, sub, text, ans)) tally[(name, ans)] = tally.get((name, ans), 0) + 1
return out
def _mk(fidx, name, sub, text, ans): return { "question_type": "descriptive", "question_subtype": sub, "question_family_index": fidx, "question_family": name, "question": text, "answer": str(ans), }
ANSWER_VOCAB = sorted({ # count - closed numeric range. Observed maximum across all 3,000 videos # (including the OOD val regimes) is 22; 0..31 leaves headroom. *[str(i) for i in range(32)], # query_side / query_position / query_direction "left", "right", "still", # query_amplitude / query_light / query_energy "small", "medium", "large", # exist "yes", "no", # intervention "light", "bob", "smooth", "jumps",})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207#!/usr/bin/env python3"""Regenerate the descriptive questions in CLEVRER style.
python3 regenerate_descriptive.py
Reads : index.csv, intervened/index_intervention.csv, questions/questions_{train,val}.json, intervened/questions/questions_train.json, itv_ts/*.csv (shipped intervened labels)Writes : out/questions/questions_train.json out/questions/questions_val.json out/questions/taxonomy.json out/questions/answer_vocab.json out/intervened/questions/questions_train.json out/intervened/questions/taxonomy.json out/balance_report.json
Explanatory / predictive / counterfactual questions are copied verbatim, so thequestion count per video and every question_id are preserved exactly."""from __future__ import annotations
import collectionsimport csvimport jsonimport sysfrom pathlib import Path
import numpy as np
sys.path.insert(0, "scripts")import pendulum_gen as Gimport questions_v2 as Q
HERE = Path(__file__).parentOUT = HERE / "out"SEED = 20261014ITV_SEED = 20261118
def cfg_from_row(r): c = G.Configuration(name=r["name"]) for k in ("theta0_deg", "omega0_rad_s", "damping_s_inv", "light_mean_deg", "light_amplitude_deg", "light_frequency_hz", "light_phase_rad", "gravity_m_s2", "length_m", "quad_drag_beta", "drive_amp_rad_s2", "drive_freq_hz", "drive_phase_rad"): setattr(c, k, float(r[k])) c.damping_model = r["damping_model"] return c
def sim_array(cfg): rows = G.simulate(cfg, frames=G.EXT_FRAMES, substeps=G.SUBSTEPS) cols = collections.defaultdict(list) for row in rows: for k, v in row.items(): cols[k].append(v) return {k: np.asarray(v, dtype=float) for k, v in cols.items()}
def csv_array(path): rows = list(csv.DictReader(open(path))) return {k: np.asarray([float(r[k]) for r in rows], dtype=float) for k in rows[0] if k not in ("frame",)}
def rewrite(entry, new_desc, q_rng): """Swap descriptive questions in place, keeping ids and order.""" out, i = [], 0 for q in entry["questions"]: if q["question_type"] != "descriptive": out.append(q) continue if i >= len(new_desc): continue nq = dict(new_desc[i]) nq["question_id"] = q["question_id"] out.append(nq) i += 1 entry["questions"] = out return entry
def process(src, dst, arrays, tally, seed, n_desc, intervention=None): data = json.load(open(src)) for k, entry in enumerate(data["scene_annotation"]): vid = entry["video_id"] q_rng = np.random.default_rng(np.random.SeedSequence([seed, k, 777])) hi, lo = (Q.CUT_FRAME, 0) if intervention else (Q.FRAMES, 0) facts = Q.analyze(arrays[vid], hi=hi, lo=lo) kind = intervention[vid] if intervention else None new = Q.build_descriptive(facts, q_rng, tally, n_desc=n_desc, hi=hi, lo=lo, intervention_kind=kind) rewrite(entry, new, q_rng) info = data["info"] info["descriptive_style"] = ( "CLEVRER-style v2: open-ended, single-word answers from a closed " "vocabulary, sub-typed count/exist/query_*, family-indexed, " "answer-balanced") info["answer_convention"] = ( "descriptive: single-word open-ended string from answer_vocab.json; " "explanatory/predictive/counterfactual: index into 'choices'") data["answer_vocab"] = Q.ANSWER_VOCAB OUT.joinpath(dst).parent.mkdir(parents=True, exist_ok=True) json.dump(data, open(OUT / dst, "w"), indent=1) return data
def taxonomy(data, extra=()): fams = collections.OrderedDict() for v in data["scene_annotation"]: for q in v["questions"]: if q["question_type"] != "descriptive": continue e = fams.setdefault(q["question_family"], { "question_family_index": q["question_family_index"], "question_subtype": q["question_subtype"], "question_family": q["question_family"], "question_templates": [], "answers": [], }) if q["question"] not in e["question_templates"]: e["question_templates"].append(q["question"]) if q["answer"] not in e["answers"]: e["answers"].append(q["answer"]) for e in fams.values(): e["answers"] = sorted(e["answers"], key=lambda a: (not a.isdigit(), a)) for e in extra: fams[e["question_family"]] = e return { "descriptive_style": "CLEVRER-style: open-ended, single-word, " "family-indexed, sub-typed, answer-balanced", "descriptive_families": list(fams.values()), "other_question_types": ["explanatory", "predictive", "counterfactual"], "answer_convention": "descriptive: single-word string from " "answer_vocab.json; others: index into 'choices'", "answer_vocab": Q.ANSWER_VOCAB, }
def report(data, tag, out): byfam = collections.defaultdict(list) phrasings = collections.defaultdict(set) for v in data["scene_annotation"]: for q in v["questions"]: if q["question_type"] != "descriptive": continue byfam[q["question_family"]].append(q["answer"]) phrasings[q["question_family"]].add(q["question"]) tot = maj = 0 for fam, ans in sorted(byfam.items(), key=lambda kv: -len(kv[1])): c = collections.Counter(ans) tot += len(ans) maj += c.most_common(1)[0][1] out.append({"tag": tag, "family": fam, "n": len(ans), "distinct_answers": len(c), "majority": round(c.most_common(1)[0][1] / len(ans), 4), "phrasings": len(phrasings[fam]), "distribution": dict(c.most_common())}) print(f" {tag:22s} n={tot:6d} no-video baseline={maj/tot:6.1%} " f"families={len(byfam)} phrasings={sum(len(s) for s in phrasings.values())}") return tot, maj
def main(): OUT.mkdir(exist_ok=True) idx = list(csv.DictReader(open("index.csv")))
print("re-simulating 3000 parental trajectories from index.csv ...") arrays = {r["video_id"]: sim_array(cfg_from_row(r)) for r in idx}
print("loading 240 shipped intervened trajectories ...") itv_idx = list(csv.DictReader(open("intervened/index_intervention.csv"))) itv_arrays = {r["video_id"]: csv_array(f"itv_ts/{r['video_id']}.csv") for r in itv_idx} itv_kind = {r["video_id"]: r["intervention_type"] for r in itv_idx}
out_rows, gt, gm = [], 0, 0 print("\nregenerating descriptive questions:")
tally = {} d = process("questions/questions_train.json", "questions/questions_train.json", arrays, tally, SEED, 2) a, b = report(d, "root/train", out_rows); gt += a; gm += b
d = process("questions/questions_val.json", "questions/questions_val.json", arrays, tally, SEED, 2) a, b = report(d, "root/val", out_rows); gt += a; gm += b
json.dump(taxonomy(d), open(OUT / "questions/taxonomy.json", "w"), indent=1) json.dump({"answer_vocab": Q.ANSWER_VOCAB}, open(OUT / "questions/answer_vocab.json", "w"), indent=1)
tally = {} d = process("intervened/questions/questions_train.json", "intervened/questions/questions_train.json", itv_arrays, tally, ITV_SEED, 5, intervention=itv_kind) a, b = report(d, "intervened/train", out_rows); gt += a; gm += b json.dump(taxonomy(d), open(OUT / "intervened/questions/taxonomy.json", "w"), indent=1)
print(f"\n {'TOTAL descriptive':22s} n={gt:6d} no-video baseline={gm/gt:6.1%}") json.dump(out_rows, open(OUT / "balance_report.json", "w"), indent=1)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103#!/usr/bin/env python3"""Numerical-stability check: answers must survive 2x integration resolution.
python3 resolution_check.py
The shipped labels are produced at 8 substeps/frame (96 Hz). This re-simulatesevery video at 16 substeps/frame (192 Hz) and re-derives each descriptiveanswer. Any change means the answer sits on a numerical knife-edge."""from __future__ import annotations
import collectionsimport csvimport jsonimport sysfrom multiprocessing import Pool
import numpy as np
sys.path.insert(0, "scripts")import pendulum_gen as Gimport questions_v2 as Qfrom regenerate_descriptive import cfg_from_row
CHANGED = collections.Counter()CHECKED = collections.Counter()
def to_array(rows): cols = collections.defaultdict(list) for r in rows: for k, v in r.items(): cols[k].append(v) return {k: np.asarray(v, dtype=float) for k, v in cols.items()}
def one(args): vid, cfg, emitted, kind = args A8 = to_array(G.simulate(cfg, frames=G.EXT_FRAMES, substeps=8)) A16 = to_array(G.simulate(cfg, frames=G.EXT_FRAMES, substeps=16)) bad = [] checked = collections.Counter() for q in emitted: fam = q["question_family"] hi, lo = (Q.CUT_FRAME, 0) if kind else (Q.FRAMES, 0) try: a8 = _ans(fam, Q.analyze(A8, hi=hi, lo=lo), kind) a16 = _ans(fam, Q.analyze(A16, hi=hi, lo=lo), kind) except Exception: continue checked[fam] += 1 if a8 is None or a16 is None: continue if str(a8) != str(a16) or str(a16) != str(q["answer"]): bad.append((vid, fam, q["answer"], a16)) return bad, checked
def _ans(fam, facts, kind): if kind: for f in Q.INTERVENTION_FAMILIES: if f[1] == fam: return f[4](kind) for f in Q.FAMILIES: if f[1] == fam: return f[4](facts) return None
def main(): idx = {r["video_id"]: r for r in csv.DictReader(open("index.csv"))} itv_kind = {r["video_id"]: r["intervention_type"] for r in csv.DictReader(open("intervened/index_intervention.csv"))}
jobs = [] for src in ("out/questions/questions_train.json", "out/questions/questions_val.json", "out/intervened/questions/questions_train.json"): for v in json.load(open(src))["scene_annotation"]: vid = v["video_id"] if vid not in idx: continue desc = [q for q in v["questions"] if q["question_type"] == "descriptive"] jobs.append((vid, cfg_from_row(idx[vid]), desc, itv_kind.get(vid) if src.startswith("out/intervened") else None))
with Pool(8) as p: results = p.map(one, jobs, chunksize=20) bad = [b for r, _ in results for b in r] for _, c in results: CHECKED.update(c)
print(f"videos: {len(jobs)} answers checked: {sum(CHECKED.values())}") print(f"families checked: {len(CHECKED)}") for vid, fam, was, now in bad[:15]: print(f" CHANGED {vid} {fam}: 96Hz={was!r} 192Hz={now!r}") print(f"\nchanged under 2x resolution: {len(bad)} {dict(CHANGED)}") print("STABLE" if not bad else f"{len(bad)} UNSTABLE") sys.exit(0 if not bad else 1)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105#!/usr/bin/env python3"""Verify the regenerated descriptive questions.
python3 verify_descriptive.py
Checks, and exits non-zero on any failure: 1. question count per video is unchanged vs the shipped files 2. every non-descriptive question is byte-identical to the shipped file 3. descriptive questions carry no `choices` (open-ended, like CLEVRER) 4. every descriptive answer is exactly one word from answer_vocab.json 5. every descriptive question has question_subtype + question_family_index 6. no phrasing/family has a 100% majority answer 7. the no-video majority baseline is reported and compared to CLEVRER"""from __future__ import annotations
import collectionsimport jsonimport sys
PAIRS = [ ("questions/questions_train.json", "out/questions/questions_train.json"), ("questions/questions_val.json", "out/questions/questions_val.json"), ("intervened/questions/questions_train.json", "out/intervened/questions/questions_train.json"),]CLEVRER_BASELINE = 0.416 # measured on CLEVRER val descriptive, n=54,990fails = []
def check(ok, msg): print((" PASS " if ok else " FAIL ") + msg) if not ok: fails.append(msg)
def main(): vocab = set(json.load(open("out/questions/answer_vocab.json"))["answer_vocab"]) print(f"answer vocabulary: {len(vocab)} tokens\n")
grand_t = grand_m = 0 for old_p, new_p in PAIRS: old = json.load(open(old_p)) new = json.load(open(new_p)) print(f"--- {new_p}") ov, nv = old["scene_annotation"], new["scene_annotation"] check(len(ov) == len(nv), f"video count {len(ov)} == {len(nv)}")
same_len = all(len(a["questions"]) == len(b["questions"]) for a, b in zip(ov, nv)) check(same_len, "question count per video unchanged")
# non-descriptive must be untouched diff = 0 for a, b in zip(ov, nv): ka = [q for q in a["questions"] if q["question_type"] != "descriptive"] kb = [q for q in b["questions"] if q["question_type"] != "descriptive"] if ka != kb: diff += 1 check(diff == 0, f"non-descriptive questions identical ({diff} videos differ)")
desc = [q for v in nv for q in v["questions"] if q["question_type"] == "descriptive"]
check(all("choices" not in q for q in desc), f"no descriptive question has `choices` (n={len(desc)})")
multi = [q["answer"] for q in desc if len(str(q["answer"]).split()) != 1] check(not multi, f"all descriptive answers are single-word " f"({len(multi)} violations)")
bad = sorted({q["answer"] for q in desc if q["answer"] not in vocab}) check(not bad, f"all answers in vocabulary (offenders: {bad[:6]})")
miss = [q["question_family"] for q in desc if "question_subtype" not in q or "question_family_index" not in q] check(not miss, "all descriptive have subtype + family_index")
byfam = collections.defaultdict(list) for q in desc: byfam[q["question_family"]].append(q["answer"]) worst = max(byfam.items(), key=lambda kv: collections.Counter(kv[1]) .most_common(1)[0][1] / len(kv[1])) wmaj = collections.Counter(worst[1]).most_common(1)[0][1] / len(worst[1]) check(wmaj < 1.0, f"no family is 100% guessable " f"(worst: {worst[0]} at {wmaj:.1%})")
tot = sum(len(v) for v in byfam.values()) maj = sum(collections.Counter(v).most_common(1)[0][1] for v in byfam.values()) grand_t += tot grand_m += maj print(f" n={tot} families={len(byfam)} " f"no-video baseline={maj/tot:.1%}\n")
base = grand_m / grand_t print(f"=== overall no-video majority baseline: {base:.1%} " f"(CLEVRER descriptive: {CLEVRER_BASELINE:.1%})") check(base < 0.55, "overall baseline below 55%")
print("\n" + ("ALL CHECKS PASSED" if not fails else f"{len(fails)} FAILURE(S)")) sys.exit(0 if not fails else 1)
if __name__ == "__main__": main()questions/answer_vocab.jsonAdded+48
questions/questions_train.json
questions/questions_val.json
questions/taxonomy.json+263-134
scripts/crosscheck_answers.pyAdded+129
scripts/questions_v2.pyAdded+314
scripts/regenerate_descriptive.pyAdded+207
scripts/resolution_check.pyAdded+103
scripts/verify_descriptive.pyAdded+105