-
Notifications
You must be signed in to change notification settings - Fork 5
[WIP] Hard reasoning #102
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
Open
rlebras
wants to merge
27
commits into
allenai:main
Choose a base branch
from
rlebras:hard_reasoning
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
[WIP] Hard reasoning #102
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
23f9dcd
Init
rlebras 2be29eb
Longer context
rlebras 6b2102d
Chat without backend
rlebras e1931dc
Merge branch 'main' of https://github.com/allenai/olmo-eval-internal …
rlebras e6a84ad
Merge branch 'main' of https://github.com/allenai/olmo-eval-internal …
rlebras 92f2b46
HardReasoning scorer based on verifier instead of gold answer
rlebras 08b67f3
merging conflicts
rlebras eb38117
Adding unit tests for _extract_last_complete_json per PR review
rlebras 996e276
Pinning np hard reasoning to a specific commit, per PR review
rlebras 3195b9a
add num_instances=4 directly to the model preset
rlebras bd9ba5f
reverting model preset
rlebras 16f1a98
injecting HF token
rlebras f023041
streaming hf ds
rlebras 8f4e994
hf hub
rlebras a25bc92
task dependencies
rlebras f613ef1
vLLM and chat
rlebras 52b8c3a
olmo-3-7b-instruct
rlebras b716ef3
parse_rate
rlebras cfd2d43
olmo 3.1 32B instruct preset
rlebras 455298c
qwen3 VL 32B instruct preset
rlebras b8659f8
qwen3 32B instruct preset
rlebras e565f01
gemma, olmo3-think, r1-32B
rlebras cdf35fb
qwen3-32B
rlebras 555bda9
r1-qwen3-8b
rlebras 3f9b903
gpt-oss-20b
rlebras 349b91c
task split
rlebras 1465f0b
new data format
rlebras 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,223 @@ | ||
| """HardReasoning evaluation tasks. | ||
|
|
||
| Logic puzzles and reasoning tasks that require multi-step constraint satisfaction. | ||
|
|
||
| Dataset: allenai/hard-reasoning | ||
|
|
||
| Usage: | ||
| olmo-eval run -m my-model -t hard_reasoning_bringing_toys | ||
| olmo-eval run -m my-model -t hard_reasoning_bringing_toys:chat | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import sys | ||
| from collections.abc import Iterator | ||
| from dataclasses import dataclass | ||
| from typing import Any | ||
|
|
||
| from olmo_eval.common.formatters import ChatFormatter | ||
| from olmo_eval.common.metrics import AccuracyMetric | ||
| from olmo_eval.common.scorers import Scorer | ||
| from olmo_eval.common.types import Instance, LMOutput, LMRequest, RequestType, SamplingParams, Split | ||
| from olmo_eval.evals.tasks.common import Task, register, register_variant | ||
|
|
||
| HARD_REASONING_TASKS: tuple[str, ...] = ( | ||
| "bringing_toys", | ||
| "classroom_assignment", | ||
| "dinner_party", | ||
| "expense_splitting", | ||
| "printing_jobs", | ||
| "secret_santa", | ||
| "social_gathering", | ||
| "wedding_planning", | ||
| "wedding_supplies", | ||
| ) | ||
|
|
||
|
|
||
| def _extract_last_complete_json(s: str) -> dict | None: | ||
| """Extract the last complete JSON object from a string.""" | ||
| stack: list[int] = [] | ||
| last_json_start: int | None = None | ||
| last_json_str: str | None = None | ||
| for i, char in enumerate(s): | ||
| if char == "{": | ||
| stack.append(i) | ||
| if last_json_start is None: | ||
| last_json_start = i | ||
| elif char == "}": | ||
| if stack: | ||
| stack.pop() | ||
| if not stack: | ||
| last_json_str = s[last_json_start : i + 1] | ||
| last_json_start = None | ||
| if last_json_str: | ||
| try: | ||
| return json.loads(last_json_str.replace("\n", "")) | ||
| except json.JSONDecodeError: | ||
| pass | ||
| return None | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class HardReasoningParsedScorer(Scorer): | ||
| """Score 1.0 if the model output was parsed as valid JSON, else 0.0.""" | ||
|
|
||
| name: str = "parsed" | ||
|
|
||
| def score(self, instance: Instance, output: LMOutput) -> float: | ||
| if output.extracted_answer is None: | ||
| return 0.0 | ||
| try: | ||
| json.loads(output.extracted_answer) | ||
| return 1.0 | ||
| except (json.JSONDecodeError, TypeError): | ||
| return 0.0 | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class HardReasoningScorer(Scorer): | ||
| """Score using the np_hard_reasoning check() function.""" | ||
|
|
||
| name: str = "hard_reasoning_check" | ||
|
|
||
| def score(self, instance: Instance, output: LMOutput) -> float: | ||
| from np_hard_reasoning.scenarios.registry import SCENARIO_REGISTRY | ||
|
|
||
| if output.extracted_answer is None: | ||
| return 0.0 | ||
| subset = instance.metadata.get("subset", "") | ||
| scenario_cls = SCENARIO_REGISTRY.get(subset) | ||
| if scenario_cls is None: | ||
| return 0.0 | ||
| try: | ||
| scenario = scenario_cls.load_from_json(instance.metadata["scenario_data"]) | ||
| return 1.0 if scenario.check_json(str(output.extracted_answer)) else 0.0 | ||
| except Exception: | ||
| return 0.0 | ||
|
|
||
|
|
||
| class HardReasoningBase(Task): | ||
| """Base class for HardReasoning logic puzzle tasks. | ||
|
|
||
| Each subtask loads from a specific subset of the allenai/hard-reasoning dataset, | ||
| where files are organized as {subset}/dev_t1.jsonl and {subset}/test_t1.jsonl. | ||
| """ | ||
|
|
||
| subset: str = "bringing_toys" | ||
| dependencies = [ | ||
| "git+https://github.com/allenai/np-hard-reasoning.git@fa8bbb2a5554e34a7ce051b71e9357e44dbabd0f", | ||
| "z3-solver", | ||
| "networkx", | ||
| ] | ||
| sampling_params = SamplingParams( | ||
| max_tokens=4096, | ||
| temperature=0.0, | ||
| stop_sequences=("\n\n",), | ||
| ) | ||
| metrics = ( | ||
| AccuracyMetric(scorer=HardReasoningScorer), | ||
| AccuracyMetric(name="parse_rate", scorer=HardReasoningParsedScorer), | ||
| ) | ||
|
|
||
| @property | ||
| def instances(self) -> Iterator[Instance]: | ||
| if self._instances_cache is None: | ||
| self._instances_cache = list(self._load_hard_reasoning_split(self.config.split)) | ||
| yield from self._instances_cache | ||
|
|
||
| def _load_hard_reasoning_split(self, split: str) -> Iterator[Instance]: | ||
| """Load instances from a specific split of the hard-reasoning dataset.""" | ||
| import json | ||
| import os | ||
|
|
||
| from huggingface_hub import hf_hub_download | ||
|
|
||
| file_name = "dev_t1.jsonl" if split == "validation" else "test_t1.jsonl" | ||
| local_path = hf_hub_download( | ||
| repo_id="allenai/hard-reasoning", | ||
| filename=f"{self.subset}/{file_name}", | ||
| repo_type="dataset", | ||
| token=os.environ.get("HF_TOKEN"), | ||
| ) | ||
| with open(local_path) as f: | ||
| for index, line in enumerate(f): | ||
| doc = json.loads(line) | ||
| instance = self.process_doc(doc, index) | ||
| if instance is not None: | ||
| yield instance | ||
|
|
||
| def process_doc(self, doc: dict[str, Any], index: int = 0) -> Instance | None: | ||
| return Instance( | ||
| question=doc["prompt"], | ||
| metadata={ | ||
| "id": doc.get("id", index), | ||
| "scenario_data": doc["instance"], | ||
| "subset": self.subset, | ||
| }, | ||
| ) | ||
|
|
||
| def format_request(self, instance: Instance) -> LMRequest: | ||
| if self.config.formatter is not None: | ||
| return self.config.formatter.format(instance, self.get_fewshot()) | ||
| return LMRequest( | ||
| request_type=RequestType.COMPLETION, | ||
| prompt=instance.question, | ||
| ) | ||
|
|
||
| def extract_answer(self, output: LMOutput) -> str | None: | ||
| """Extract the last complete JSON object from the model's response.""" | ||
| json_obj = _extract_last_complete_json(output.text) | ||
| if json_obj is not None: | ||
| return json.dumps(json_obj) | ||
| return output.text.strip() or None | ||
|
|
||
| def _build_fewshot(self) -> list[Instance]: | ||
| """Build few-shot examples from the dev split.""" | ||
| import random | ||
|
|
||
| if self.config.num_fewshot == 0: | ||
| return [] | ||
| all_instances = list(self._load_hard_reasoning_split("validation")) | ||
| if not all_instances: | ||
| return [] | ||
| rng = random.Random(self.config.fewshot_seed) | ||
| return rng.sample(all_instances, min(self.config.num_fewshot, len(all_instances))) | ||
|
|
||
|
|
||
| # ============================================================================= | ||
| # Task Registration | ||
| # ============================================================================= | ||
|
|
||
| for _subset in HARD_REASONING_TASKS: | ||
| _task_name = f"hard_reasoning_{_subset}" | ||
| _class_name = f"HardReasoning_{_subset.title().replace('_', '')}" | ||
| _cls = type( | ||
| _class_name, | ||
| (HardReasoningBase,), | ||
| { | ||
| "subset": _subset, | ||
| "__module__": __name__, | ||
| "__qualname__": _class_name, | ||
| }, | ||
| ) | ||
| setattr(sys.modules[__name__], _class_name, _cls) | ||
| register(_task_name)(_cls) | ||
| register_variant( | ||
| _task_name, | ||
| "chat", | ||
| formatter=ChatFormatter(), | ||
| sampling_params=SamplingParams(max_tokens=32768, temperature=0.0), | ||
| ) | ||
| register_variant( | ||
| _task_name, | ||
| "dev", | ||
| split=Split.VALIDATION, | ||
| ) | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "HARD_REASONING_TASKS", | ||
| "HardReasoningBase", | ||
| ] | ||
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,30 @@ | ||
| """Tests for HardReasoning task logic.""" | ||
|
|
||
| from olmo_eval.evals.tasks.hard_reasoning import _extract_last_complete_json | ||
|
|
||
|
|
||
| class TestExtractLastCompleteJson: | ||
| def test_simple_json(self): | ||
| assert _extract_last_complete_json('{"a": 1}') == {"a": 1} | ||
|
|
||
| def test_json_after_text(self): | ||
| assert _extract_last_complete_json('Some text {"key": "value"}') == {"key": "value"} | ||
|
|
||
| def test_returns_last_json(self): | ||
| result = _extract_last_complete_json('{"first": 1} some text {"second": 2}') | ||
| assert result == {"second": 2} | ||
|
|
||
| def test_nested_json(self): | ||
| assert _extract_last_complete_json('{"outer": {"inner": 42}}') == {"outer": {"inner": 42}} | ||
|
|
||
| def test_json_with_newlines(self): | ||
| assert _extract_last_complete_json('{"a":\n1}') == {"a": 1} | ||
|
|
||
| def test_no_json_returns_none(self): | ||
| assert _extract_last_complete_json("no json here") is None | ||
|
|
||
| def test_incomplete_json_returns_none(self): | ||
| assert _extract_last_complete_json('{"incomplete": ') is None | ||
|
|
||
| def test_empty_string_returns_none(self): | ||
| assert _extract_last_complete_json("") is None |
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.
Might be worth adding a test for any custom extraction logic like this. It can be lightweight.