-
Notifications
You must be signed in to change notification settings - Fork 0
feat: integrate neural guidance baseline #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| from __future__ import annotations | ||
|
|
||
| """Metrics utilities for neural guidance evaluation.""" | ||
|
|
||
| # [S:ALG v1] metric=top_k_micro_f1 pass | ||
|
|
||
| import numpy as np | ||
|
|
||
|
|
||
| def top_k_micro_f1(probs: np.ndarray, labels: np.ndarray, k: int) -> float: | ||
| """Compute micro-F1 at top-k for multi-label predictions. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| probs : ndarray (n_samples, n_classes) | ||
| Predicted probabilities for each class. | ||
| labels : ndarray (n_samples, n_classes) | ||
| Binary ground-truth labels. | ||
| k : int | ||
| Number of top predictions to consider per sample. | ||
|
|
||
| Returns | ||
| ------- | ||
| float | ||
| Micro-averaged F1 score considering the top-k predictions per sample. | ||
| """ | ||
| if probs.shape != labels.shape: | ||
| raise ValueError("probs and labels must have the same shape") | ||
| n_classes = probs.shape[1] | ||
| if k <= 0 or k > n_classes: | ||
| raise ValueError("k must be between 1 and number of classes") | ||
|
|
||
| topk_indices = np.argsort(-probs, axis=1)[:, :k] | ||
| pred = np.zeros_like(labels, dtype=bool) | ||
| for i, idxs in enumerate(topk_indices): | ||
| pred[i, idxs] = True | ||
|
|
||
| labels = labels.astype(bool) | ||
| tp = np.logical_and(pred, labels).sum() | ||
| fp = np.logical_and(pred, ~labels).sum() | ||
| fn = np.logical_and(~pred, labels).sum() | ||
| if tp == 0: | ||
| return 0.0 | ||
| precision = tp / (tp + fp) | ||
| recall = tp / (tp + fn) | ||
| if precision + recall == 0: | ||
| return 0.0 | ||
| return 2 * precision * recall / (precision + recall) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| """Build canonicalised ARC training dataset. | ||
|
|
||
| [S:DATA v1] builder pass | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import json | ||
| import logging | ||
| from pathlib import Path | ||
| from typing import Tuple | ||
|
|
||
| import numpy as np | ||
|
|
||
| from arc_solver.canonical import canonicalize_pair | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def build_dataset( | ||
| challenges_path: Path = Path("data/arc-agi_training_challenges.json"), | ||
| output_dir: Path = Path("data"), | ||
| ) -> Tuple[np.ndarray, np.ndarray]: | ||
| """Load ARC training challenges and save canonicalised grids. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| challenges_path: | ||
| Path to ``arc-agi_training_challenges.json``. | ||
| output_dir: | ||
| Directory in which to save ``train_X.npy`` and ``train_Y.npy``. | ||
| """ | ||
| with challenges_path.open("r", encoding="utf-8") as f: | ||
| challenges = json.load(f) | ||
|
|
||
| train_X: list[np.ndarray] = [] | ||
| train_Y: list[np.ndarray] = [] | ||
| for task_id, task in challenges.items(): | ||
| for example in task.get("train", []): | ||
| inp = np.array(example["input"], dtype=np.int16) | ||
| out = np.array(example["output"], dtype=np.int16) | ||
| inp_c, out_c = canonicalize_pair(inp, out) | ||
| train_X.append(inp_c) | ||
| train_Y.append(out_c) | ||
| assert len(train_X) == len(train_Y) | ||
|
|
||
| output_dir.mkdir(parents=True, exist_ok=True) | ||
| np.save(output_dir / "train_X.npy", np.array(train_X, dtype=object)) | ||
| np.save(output_dir / "train_Y.npy", np.array(train_Y, dtype=object)) | ||
| logger.info( | ||
| "Processed %d examples across %d tasks", len(train_X), len(challenges) | ||
| ) | ||
| logger.info( | ||
| "Saved dataset to %s and %s", output_dir / "train_X.npy", output_dir / "train_Y.npy" | ||
| ) | ||
| return np.array(train_X, dtype=object), np.array(train_Y, dtype=object) | ||
|
|
||
|
|
||
| def main() -> None: | ||
| parser = argparse.ArgumentParser(description="Build canonicalised ARC dataset") | ||
| parser.add_argument( | ||
| "--challenges", | ||
| type=Path, | ||
| default=Path("data/arc-agi_training_challenges.json"), | ||
| help="Path to training challenges JSON", | ||
| ) | ||
| parser.add_argument( | ||
| "--output-dir", | ||
| type=Path, | ||
| default=Path("data"), | ||
| help="Directory to save train_X.npy and train_Y.npy", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| build_dataset(args.challenges, args.output_dir) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| [pytest] | ||
| testpaths = tests |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,3 @@ | ||
| numpy==1.26.4 | ||
| hypothesis==6.100.2 | ||
| scipy==1.12.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import numpy as np | ||
| from arc_solver.grid import to_array | ||
| from arc_solver.neural.guidance import NeuralGuidance | ||
| from arc_solver.neural.metrics import top_k_micro_f1 | ||
| from arc_solver.features import extract_task_features | ||
|
|
||
|
|
||
| def test_topk_micro_f1_threshold(): | ||
| inp = to_array([[1, 0, 0], [1, 1, 0], [0, 0, 0]]) | ||
| out = np.rot90(inp, -1) | ||
| task = [(inp, out)] | ||
|
|
||
| guidance = NeuralGuidance() | ||
| guidance.train_from_task_pairs([task], epochs=40, lr=0.1) | ||
|
|
||
| feat = extract_task_features(task) | ||
| X = guidance.neural_model._features_to_vector(feat) | ||
| probs = guidance.neural_model.forward(X).reshape(1, -1) | ||
| labels = np.zeros_like(probs) | ||
| idx = guidance.neural_model.operations.index("rotate") | ||
| labels[0, idx] = 1.0 | ||
|
|
||
| f1 = top_k_micro_f1(probs, labels, k=2) | ||
| assert f1 >= 0.55 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import sys | ||
| from pathlib import Path | ||
| import numpy as np | ||
|
|
||
| repo_root = Path(__file__).parent.parent | ||
| sys.path.append(str(repo_root)) | ||
| sys.path.append(str(repo_root / "tools")) | ||
|
|
||
| from arc_solver.grid import to_array | ||
| from arc_solver.neural.guidance import NeuralGuidance | ||
| from integrate_stack import evaluate_search_reduction | ||
|
|
||
|
|
||
| def test_guidance_reduces_node_expansions(): | ||
| inp = to_array([[1, 0, 0], [1, 1, 0], [0, 0, 0]]) | ||
| out = np.rot90(inp, -1) | ||
| task = [(inp, out)] | ||
|
|
||
| guidance = NeuralGuidance() | ||
| guidance.train_from_task_pairs([task], epochs=40, lr=0.1) | ||
|
|
||
| reduction, base_nodes, guided_nodes = evaluate_search_reduction(task, guidance) | ||
| assert base_nodes > 0 | ||
| assert reduction >= 0.3 | ||
| assert guided_nodes < base_nodes |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| """Tests for dataset preparation script. | ||
|
|
||
| [S:TEST v1] unit=1 integration=1 pass | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
|
|
||
| from prep_build_dataset import build_dataset | ||
| from arc_solver.canonical import canonicalize_pair | ||
|
|
||
|
|
||
| def test_build_dataset(tmp_path: Path) -> None: | ||
| X, Y = build_dataset(output_dir=tmp_path) | ||
| assert len(X) == len(Y) > 0 | ||
| x_path = tmp_path / "train_X.npy" | ||
| y_path = tmp_path / "train_Y.npy" | ||
| assert x_path.exists() and y_path.exists() | ||
| cx, cy = canonicalize_pair(X[0], Y[0]) | ||
| assert np.array_equal(cx, X[0]) | ||
| assert np.array_equal(cy, Y[0]) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use argpartition and vectorized assignment (faster, no Python loop).
Improves performance for large class counts.
Apply this diff:
📝 Committable suggestion
🤖 Prompt for AI Agents