rogermt commited on
Commit
9a5b998
·
verified ·
1 Parent(s): a827001

Add sign_corrected_conv.py: refit conv_var tasks with direct output (>0 validation, 3 nodes instead of 15-20)

Browse files
Files changed (1) hide show
  1. own-solver/sign_corrected_conv.py +290 -0
own-solver/sign_corrected_conv.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Sign-corrected direct Conv solver for conv_var tasks.
4
+
5
+ Replaces the current architecture:
6
+ ReduceSum → Conv → ArgMax → Equal×10 → Cast×10 → Concat → Mul → output (15-20 nodes)
7
+
8
+ With minimal architecture:
9
+ ReduceSum → Conv → Mul → output (3 nodes, 2 intermediates)
10
+
11
+ The key insight: Kaggle validates via (output > 0.0).astype(float).
12
+ If Conv weights are trained to produce POSITIVE values only in the correct
13
+ channel and NEGATIVE/ZERO in all others, we skip ArgMax+OneHot entirely.
14
+
15
+ Algorithm:
16
+ 1. lstsq fit with targets: +1 (correct channel), -1 (wrong channels)
17
+ 2. Check for sign violations (pixels where wrong channel is positive)
18
+ 3. Iteratively increase margin on violating pixels until all signs are correct
19
+ 4. Validate on full train+test+arc-gen
20
+
21
+ Integration: Add this to conv.py as an alternative to solve_conv_variable.
22
+ Call it FIRST (before the standard approach). If it succeeds, use it.
23
+ If not, fall back to the standard ArgMax+OneHot approach.
24
+
25
+ Score impact under new formula (25 - ln(memory + params)):
26
+ Old conv_var ks=3: ~10 intermediate tensors → cost ~170,000 → score ~13.0
27
+ New direct ks=3: 2 intermediate tensors → cost ~44,500 → score ~14.3
28
+ GAIN: +1.3 pts per ks=3 task (8 tasks = +10.4 pts)
29
+
30
+ For larger kernels: gain is similar since we eliminate the same onehot overhead.
31
+
32
+ Usage standalone:
33
+ python sign_corrected_conv.py --data_dir ./tasks --output_dir ./models
34
+
35
+ Usage integrated in solver pipeline:
36
+ Import solve_conv_var_direct() and call before solve_conv_variable()
37
+ """
38
+
39
+ import json
40
+ import math
41
+ import os
42
+ import sys
43
+ import time
44
+
45
+ import numpy as np
46
+ import onnx
47
+ import onnxruntime as ort
48
+ from onnx import helper, TensorProto, numpy_helper
49
+
50
+
51
+ GRID_SHAPE = [1, 10, 30, 30]
52
+ GH, GW = 30, 30
53
+
54
+
55
+ def encode_grid(grid):
56
+ """Encode integer grid to one-hot tensor."""
57
+ arr = np.array(grid, dtype=np.int32)
58
+ h, w = arr.shape
59
+ t = np.zeros((1, 10, 30, 30), dtype=np.float32)
60
+ for r in range(h):
61
+ for c in range(w):
62
+ if 0 <= arr[r, c] < 10:
63
+ t[0, arr[r, c], r, c] = 1.0
64
+ return t
65
+
66
+
67
+ def validate_model(model_bytes, examples, max_check=50):
68
+ """Validate model via (output > 0.0) == expected one-hot."""
69
+ try:
70
+ opts = ort.SessionOptions()
71
+ opts.log_severity_level = 3
72
+ sess = ort.InferenceSession(model_bytes, sess_options=opts, providers=['CPUExecutionProvider'])
73
+ except Exception:
74
+ return False
75
+ for ex in examples[:max_check]:
76
+ try:
77
+ inp = encode_grid(ex['input'])
78
+ out = sess.run(['output'], {'input': inp})[0]
79
+ expected = encode_grid(ex['output'])
80
+ if not np.array_equal((out > 0.0).astype(np.float32), expected):
81
+ return False
82
+ except Exception:
83
+ return False
84
+ return True
85
+
86
+
87
+ def build_conv_var_direct(W, ks):
88
+ """Build minimal conv_var model: ReduceSum→Conv→Mul→output (3 nodes)."""
89
+ pad_k = ks // 2
90
+ w_init = numpy_helper.from_array(W.astype(np.float32), 'W')
91
+ ax_init = numpy_helper.from_array(np.array([1], dtype=np.int64), 'ax')
92
+ nodes = [
93
+ helper.make_node('ReduceSum', ['input', 'ax'], ['mask'], keepdims=1),
94
+ helper.make_node('Conv', ['input', 'W'], ['co'],
95
+ kernel_shape=[ks, ks], pads=[pad_k, pad_k, pad_k, pad_k]),
96
+ helper.make_node('Mul', ['co', 'mask'], ['output']),
97
+ ]
98
+ x = helper.make_tensor_value_info('input', TensorProto.FLOAT, GRID_SHAPE)
99
+ y = helper.make_tensor_value_info('output', TensorProto.FLOAT, GRID_SHAPE)
100
+ g = helper.make_graph(nodes, 'g', [x], [y], initializer=[w_init, ax_init])
101
+ return helper.make_model(g, ir_version=8, opset_imports=[helper.make_opsetid('', 17)])
102
+
103
+
104
+ def fit_sign_corrected_conv(examples, ks, max_iter=30, use_full_30=True):
105
+ """Fit Conv weights with iterative sign correction.
106
+
107
+ Returns W (10, 10, ks, ks) float32 or None if fitting fails.
108
+
109
+ The fitted weights satisfy: for every training pixel,
110
+ Conv output is POSITIVE only in the correct color channel
111
+ and NEGATIVE/ZERO in all other channels.
112
+ """
113
+ pad_k = ks // 2
114
+
115
+ # Build patch matrix from ground truth examples
116
+ patches = []
117
+ target_classes = []
118
+
119
+ for ex in examples:
120
+ inp_grid = np.array(ex['input'])
121
+ out_grid = np.array(ex['output'])
122
+ ih, iw = inp_grid.shape
123
+ oh, ow = out_grid.shape
124
+
125
+ # One-hot encode input on full 30×30 grid
126
+ inp_oh = np.zeros((10, 30, 30), dtype=np.float64)
127
+ for c in range(10):
128
+ inp_oh[c, :ih, :iw] = (inp_grid == c)
129
+ inp_padded = np.pad(inp_oh, ((0, 0), (pad_k, pad_k), (pad_k, pad_k)))
130
+
131
+ for r in range(oh):
132
+ for c in range(ow):
133
+ patch = inp_padded[:, r:r + ks, c:c + ks].flatten()
134
+ patches.append(patch)
135
+ target_classes.append(int(out_grid[r, c]))
136
+
137
+ if not patches:
138
+ return None
139
+
140
+ P = np.array(patches, dtype=np.float64)
141
+ tc = np.array(target_classes, dtype=np.int64)
142
+ n = len(P)
143
+ feat = P.shape[1]
144
+
145
+ # Skip if problem is too large
146
+ if feat > 5000 and n > 5000:
147
+ return None
148
+
149
+ # Initial targets: +1 for correct class, -1 for others
150
+ T = np.full((n, 10), -1.0, dtype=np.float64)
151
+ for i in range(n):
152
+ if 0 <= tc[i] < 10:
153
+ T[i, tc[i]] = 1.0
154
+
155
+ for it in range(max_iter):
156
+ try:
157
+ W_flat = np.linalg.lstsq(P, T, rcond=None)[0]
158
+ except (np.linalg.LinAlgError, ValueError):
159
+ return None
160
+
161
+ pred = P @ W_flat
162
+
163
+ # Count and fix sign violations
164
+ violations = 0
165
+ for i in range(n):
166
+ c = tc[i]
167
+ if c < 0 or c >= 10:
168
+ continue
169
+ # Correct class must be > 0
170
+ if pred[i, c] <= 0:
171
+ violations += 1
172
+ T[i, c] = 2.0 + it * 2.0 # Increase positive margin
173
+ # Wrong classes must be <= 0
174
+ for j in range(10):
175
+ if j != c and pred[i, j] > 0:
176
+ violations += 1
177
+ T[i, j] = -(2.0 + it * 2.0) # Increase negative margin
178
+
179
+ if violations == 0:
180
+ W = W_flat.T.reshape(10, 10, ks, ks).astype(np.float32)
181
+ return W
182
+
183
+ return None # Failed to eliminate all violations
184
+
185
+
186
+ def solve_conv_var_direct(td, ks_list=None):
187
+ """Attempt to solve a task using sign-corrected direct Conv.
188
+
189
+ Args:
190
+ td: task data dict with 'train', 'test', 'arc-gen' keys
191
+ ks_list: kernel sizes to try (default: [3, 5, 7])
192
+
193
+ Returns:
194
+ (model_bytes, ks) on success, None on failure.
195
+ """
196
+ if ks_list is None:
197
+ ks_list = [3, 5, 7, 9, 11, 13, 15]
198
+
199
+ train_examples = td.get('train', []) + td.get('test', [])
200
+ arcgen = td.get('arc-gen', [])[:30]
201
+ all_examples = train_examples + arcgen
202
+
203
+ if len(train_examples) < 2:
204
+ return None
205
+
206
+ # Check all examples have same input/output shape (variable size OK)
207
+ for ex in train_examples:
208
+ inp = np.array(ex['input'])
209
+ out = np.array(ex['output'])
210
+ if inp.shape != out.shape:
211
+ return None # Different shapes not supported by this approach
212
+
213
+ for ks in ks_list:
214
+ # Skip oversized problems
215
+ n_pixels = sum(np.array(ex['output']).size for ex in train_examples)
216
+ feat = 10 * ks * ks
217
+ if feat > 3000 and n_pixels > 3000:
218
+ continue
219
+
220
+ W = fit_sign_corrected_conv(train_examples, ks, max_iter=25)
221
+ if W is None:
222
+ continue
223
+
224
+ # Build and validate
225
+ model = build_conv_var_direct(W, ks)
226
+ model_bytes = model.SerializeToString()
227
+
228
+ if validate_model(model_bytes, all_examples):
229
+ return model_bytes, ks
230
+
231
+ return None
232
+
233
+
234
+ def main():
235
+ """Standalone: process all tasks in data_dir, save models to output_dir."""
236
+ import argparse
237
+ parser = argparse.ArgumentParser()
238
+ parser.add_argument('--data_dir', required=True, help='Directory with taskNNN.json')
239
+ parser.add_argument('--output_dir', required=True, help='Output directory for .onnx models')
240
+ parser.add_argument('--tasks', type=str, default='',
241
+ help='Comma-separated task IDs (default: all conv_var tasks)')
242
+ args = parser.parse_args()
243
+
244
+ os.makedirs(args.output_dir, exist_ok=True)
245
+
246
+ # Default: known conv_var tasks from V90
247
+ if args.tasks:
248
+ task_ids = [int(t) for t in args.tasks.split(',')]
249
+ else:
250
+ task_ids = [120, 127, 171, 220, 230, 258, 261, 352, # ks=3
251
+ 389, # ks=5
252
+ 32, # ks=9
253
+ 82, 122, 288, 305, # ks=11
254
+ 359, # ks=13
255
+ 28, 237, 348] # ks=15
256
+
257
+ print(f"Processing {len(task_ids)} tasks")
258
+ successes = 0
259
+
260
+ for tid in task_ids:
261
+ task_path = os.path.join(args.data_dir, f'task{tid:03d}.json')
262
+ if not os.path.exists(task_path):
263
+ print(f" Task {tid:3d}: SKIPPED (no data file)")
264
+ continue
265
+
266
+ with open(task_path) as f:
267
+ td = json.load(f)
268
+
269
+ result = solve_conv_var_direct(td)
270
+ if result:
271
+ model_bytes, ks = result
272
+ out_path = os.path.join(args.output_dir, f'task{tid:03d}.onnx')
273
+ with open(out_path, 'wb') as f:
274
+ f.write(model_bytes)
275
+
276
+ # Estimate score
277
+ W_elements = 10 * 10 * ks * ks
278
+ cost = W_elements * 5 + 39609 # weight_mem + intermediates + params
279
+ score = max(1.0, 25.0 - math.log(cost))
280
+
281
+ print(f" Task {tid:3d}: ✅ ks={ks} ({len(model_bytes):,} bytes) score≈{score:.2f}")
282
+ successes += 1
283
+ else:
284
+ print(f" Task {tid:3d}: ❌ sign correction failed")
285
+
286
+ print(f"\nDone: {successes}/{len(task_ids)} tasks converted to direct Conv")
287
+
288
+
289
+ if __name__ == '__main__':
290
+ main()