in-context-grid-reasoning / test_generate.py
WhySoCodius's picture
Add In-Context Grid Reasoning dataset (synthetic, CC-BY-4.0)
538ccea verified
Raw
History Blame Contribute Delete
2.75 kB
"""Self-check for generate.py. Run: python test_generate.py"""
import random
from generate import (TRANSFORMS, make_task, apply_rule, to_str, new_grid,
sample_params, t_max_pool2)
def _from_str(s):
return [[int(v) for v in row.split()] for row in s.split(";")]
def test_transforms_are_total_and_rectangular():
rng = random.Random(0)
for name, (fn, _) in TRANSFORMS.items():
for _ in range(50):
h = rng.choice([4, 6]) if name == "max_pool2" else rng.randint(3, 5)
w = rng.choice([4, 6]) if name == "max_pool2" else rng.randint(3, 5)
g = new_grid(rng, h, w, 6)
out = fn(g, sample_params(rng, 6))
assert out and all(len(r) == len(out[0]) for r in out), name
def test_known_values():
g = [[1, 2], [3, 4]]
assert TRANSFORMS["flip_h"][0](g, {}) == [[2, 1], [4, 3]]
assert TRANSFORMS["flip_v"][0](g, {}) == [[3, 4], [1, 2]]
assert TRANSFORMS["transpose"][0](g, {}) == [[1, 3], [2, 4]]
assert TRANSFORMS["rotate90"][0](g, {}) == [[3, 1], [4, 2]]
assert t_max_pool2([[1, 9, 0, 0], [0, 0, 0, 0], [0, 0, 5, 0], [0, 0, 0, 7]], {}) == [[9, 0], [0, 7]]
def test_query_answer_matches_support_rule():
rng = random.Random(1)
for i in range(400):
t = make_task(rng, f"t-{i}")
rule = t["rule"].split("+")
# re-derive every support output from the stated rule params is not
# possible without params, but the rule must at least be self-consistent:
# applying it to query_input must reproduce query_output.
got = to_str(apply_rule(rule, _from_str(t["query_input"]),
_params_for(t)))
assert got == t["query_output"], t["task_id"]
def _params_for(task):
# generate.py freezes params inside make_task; reconstruct a compatible set by
# brute force over the small param space so the check stays independent.
from itertools import product
n = task["num_colors"]
qi = _from_str(task["query_input"])
rule = task["rule"].split("+")
for k, a, b, s, c in product(range(1, n), range(n), range(n), (1, 2), range(n)):
p = {"ncolors": n, "k": k, "a": a, "b": b, "s": s, "c": c}
if to_str(apply_rule(rule, qi, p)) == task["query_output"]:
return p
raise AssertionError(f"no params reproduce {task['task_id']}")
def test_deterministic():
a = [make_task(random.Random(42), f"x{i}") for i in range(20)]
b = [make_task(random.Random(42), f"x{i}") for i in range(20)]
assert a == b
if __name__ == "__main__":
test_transforms_are_total_and_rectangular()
test_known_values()
test_query_answer_matches_support_rule()
test_deterministic()
print("all checks passed")