File size: 6,099 Bytes
538ccea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"""
Procedural generator for the In-Context Grid Reasoning (ICGR) dataset.

Every task is a demonstration-conditioned rule-induction problem in the spirit of
ARC-AGI: a few (input grid -> output grid) support pairs share one hidden
transformation, and the solver must apply that same transformation to a held-out
query input.

All data here is synthetic and generated by this script alone. No third-party
text, images, or datasets are used, so the output carries no upstream copyright.

Reproduce with:  python generate.py
"""

import argparse
import json
import random
from pathlib import Path

# --- grid helpers -----------------------------------------------------------

def new_grid(rng, h, w, ncolors):
    return [[rng.randrange(ncolors) for _ in range(w)] for _ in range(h)]


def dims(g):
    return len(g), len(g[0])


def to_str(g):
    return ";".join(" ".join(str(v) for v in row) for row in g)


# --- transformations ------------------------------------------------------
# Each is a pure function grid -> grid. Keep them total: any rectangular grid in,
# rectangular grid out. Params are frozen per task so every support pair and the
# query share the exact same rule.

def t_flip_h(g, p):
    return [list(reversed(row)) for row in g]


def t_flip_v(g, p):
    return [list(row) for row in reversed(g)]


def t_transpose(g, p):
    h, w = dims(g)
    return [[g[r][c] for r in range(h)] for c in range(w)]


def t_rotate90(g, p):
    h, w = dims(g)
    return [[g[h - 1 - r][c] for r in range(h)] for c in range(w)]


def t_add_mod(g, p):
    k, n = p["k"], p["ncolors"]
    return [[(v + k) % n for v in row] for row in g]


def t_color_swap(g, p):
    a, b = p["a"], p["b"]
    return [[b if v == a else a if v == b else v for v in row] for row in g]


def t_shift_rows(g, p):
    s = p["s"]
    return [row[-s:] + row[:-s] for row in g]


def t_tile_h(g, p):
    return [row + row for row in g]


def t_border(g, p):
    c = p["c"]
    h, w = dims(g)
    out = [list(row) for row in g]
    for j in range(w):
        out[0][j] = c
        out[h - 1][j] = c
    for i in range(h):
        out[i][0] = c
        out[i][w - 1] = c
    return out


def t_max_pool2(g, p):
    # non-overlapping 2x2 max; grid dims are always even in this generator
    h, w = dims(g)
    return [[max(g[2 * r][2 * c], g[2 * r + 1][2 * c],
                 g[2 * r][2 * c + 1], g[2 * r + 1][2 * c + 1])
             for c in range(w // 2)] for r in range(h // 2)]


TRANSFORMS = {
    "flip_h": (t_flip_h, "Mirror the grid left-to-right."),
    "flip_v": (t_flip_v, "Mirror the grid top-to-bottom."),
    "transpose": (t_transpose, "Swap rows and columns (transpose)."),
    "rotate90": (t_rotate90, "Rotate the grid 90 degrees clockwise."),
    "add_mod": (t_add_mod, "Add a fixed constant to every cell, modulo the colour count."),
    "color_swap": (t_color_swap, "Swap two colours everywhere they appear."),
    "shift_rows": (t_shift_rows, "Cyclically shift every row right by a fixed amount."),
    "tile_h": (t_tile_h, "Concatenate the grid with a copy of itself, side by side."),
    "border": (t_border, "Paint the outer border of the grid a fixed colour."),
    "max_pool2": (t_max_pool2, "Replace each non-overlapping 2x2 block with its maximum value."),
}

SINGLE = list(TRANSFORMS)
# pairs that compose cleanly without fighting over dimensions
COMPOSABLE = ["flip_h", "flip_v", "add_mod", "color_swap", "shift_rows", "border"]


def sample_params(rng, ncolors):
    return {
        "ncolors": ncolors,
        "k": rng.randint(1, ncolors - 1),
        "a": rng.randrange(ncolors),
        "b": rng.randrange(ncolors),
        "s": rng.randint(1, 2),
        "c": rng.randrange(ncolors),
    }


def apply_rule(rule, g, p):
    for name in rule:
        g = TRANSFORMS[name][0](g, p)
    return g


def describe(rule):
    return " Then, ".join(TRANSFORMS[n][1] for n in rule)


# --- task assembly --------------------------------------------------------

def make_task(rng, task_id):
    ncolors = rng.choice([4, 5, 6])
    compose = rng.random() < 0.35
    if compose:
        rule = rng.sample(COMPOSABLE, 2)
    else:
        rule = [rng.choice(SINGLE)]

    # max_pool halves dims, so start even and a bit larger for it
    if "max_pool2" in rule:
        h = rng.choice([4, 6])
        w = rng.choice([4, 6])
    else:
        h = rng.randint(3, 5)
        w = rng.randint(3, 5)

    p = sample_params(rng, ncolors)
    n_support = rng.randint(2, 4)

    grids = []
    seen = set()
    while len(grids) < n_support + 1:
        g = new_grid(rng, h, w, ncolors)
        key = to_str(g)
        if key in seen:
            continue
        seen.add(key)
        grids.append(g)

    support = [{"input": to_str(g), "output": to_str(apply_rule(rule, g, p))}
               for g in grids[:-1]]
    q = grids[-1]

    return {
        "task_id": task_id,
        "rule": "+".join(rule),
        "rule_kind": "composed" if compose else "atomic",
        "rule_description": describe(rule),
        "num_colors": ncolors,
        "grid_h": h,
        "grid_w": w,
        "num_support": n_support,
        "support": support,
        "query_input": to_str(q),
        "query_output": to_str(apply_rule(rule, q, p)),
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=1000)
    ap.add_argument("--seed", type=int, default=20260903)
    ap.add_argument("--test-frac", type=float, default=0.2)
    ap.add_argument("--out", type=Path, default=Path("data"))
    args = ap.parse_args()

    rng = random.Random(args.seed)
    tasks = [make_task(rng, f"icgr-{i:05d}") for i in range(args.n)]
    rng.shuffle(tasks)
    n_test = int(args.n * args.test_frac)
    splits = {"test": tasks[:n_test], "train": tasks[n_test:]}

    args.out.mkdir(parents=True, exist_ok=True)
    for name, rows in splits.items():
        path = args.out / f"{name}.jsonl"
        with path.open("w") as f:
            for r in rows:
                f.write(json.dumps(r) + "\n")
        print(f"{name}: {len(rows)} -> {path}")


if __name__ == "__main__":
    main()