Download clevrer_lite/questions.py from jimchen2/clevrer-lite-example: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/datasets/jimchen2/clevrer-lite-example/resolve/main/clevrer_lite/questions.py
- Command line
-
hf download hf://datasets/jimchen2/clevrer-lite-example/clevrer_lite/questions.py
-
curl -L -o questions.py https://huggingface.co/datasets/jimchen2/clevrer-lite-example/resolve/main/clevrer_lite/questions.py
19 kB
| """CLEVRER-style question generation. | |
| Every question is generated from the *extracted events* of the recorded | |
| trajectory, so questions and answers are grounded in what actually happened. | |
| Question types mirror CLEVRER: | |
| descriptive - single/multi-step perception on the first frame | |
| ("How many red objects?", "What color is the sphere?") | |
| explanatory - causal/temporal reasoning about collision & motion events | |
| ("What happened right after ... collided?") | |
| predictive - "Will A collide with B by the end of the video?" | |
| counterfactual - answered by *re-simulating* the scene with one object | |
| removed, exactly like the real CLEVRER pipeline. | |
| Each question carries: text, answer, multiple-choice list + answer index, | |
| type, template id, and a simplified functional program. | |
| """ | |
| import numpy as np | |
| from . import config, simulate | |
| _NOTHING = "nothing happened" | |
| _ATTR_ORDER = ["size", "material", "color", "shape"] | |
| # -------------------------------------------------------------------------- | |
| # helpers | |
| # -------------------------------------------------------------------------- | |
| def _ref(obj, objs): | |
| """Shortest unambiguous CLEVRER-style reference, e.g. 'the red sphere'.""" | |
| for attrs in (("color", "shape"), ("color",), ("shape",), | |
| ("size", "color", "shape"), ("material", "color", "shape"), | |
| ("size", "material", "color", "shape")): | |
| vals = tuple(obj[a] for a in attrs) | |
| if sum(1 for o in objs if tuple(o[a] for a in attrs) == vals) == 1: | |
| ordered = [a for a in _ATTR_ORDER if a in attrs] | |
| return "the " + " ".join(obj[a] for a in ordered) | |
| return f"the object {obj['idx']}" | |
| def _shuffle_choices(ans, distractors, rng): | |
| """Build a shuffled choice list; returns (choices, answer_index).""" | |
| choices = [ans] + [d for d in distractors if d != ans] | |
| choices = list(dict.fromkeys(choices)) # dedupe, keep order | |
| perm = rng.permutation(len(choices)) | |
| choices = [choices[i] for i in perm] | |
| return choices, int(choices.index(ans)) | |
| def _numeric_choices(ans, lo, hi, rng, k=6): | |
| vals = {ans} | |
| pool = [v for v in range(lo, hi + 1) if v != ans] | |
| if pool: | |
| vals |= set(int(x) for x in rng.choice(pool, size=min(k - 1, len(pool)), | |
| replace=False)) | |
| return [str(v) for v in sorted(vals)] | |
| def _q(question, answer, choices, answer_index, qtype, template, program): | |
| answer = str(answer) | |
| if answer_index is None: | |
| answer_index = choices.index(answer) | |
| return {"question": question, "answer": answer, "choices": choices, | |
| "answer_index": answer_index, "question_type": qtype, | |
| "template": template, "program": program} | |
| def _col_choices(ans, rng): | |
| names = list(config.COLOR_NAMES) | |
| perm = rng.permutation(len(names)) | |
| choices = [names[i] for i in perm] | |
| return choices, choices.index(ans) | |
| # -------------------------------------------------------------------------- | |
| # descriptive questions (about the first frame) | |
| # -------------------------------------------------------------------------- | |
| def _descriptive(objs, ev, rng): | |
| out = [] | |
| n = len(objs) | |
| pos0 = {o["idx"]: o["position"] for o in objs} | |
| out.append(_q("How many objects are there?", str(n), | |
| _numeric_choices(n, 0, max(6, n), rng), None, | |
| "descriptive", "count_all", | |
| [{"op": "count"}])) | |
| # count by attribute | |
| for key, noun in (("color", "objects"), ("shape", "objects"), | |
| ("material", "objects")): | |
| values = sorted({o[key] for o in objs}) | |
| for v in values: | |
| cnt = sum(1 for o in objs if o[key] == v) | |
| phrase = f"How many {v} {noun} are there?" | |
| prog = [{"op": f"filter_{key}", "value": v}, {"op": "count"}] | |
| ch = _numeric_choices(cnt, 0, max(6, n), rng) | |
| out.append(_q(phrase, str(cnt), ch, None, "descriptive", | |
| f"count_{key}", prog)) | |
| # query color of a unique shape | |
| for sh in config.SHAPES: | |
| same = [o for o in objs if o["shape"] == sh] | |
| if len(same) == 1: | |
| o = same[0] | |
| ch, ai = _col_choices(o["color"], rng) | |
| out.append(_q(f"What color is the {sh}?", o["color"], ch, ai, | |
| "descriptive", "query_color", | |
| [{"op": "filter_shape", "value": sh}, | |
| {"op": "query_color"}])) | |
| # query shape of a unique color | |
| for col in config.COLOR_NAMES: | |
| same = [o for o in objs if o["color"] == col] | |
| if len(same) == 1: | |
| o = same[0] | |
| ch = list(config.SHAPES) | |
| perm = rng.permutation(len(ch)) | |
| ch = [ch[i] for i in perm] | |
| out.append(_q(f"What shape is the {col} object?", o["shape"], ch, | |
| list(ch).index(o["shape"]), "descriptive", | |
| "query_shape", | |
| [{"op": "filter_color", "value": col}, | |
| {"op": "query_shape"}])) | |
| # query material of a unique color+shape | |
| for o in objs: | |
| same = [x for x in objs if x["color"] == o["color"] and x["shape"] == o["shape"]] | |
| if len(same) == 1: | |
| ch = list(config.MATERIALS) | |
| perm = rng.permutation(len(ch)) | |
| ch = [ch[i] for i in perm] | |
| out.append(_q(f"What material is the {o['color']} {o['shape']} made of?", | |
| o["material"], ch, ch.index(o["material"]), | |
| "descriptive", "query_material", | |
| [{"op": "filter_color", "value": o["color"]}, | |
| {"op": "filter_shape", "value": o["shape"]}, | |
| {"op": "query_material"}])) | |
| # spatial relations (margin so 'left of' is unambiguous, exactly one match) | |
| margin = 0.6 | |
| dirs = { | |
| "left of": lambda a, b: (b[0] - a[0]) >= margin, # a is left of b | |
| "right of": lambda a, b: (a[0] - b[0]) >= margin, | |
| "behind": lambda a, b: (a[1] - b[1]) >= margin, # +y is far/back | |
| "in front of": lambda a, b: (b[1] - a[1]) >= margin, | |
| } | |
| for rb in objs: | |
| for name, fn in dirs.items(): | |
| cands = [o for o in objs if o["idx"] != rb["idx"] and | |
| fn(pos0[o["idx"]], pos0[rb["idx"]])] | |
| if len(cands) == 1: | |
| o = cands[0] | |
| ch, ai = _col_choices(o["color"], rng) | |
| out.append(_q(f"What color is the object {name} {_ref(rb, objs)}?", | |
| o["color"], ch, ai, "descriptive", "query_color_rel", | |
| [{"op": "filter_color", "value": rb["color"]}, | |
| {"op": "relate", "direction": name.replace(" ", "_")}, | |
| {"op": "query_color"}])) | |
| return out | |
| # -------------------------------------------------------------------------- | |
| # explanatory questions (causal / temporal) | |
| # -------------------------------------------------------------------------- | |
| def _coll_desc(objs, a, b): | |
| return f"{_ref(a, objs)} collided with {_ref(b, objs)}" | |
| def _explanatory(objs, ev, rng): | |
| out = [] | |
| cev = ev["collisions"] | |
| idx_of = {o["idx"]: o for o in objs} | |
| refc = {o["idx"]: _ref(o, objs) for o in objs} | |
| if not cev: | |
| return out | |
| def ev_desc(e): | |
| a, b = e["objects"] | |
| return _coll_desc(objs, idx_of[a], idx_of[b]) | |
| # what happened right after / before a collision | |
| for k, e in enumerate(cev): | |
| for direction, other in (("after", k + 1), ("before", k - 1)): | |
| ans = ev_desc(cev[other]) if 0 <= other < len(cev) else _NOTHING | |
| distractors = [ev_desc(x) for i, x in enumerate(cev) | |
| if i not in (k, other)] | |
| for (t, i, ax, s) in ev["wall_hits"][:40]: | |
| d = f"{refc[i]} collided with the wall" | |
| if d not in distractors: | |
| distractors.append(d) | |
| for o, sts in ev["starts"].items(): | |
| if o in refc and sts: | |
| d = f"{refc[o]} started moving" | |
| if d not in distractors: | |
| distractors.append(d) | |
| if ans != _NOTHING and _NOTHING not in distractors: | |
| distractors.append(_NOTHING) | |
| if len(distractors) < 3: | |
| continue | |
| rng.shuffle(distractors) | |
| distractors = distractors[:3] | |
| a, b = e["objects"] | |
| ch, ai = _shuffle_choices(ans, distractors, rng) | |
| out.append(_q(f"What happened right {direction} " | |
| f"{ev_desc(e)}?", ans, ch, ai, "explanatory", | |
| f"what_happened_{direction}", | |
| [{"op": "find_collision", "objects": [a, b]}, | |
| {"op": f"query_{direction}_event"}])) | |
| # what caused an object to start moving | |
| for o_idx, sts in ev["starts"].items(): | |
| if o_idx not in idx_of: | |
| continue | |
| for s in sts: | |
| cause = None | |
| for e in cev: | |
| a, b = e["objects"] | |
| if o_idx in (a, b) and abs(e["frame"] - s) <= config.CAUSE_WINDOW_FRAMES: | |
| cause = b if a == o_idx else a | |
| break | |
| if cause is None: | |
| continue | |
| ans = f"the collision with {refc[cause]}" | |
| others = [p for e in cev for p in e["objects"] | |
| if p not in (o_idx, cause) and p in refc] | |
| distractors = [f"the collision with {refc[p]}" for p in dict.fromkeys(others)] | |
| distractors += ["it was pushed by the wall", "nothing - it was already moving"] | |
| rng.shuffle(distractors) | |
| ch, ai = _shuffle_choices(ans, distractors[:3], rng) | |
| out.append(_q(f"What caused {refc[o_idx]} to start moving?", ans, ch, ai, | |
| "explanatory", "cause_of_motion", | |
| [{"op": "filter_object", "idx": o_idx}, | |
| {"op": "query_motion_cause"}])) | |
| # which object started moving right before / after a collision | |
| for e in cev: | |
| a, b = e["objects"] | |
| t = e["frame"] | |
| for direction, lo, hi, pick in (("after", t + 1, t + 12, min), | |
| ("before", max(1, t - 12), t, max)): | |
| cands = [(s, o) for o, ss in ev["starts"].items() | |
| if o not in (a, b) and o in idx_of for s in ss | |
| if lo <= s <= hi] | |
| if not cands: | |
| continue | |
| _, ans_o = pick(cands) | |
| ans = refc[ans_o] | |
| others = [o for o in objs if o["idx"] not in (ans_o, a, b)] | |
| distractors = [_ref(o, objs) for o in others] | |
| distractors.append("none of them") | |
| rng.shuffle(distractors) | |
| ch, ai = _shuffle_choices(ans, distractors[:3], rng) | |
| out.append(_q(f"Which object started moving right {direction} " | |
| f"{ev_desc(e)}?", ans, ch, ai, "explanatory", | |
| f"who_started_{direction}", | |
| [{"op": "find_collision", "objects": [a, b]}, | |
| {"op": f"query_{direction}_motion_start"}])) | |
| # how many objects were moving when a collision happened | |
| for e in cev: | |
| a, b = e["objects"] | |
| t = min(e["frame"], ev["moving"].shape[0] - 1) | |
| cnt = int(ev["moving"][t].sum()) | |
| ch = _numeric_choices(cnt, 0, len(objs), rng) | |
| out.append(_q(f"How many objects were moving when {ev_desc(e)}?", | |
| str(cnt), ch, None, "explanatory", "count_moving_at", | |
| [{"op": "find_collision", "objects": [a, b]}, | |
| {"op": "count_moving_at_collision"}])) | |
| # total number of collisions | |
| if len(cev) >= 2: | |
| ch = _numeric_choices(len(cev), 0, max(6, len(cev) + 1), rng) | |
| out.append(_q("How many collisions happened in the video?", | |
| str(len(cev)), ch, None, "explanatory", | |
| "count_collisions", | |
| [{"op": "filter_event", "type": "collision"}, {"op": "count"}])) | |
| return out | |
| # -------------------------------------------------------------------------- | |
| # predictive questions (binary, grounded in the full recorded trajectory) | |
| # -------------------------------------------------------------------------- | |
| def _predictive(objs, ev, rng): | |
| out = [] | |
| cev = ev["collisions"] | |
| idx_of = {o["idx"]: o for o in objs} | |
| pairs_collided = {tuple(sorted(e["objects"])) for e in cev} | |
| all_pairs = [tuple(sorted((a["idx"], b["idx"]))) | |
| for i, a in enumerate(objs) for b in objs[i + 1:]] | |
| def binary_q(pair, ans_yes, template): | |
| a, b = pair | |
| ch = ["yes", "no"] | |
| rng.shuffle(ch) | |
| ans = "yes" if ans_yes else "no" | |
| return _q(f"Will {_ref(idx_of[a], objs)} collide with " | |
| f"{_ref(idx_of[b], objs)} by the end of the video?", | |
| ans, ch, ch.index(ans), "predictive", template, | |
| [{"op": "find_collision", "objects": [a, b]}, | |
| {"op": "query_existence"}]) | |
| yes_pairs = [p for p in pairs_collided] | |
| no_pairs = [p for p in all_pairs if p not in pairs_collided] | |
| if yes_pairs: | |
| p = yes_pairs[int(rng.integers(len(yes_pairs)))] | |
| out.append(binary_q(p, True, "will_collide")) | |
| if no_pairs: | |
| p = no_pairs[int(rng.integers(len(no_pairs)))] | |
| out.append(binary_q(p, False, "will_collide")) | |
| # after colliding with b, will a collide with something else? | |
| for e in cev: | |
| a, b = e["objects"] | |
| later = [x for x in cev if x is not e and a in x["objects"] | |
| and x["frame"] > e["frame"]] | |
| if not later and len(cev) < 2: | |
| continue | |
| ans = "yes" if later else "no" | |
| ch = ["yes", "no"] | |
| rng.shuffle(ch) | |
| out.append(_q(f"After {_coll_desc(objs, idx_of[a], idx_of[b])}, " | |
| f"will {_ref(idx_of[a], objs)} collide with something else?", | |
| ans, ch, ch.index(ans), "predictive", "will_collide_again", | |
| [{"op": "find_collision", "objects": [a, b]}, | |
| {"op": "query_subsequent_collision"}])) | |
| return out | |
| # -------------------------------------------------------------------------- | |
| # counterfactual questions (re-simulate the scene with one object removed) | |
| # -------------------------------------------------------------------------- | |
| def _counterfactual(objs, ev, rng, num_frames): | |
| out = [] | |
| cev = ev["collisions"] | |
| if not cev or len(objs) < 3: | |
| return out | |
| idx_of = {o["idx"]: o for o in objs} | |
| refc = {o["idx"]: _ref(o, objs) for o in objs} | |
| cache = {} | |
| def cf_events(z): | |
| if z not in cache: | |
| cache[z] = simulate.resimulate_without( | |
| [dict(s) for s in objs], z, num_frames) | |
| return cache[z] | |
| def binary(ans_yes, question, template, program): | |
| ch = ["yes", "no"] | |
| rng.shuffle(ch) | |
| ans = "yes" if ans_yes else "no" | |
| out.append(_q(question, ans, ch, ch.index(ans), "counterfactual", | |
| template, program)) | |
| # would a still collide with b without z? | |
| for e in cev: | |
| a, b = e["objects"] | |
| others = [o["idx"] for o in objs if o["idx"] not in (a, b)] | |
| for z in others: | |
| cf = cf_events(z) | |
| still = any(set(x["objects"]) == {a, b} for x in cf["collisions"]) | |
| binary(still, | |
| f"If {refc[z]} were removed, would {refc[a]} still collide " | |
| f"with {refc[b]}?", | |
| "cf_collision", | |
| [{"op": "remove_object", "idx": z}, | |
| {"op": "find_collision", "objects": [a, b]}, | |
| {"op": "query_existence"}]) | |
| # would o still start moving without z (z can be its collision partner)? | |
| for o_idx, sts in ev["starts"].items(): | |
| if not sts or o_idx not in idx_of: | |
| continue | |
| partners = set() | |
| for e in cev: | |
| if o_idx in e["objects"]: | |
| partners |= {p for p in e["objects"] if p != o_idx} | |
| others = list(partners) + [o["idx"] for o in objs | |
| if o["idx"] not in {o_idx} | partners] | |
| for z in dict.fromkeys(others): | |
| cf = cf_events(z) | |
| still = (o_idx in cf["initially_moving"]) or bool(cf["starts"].get(o_idx)) | |
| binary(still, | |
| f"If {refc[z]} were removed, would {refc[o_idx]} still " | |
| f"start moving?", | |
| "cf_motion", | |
| [{"op": "remove_object", "idx": z}, | |
| {"op": "filter_object", "idx": o_idx}, | |
| {"op": "query_motion_start"}]) | |
| return out | |
| # -------------------------------------------------------------------------- | |
| # orchestration | |
| # -------------------------------------------------------------------------- | |
| def build_questions(spec, ev, rng, num_frames, max_questions=8): | |
| """Return a list of question dicts sampled across the 4 CLEVRER types.""" | |
| objs = [s for s in spec if not s.get("is_probe")] | |
| probe_idx = {s["idx"] for s in spec if s.get("is_probe")} | |
| if probe_idx: # drop probe objects from question-relevant events | |
| ev = { | |
| "collisions": [e for e in ev["collisions"] if not probe_idx & set(e["objects"])], | |
| "starts": {k: v for k, v in ev["starts"].items() if k not in probe_idx}, | |
| "stops": {k: v for k, v in ev["stops"].items() if k not in probe_idx}, | |
| "initially_moving": [k for k in ev["initially_moving"] if k not in probe_idx], | |
| "moving": ev["moving"], | |
| "speeds": ev["speeds"], | |
| "wall_hits": [w for w in ev["wall_hits"] if w[1] not in probe_idx], | |
| } | |
| pools = { | |
| "descriptive": _descriptive(objs, ev, rng), | |
| "explanatory": _explanatory(objs, ev, rng), | |
| "predictive": _predictive(objs, ev, rng), | |
| "counterfactual": _counterfactual(objs, ev, rng, num_frames), | |
| } | |
| quotas = [("descriptive", 3), ("explanatory", 2), | |
| ("predictive", 1), ("counterfactual", 2)] | |
| picked, seen = [], set() | |
| def take(pool, k): | |
| pool = [q for q in pool if q["question"] not in seen] | |
| rng.shuffle(pool) | |
| for q in pool[:k]: | |
| seen.add(q["question"]) | |
| picked.append(q) | |
| for qtype, k in quotas: | |
| take(pools[qtype], k) | |
| leftover = [q for pool in pools.values() for q in pool | |
| if q["question"] not in seen] | |
| rng.shuffle(leftover) | |
| for q in leftover: | |
| if len(picked) >= max_questions: | |
| break | |
| seen.add(q["question"]) | |
| picked.append(q) | |
| rng.shuffle(picked) | |
| return picked | |