rogermt commited on
Commit
9caa30d
·
verified ·
1 Parent(s): 9ae02a4

Add DeepSeek task classifier for LLM-guided solver routing

Browse files
Files changed (1) hide show
  1. trm_solver/classify_tasks.py +191 -0
trm_solver/classify_tasks.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ ARC-AGI Task Classifier — Routes tasks to NeuroGolf solvers via DeepSeek API.
4
+ Output: JSON mapping task_id -> ordered solver list to try first.
5
+ The LLM call is OFFLINE (model generation time only). Zero ONNX cost.
6
+
7
+ Usage on Kaggle:
8
+ python classify_tasks.py
9
+
10
+ Usage locally:
11
+ python classify_tasks.py --data_dir ARC-AGI/data/training/
12
+ """
13
+
14
+ import json, os, glob, time, argparse
15
+
16
+ SOLVER_NAMES = [
17
+ "identity", "constant", "color_map", "transpose", "flip", "rotate",
18
+ "shift", "tile", "upscale", "kronecker", "nonuniform_scale",
19
+ "mirror_h", "mirror_v", "quad_mirror", "concat", "concat_enhanced",
20
+ "diagonal_tile", "fixed_crop", "spatial_gather",
21
+ "varshape_spatial_gather", "gravity_unrolled", "edge_detect",
22
+ "mode_fill", "downsample_stride", "symmetry_complete",
23
+ "extract_inner", "add_border", "sparse_fill", "channel_filter",
24
+ ]
25
+
26
+ COMPOSITION_PATTERNS = [
27
+ "transform_then_recolor",
28
+ "crop_then_transform",
29
+ "recolor_then_tile",
30
+ ]
31
+
32
+ SYSTEM_PROMPT = f"""You are a world-class ARC-AGI pattern classifier. Analyze grid transformations and predict which solver would produce the correct output.
33
+
34
+ Available single solvers:
35
+ {', '.join(SOLVER_NAMES)}
36
+
37
+ Available composition solvers (two transforms chained):
38
+ {', '.join(COMPOSITION_PATTERNS)}
39
+
40
+ Solver descriptions:
41
+ - identity: output = input
42
+ - constant: output is a fixed grid regardless of input
43
+ - color_map: per-pixel color remapping
44
+ - transpose: matrix transpose
45
+ - flip: horizontal or vertical flip
46
+ - rotate: 90/180/270 rotation
47
+ - shift: translate grid by offset
48
+ - tile: repeat input to fill output
49
+ - upscale: nearest-neighbor pixel-repeat zoom
50
+ - kronecker: kron(mask, input) self-similar
51
+ - nonuniform_scale: non-integer scale
52
+ - mirror_h/v: mirror and tile horizontally/vertically
53
+ - quad_mirror: 4-way kaleidoscope
54
+ - concat: concatenate transformed copies
55
+ - concat_enhanced: concat with color-dependent selection
56
+ - diagonal_tile: tile along diagonal
57
+ - fixed_crop: crop a rectangular region
58
+ - spatial_gather: arbitrary pixel rearrangement
59
+ - varshape_spatial_gather: spatial_gather with variable shapes
60
+ - gravity_unrolled: directional pixel compaction
61
+ - mode_fill: fill grid with most common color
62
+ - downsample_stride: subsample at regular stride
63
+ - symmetry_complete: complete partial symmetry
64
+ - extract_inner: remove outer border/frame
65
+ - add_border: add constant-color border
66
+ - sparse_fill: expand non-zero pixels into blocks
67
+ - channel_filter: keep only certain color channels
68
+ - transform_then_recolor: any spatial transform THEN color_map
69
+ - crop_then_transform: crop THEN apply spatial transform
70
+ - recolor_then_tile: color_map THEN tile/upscale
71
+
72
+ IMPORTANT: Look at ALL training pairs together. The pattern must be consistent across all pairs.
73
+
74
+ Output a valid JSON object mapping each task ID to:
75
+ {{
76
+ "TASK_ID": {{
77
+ "primary_solver": "solver_name",
78
+ "fallback_solvers": ["solver1", "solver2"],
79
+ "grid_size_changed": true/false,
80
+ "confidence": 1-10,
81
+ "notes": "brief pattern description"
82
+ }}
83
+ }}
84
+
85
+ Output ONLY JSON. No other text."""
86
+
87
+
88
+ def format_grid(grid):
89
+ return "\n".join([f"R{i}: {row}" for i, row in enumerate(grid)])
90
+
91
+
92
+ def classify_tasks(data_dir, output_file, api_key=None, base_url=None,
93
+ model="deepseek-chat", batch_size=5):
94
+ """Classify all ARC tasks using DeepSeek API."""
95
+
96
+ if api_key:
97
+ from openai import OpenAI
98
+ client = OpenAI(api_key=api_key, base_url=base_url or "https://api.deepseek.com")
99
+ else:
100
+ try:
101
+ from kaggle_secrets import UserSecretsClient
102
+ from openai import OpenAI
103
+ user_secrets = UserSecretsClient()
104
+ client = OpenAI(
105
+ api_key=user_secrets.get_secret("Deepseek_api_key"),
106
+ base_url="https://api.deepseek.com"
107
+ )
108
+ except ImportError:
109
+ raise RuntimeError("No API key provided and not on Kaggle.")
110
+
111
+ all_files = sorted(glob.glob(os.path.join(data_dir, "task*.json")))
112
+ if not all_files:
113
+ all_files = sorted(glob.glob(os.path.join(data_dir, "*.json")))
114
+ print(f"Found {len(all_files)} task files")
115
+
116
+ classifications = {}
117
+ if os.path.exists(output_file):
118
+ with open(output_file) as f:
119
+ classifications = json.load(f)
120
+ print(f"Resuming: {len(classifications)} already classified")
121
+
122
+ for i in range(0, len(all_files), batch_size):
123
+ batch_files = all_files[i : i + batch_size]
124
+ batch_ids = [os.path.basename(f).replace('.json','') for f in batch_files]
125
+ if all(bid in classifications for bid in batch_ids):
126
+ continue
127
+
128
+ prompt = "Classify these ARC tasks:\n"
129
+ for f in batch_files:
130
+ tid = os.path.basename(f).replace('.json','')
131
+ with open(f) as fh:
132
+ task = json.load(fh)
133
+ prompt += f"\n### TASK: {tid}\n"
134
+ for idx, pair in enumerate(task.get('train', [])):
135
+ prompt += f"--- Example {idx} ---\nIN:\n{format_grid(pair['input'])}\nOUT:\n{format_grid(pair['output'])}\n"
136
+ for idx, pair in enumerate(task.get('test', [])):
137
+ prompt += f"--- Test Input {idx} ---\nIN:\n{format_grid(pair['input'])}\n"
138
+
139
+ for attempt in range(3):
140
+ try:
141
+ response = client.chat.completions.create(
142
+ model=model,
143
+ messages=[
144
+ {"role": "system", "content": SYSTEM_PROMPT},
145
+ {"role": "user", "content": prompt}
146
+ ],
147
+ response_format={'type': 'json_object'}
148
+ )
149
+ batch_results = json.loads(response.choices[0].message.content)
150
+ classifications.update(batch_results)
151
+ with open(output_file, 'w') as f:
152
+ json.dump(classifications, f, indent=2)
153
+ print(f" [{i+1}-{i+len(batch_files)}] Classified: {list(batch_results.keys())}")
154
+ break
155
+ except Exception as e:
156
+ print(f" Retry {attempt+1}: {e}")
157
+ time.sleep(3)
158
+
159
+ routing = {}
160
+ for tid, data in classifications.items():
161
+ primary = data.get('primary_solver', '')
162
+ fallbacks = data.get('fallback_solvers', [])
163
+ solvers = [primary] + [s for s in fallbacks if s != primary]
164
+ routing[tid] = {
165
+ 'solvers': solvers,
166
+ 'confidence': data.get('confidence', 5),
167
+ 'grid_changed': data.get('grid_size_changed', False),
168
+ 'notes': data.get('notes', '')
169
+ }
170
+
171
+ routing_file = output_file.replace('.json', '_routing.json')
172
+ with open(routing_file, 'w') as f:
173
+ json.dump(routing, f, indent=2)
174
+
175
+ print(f"\nDone. {len(classifications)} tasks classified.")
176
+ print(f"Classifications: {output_file}")
177
+ print(f"Routing table: {routing_file}")
178
+ return routing
179
+
180
+
181
+ if __name__ == "__main__":
182
+ parser = argparse.ArgumentParser()
183
+ parser.add_argument('--data_dir', default='/kaggle/input/competitions/neurogolf-2026/')
184
+ parser.add_argument('--output_file', default='/kaggle/working/arc_task_routes.json')
185
+ parser.add_argument('--api_key', default='')
186
+ parser.add_argument('--base_url', default='')
187
+ parser.add_argument('--model', default='deepseek-chat')
188
+ parser.add_argument('--batch_size', type=int, default=5)
189
+ args = parser.parse_args()
190
+ classify_tasks(args.data_dir, args.output_file, args.api_key,
191
+ args.base_url, args.model, args.batch_size)