Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/gsm8k/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 stein-wang0226

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
31 changes: 31 additions & 0 deletions src/gsm8k/PARITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Proposed GSM8K parity run

Both sides use one independent Chat Completions request with identical settings, no system message and no tools. The user message contains the pinned question followed by the shared completion-format instruction. The Harbor agent removes the task's file-writing wrapper before making that request. The original runner applies OpenAI's pinned scorer to the full completion. The Harbor agent preserves its own completion, extracts the first answer with the pinned extractor, and puts it in `/app/output/answer.txt` for the independent verifier. Record the shared prompt and transport in the experiment notes. The original repository's example checkpoint sampler supports a calculator, so this proposed comparison requires agreement on the shared no-tools protocol.

The eight-task sanity cohort is committed in `parity-smoke-ids.txt`. The proposed scored cohort is the full official test split, 1,319 tasks. Execute both sanity runs, one complete pair, then two additional complete pairs. Keep source rows, model revision, sampling, budget, and tooling fixed. Use a unique output directory and job name for each repetition.

From the adapters repository root, prepare the exact inputs.

```bash
mkdir -p runs/gsm8k-parity
revision=3101c7d5072418e28b9008a6636bde82a006892c
upstream="https://raw.githubusercontent.com/openai/grade-school-math/$revision/grade_school_math"
curl -fsS "$upstream/data/test.jsonl" -o runs/gsm8k-parity/test.jsonl
curl -fsS "$upstream/dataset.py" -o runs/gsm8k-parity/dataset.py
ids="$(paste -sd, src/gsm8k/parity-smoke-ids.txt)"
uv run --project src/gsm8k --locked gsm8k --split parity \
--source runs/gsm8k-parity/test.jsonl --task-ids "$ids" \
--output-dir datasets/gsm8k-parity-smoke
```

Create `runs/gsm8k-parity/profile.json` with the approved `model`, `temperature`, `max_completion_tokens` and `timeout_seconds`. Allow time for the answer write within the task's 60-second agent deadline. Provide `GSM8K_PARITY_BASE_URL` ending at the Chat Completions API prefix and `GSM8K_PARITY_API_KEY` in the host environment. Keep both sides on the same endpoint. The runner checks the returned model revision and records the raw completion, request SHA-256, finish reason and available usage. Credentials stay in the environment.

```bash
uv run --project src/gsm8k --locked python -m gsm8k.parity \
--source runs/gsm8k-parity/test.jsonl --scorer runs/gsm8k-parity/dataset.py \
--profile runs/gsm8k-parity/profile.json --task-ids "$ids" \
--output runs/gsm8k-parity/original-sanity.jsonl
uv run --project src/gsm8k --locked harbor run -c src/gsm8k/parity-config.example.yaml
```

For the full test cohort, generate with `--split test` and omit `--task-ids` from the original runner. Point the Harbor config at the complete test directory. Compare prompt hashes and match source rows before scoring. Calculate each run from the full cohort. Keep model errors and verifier errors separately from scored responses. Compute mean ± sample SEM and compare the two raw score ranges. Fill in the official parity JSON and README table after scores and real PR URLs exist.
88 changes: 88 additions & 0 deletions src/gsm8k/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# GSM8K for Harbor

## Overview

Generate Harbor tasks from OpenAI's original GSM8K train and test splits with fixed source and image revisions.

## What is GSM8K?

GSM8K is a set of English grade-school math problems. The source contains 7,473 train and 1,319 test examples. [OpenAI dataset source](https://github.com/openai/grade-school-math/tree/3101c7d5072418e28b9008a6636bde82a006892c)

## Adapter Features

- Preserve the original question, source row, and gold answer.
- Run a non-root agent and a separate offline verifier.
- Build a dataset manifest with Harbor Registry names and content digests.

## Generated Task Structure

Each task includes `task.toml`, `instruction.md`, `environment/Dockerfile`, `solution/solve.sh`, and `tests/`. The dataset directory includes `dataset.toml` and a source manifest.

## Installation / Prerequisites

Install `uv`, Python 3.12, and a functioning Docker or Podman backend. The adapter pins Harbor 0.27.0.

## Usage

From this adapter directory, run:

```bash
uv run gsm8k --output-dir ../../datasets/gsm8k-test
uv run gsm8k --split train --output-dir ../../datasets/gsm8k-train
```

Use `--source` for a local copy of the pinned input. Use `--limit` or `--task-ids` for a deterministic subset. Use `--split parity --task-ids ...` to generate an explicitly selected test subset. Use `--overwrite` to replace an existing adapter output.

## Run Evaluation

The proposed Registry identifiers are `gsm8k/gsm8k-test` and `gsm8k/gsm8k-train`. Registry commands become available after the maintainers register the datasets.

From the repository root, run `uv run --project src/gsm8k --locked harbor run -c src/gsm8k/run_gsm8k.yaml` against the generated test tasks. For train, use `uv run --project src/gsm8k --locked harbor run --path datasets/gsm8k-train --agent oracle --env docker`.

## Comparison with Original Benchmark

The native control suite checked 17,590 submissions against the pinned OpenAI scorer. The matched-model experiment is proposed. Its agent, precise model revision and budget are subject to maintainer coordination.

Prepare the eight-task sanity cohort with the command below. These zero-based source rows are spaced from row 0 to row 1318 across the fixed test split. The proposed scored experiment uses the full 1,319-task test split.

```bash
uv run --project src/gsm8k --locked gsm8k --split parity \
--task-ids "$(paste -sd, src/gsm8k/parity-smoke-ids.txt)" \
--output-dir datasets/gsm8k-parity-smoke
```

The original repository supplies the task data, first-marker answer extractor, and an example checkpoint sampler with calculator support. The proposed paired runner uses the same model prompt, single-turn configuration, and tool policy on both sides. The original side scores each raw completion with the pinned `is_correct`. A Harbor-compatible agent makes a separate model request and transports the extracted answer to the native verifier. The proposed shared-agent comparison covers this file transport and grading path. A standard terminal agent would require its own matched system configuration and score table.

### Eight-task sanity

Using two independent requests per task with `gpt-4.1-mini-2025-04-14` and identical payloads, the original scorer awarded 8/8 and native Harbor 0.27.0 on Podman awarded 7/8. The Harbor verifier matched the pinned original scorer when both scored each of the eight Harbor-side responses. For `gsm8k-test-0753`, the original response gave `128`, while the Harbor-side response ended with `#### 86 glasses and 42 plates`. The shared extractor returned `86` and both verifiers awarded zero to that response.

The sanity run separated the two model requests from the Harbor verifier execution. The formal paired runs await maintainer agreement on the agent, model, cohort, and run count.

See the paired harness and reproduction commands in [the proposed parity protocol](PARITY.md).

## Notes & Caveats

The Harbor prompt asks for a single number in `/app/output/answer.txt`. The verifier uses exact matching after stripping surrounding whitespace and valid thousands separators. The original completion extractor accepts answers embedded in additional text.

## Troubleshooting

For a missing reward, inspect `verifier/test-stdout.txt`, `verifier/test-stderr.txt`, and the Harbor trial result. The shell entry invokes `grade.py`, which writes `/logs/verifier/reward.txt`. The agent environment must allow UID 1001 to create `/app/output/answer.txt`.

## Citation

Karl Cobbe et al., *Training Verifiers to Solve Math Word Problems*, 2021. [Paper](https://arxiv.org/abs/2110.14168)

```bibtex
@misc{cobbe2021training,
title = {Training Verifiers to Solve Math Word Problems},
author = {Cobbe, Karl and Kosaraju, Vineet and Bavarian, Mohammad and others},
year = {2021},
eprint = {2110.14168},
archivePrefix = {arXiv}
}
```

## Authors & Contributions

Original benchmark by Karl Cobbe and co-authors. Harbor adaptation by stein-wang0226. [OpenAI license](src/gsm8k/LICENSE.openai)
26 changes: 26 additions & 0 deletions src/gsm8k/adapter_metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[
{
"adapter_name": "gsm8k",
"adapter_builders": [
"stein-wang0226 (101868035+stein-wang0226@users.noreply.github.com)"
],
"original_benchmark": [
{"split": "train", "size": 7473, "harness": "llm", "adaptable": true},
{"split": "test", "size": 1319, "harness": "llm", "adaptable": true}
],
"harbor_adapter": [
{
"split": "full",
"adapted_benchmark_size": 8792,
"parity_benchmark_size": 0,
"parity_sampling_rate": 0,
"registry_benchmark_size": 0,
"added_agents": ["gsm8k-paired-chat@0.1.0"],
"parity_matching_agents": [],
"parity_unmatching_agents": [],
"parity_costs": null,
"notes": "Matched model parity and Harbor Registry publication are pending."
}
]
}
]
15 changes: 15 additions & 0 deletions src/gsm8k/parity-config.example.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
job_name: gsm8k-parity-smoke
jobs_dir: runs/gsm8k-parity/harbor
datasets:
- path: datasets/gsm8k-parity-smoke
agents:
- import_path: gsm8k.parity:PairedParityAgent
kwargs:
profile_path: runs/gsm8k-parity/profile.json
scorer_path: runs/gsm8k-parity/dataset.py
environment:
type: docker
n_concurrent_trials: 1
n_attempts: 1
retry:
max_retries: 0
8 changes: 8 additions & 0 deletions src/gsm8k/parity-smoke-ids.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
gsm8k-test-0000
gsm8k-test-0188
gsm8k-test-0377
gsm8k-test-0565
gsm8k-test-0753
gsm8k-test-0941
gsm8k-test-1130
gsm8k-test-1318
18 changes: 18 additions & 0 deletions src/gsm8k/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[project]
name = "harbor-gsm8k-adapter"
version = "0.2.0"
description = "Reproducible conversion of the original GSM8K dataset to Harbor"
readme = "README.md"
requires-python = ">=3.12,<3.13"
dependencies = ["harbor==0.27.0"]

[project.scripts]
gsm8k = "gsm8k.main:main"

[build-system]
requires = ["uv_build>=0.9.18,<0.10.0"]
build-backend = "uv_build"

[tool.uv.build-backend]
module-name = "gsm8k"
source-include = ["src/gsm8k/LICENSE.openai"]
10 changes: 10 additions & 0 deletions src/gsm8k/run_gsm8k.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
datasets:
- path: datasets/gsm8k-test
agents:
- name: oracle
environment:
type: docker
n_attempts: 1
n_concurrent_trials: 4
retry:
max_retries: 0
21 changes: 21 additions & 0 deletions src/gsm8k/src/gsm8k/LICENSE.openai
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 OpenAI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions src/gsm8k/src/gsm8k/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Generate and verify the GSM8K Harbor dataset."""
149 changes: 149 additions & 0 deletions src/gsm8k/src/gsm8k/acceptance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""Plan and reconcile deterministic GSM8K controls on Docker or Podman."""

from collections import defaultdict
from decimal import Decimal
from hashlib import sha256
import json

from harbor.models.job.lock import TrialLock
from harbor.models.trial.result import TrialResult
from harbor.publisher.packager import Packager

from .adapter import ANSWER_PATH, HARBOR_VERSION, read_source


def load(path):
return json.loads(path.read_bytes())


def save(path, value):
temporary = path.with_suffix(".tmp")
temporary.write_text(json.dumps(value, sort_keys=True, indent=2) + "\n", encoding="utf-8")
temporary.replace(path)


def answer_for(gold, case):
if case == "empty":
return ""
if case == "malformed":
return "not a number\n"
if case == "comma":
return f"{Decimal(gold):,}\n"
if case == "wrong":
return f"{Decimal(gold) + 1:f}\n"
if case != "oracle":
raise ValueError(f"Unknown control: {case}")
return f"{gold}\n"


def control(row, task, case):
return {
"task_name": row.task_name, "source_row": row.row,
"source_line_sha256": row.line_sha256, "task_digest": task["task_digest"],
"harbor_checksum": task["harbor_checksum"], "instruction_sha256": task["files"]["instruction.md"],
"case": case, "submission": answer_for(row.gold, case), "upstream_answer": row.upstream_answer,
"expected_reward": int(case in ("oracle", "comma")),
}


def planned_controls(dataset, source, split, extract_answer):
manifest_raw = (dataset / "manifest.json").read_bytes()
manifest = json.loads(manifest_raw)
rows = read_source(source.read_bytes(), split)
tasks = {task["task_name"]: task for task in manifest["tasks"]}
if manifest["source"]["split"] != split or list(tasks) != [row.task_name for row in rows]:
raise ValueError(f"Expected the complete {split} dataset")
for row in rows:
task = tasks[row.task_name]
if (task["source_line_sha256"] != row.line_sha256 or task["source_row"] != row.row
or extract_answer(row.upstream_answer) != row.gold):
raise ValueError(f"Source alignment failed for {row.task_name}")
format_row = next(row for row in rows if abs(Decimal(row.gold)) >= 1000)
formats = [control(format_row, tasks[format_row.task_name], case) for case in ("empty", "malformed", "comma")]
numbers = [control(row, tasks[row.task_name], case) for row in rows for case in ("oracle", "wrong")]
return sha256(manifest_raw).hexdigest(), formats + numbers


def grouped_controls(records):
cases = defaultdict(list)
for record in records:
cases[record["case"]].append(record)
return cases


def verify_payload(dataset, records):
tasks = {record["task_name"]: record["task_digest"] for record in records}
for name, digest in tasks.items():
digest_raw, _ = Packager.compute_content_hash(dataset / name)
if digest != f"sha256:{digest_raw}":
raise ValueError(f"Staged task content digest mismatch for {name}")


def trial_submission(trial_dir):
entries = load(trial_dir / "artifacts/manifest.json")
matches = [entry for entry in entries if entry["source"] == ANSWER_PATH]
if len(matches) != 1 or matches[0]["type"] != "file" or matches[0]["status"] != "ok":
raise ValueError(f"Answer collection incomplete for {trial_dir.name}")
collected = trial_dir / matches[0]["destination"]
artifact_root = (trial_dir / "artifacts").resolve()
if collected.is_symlink() or not collected.is_file() or not collected.resolve().is_relative_to(artifact_root):
raise ValueError(f"Unexpected collected submission path for {trial_dir.name}")
return collected.read_bytes()


def check_trial(trial, lock, record, provider):
phases = (trial.environment_setup, trial.agent_setup, trial.agent_execution, trial.verifier)
agent = "oracle" if record["case"] == "oracle" else "gsm8k-answer-replay"
if (trial.exception_info or not trial.finished_at or any(
not phase or not phase.started_at or not phase.finished_at or phase.finished_at < phase.started_at
for phase in phases)):
raise ValueError(f"Trial did not finish cleanly: {trial.trial_name}")
if (trial.task_name != f"gsm8k/{record['task_name']}" or lock.task.name != record["task_name"]
or lock.task.digest != record["task_digest"]
or trial.task_checksum != record["harbor_checksum"] or trial.verifier_environment_mode != "separate"
or trial.agent_info.name != agent or trial.agent_info.model_info is not None
or trial.config.environment.type != provider):
raise ValueError(f"Unexpected native trial configuration: {trial.trial_name}")


def reconcile(result_path, trial, record, provider, is_correct):
trial_dir = result_path.parent
lock = TrialLock.model_validate_json((trial_dir / "lock.json").read_bytes())
check_trial(trial, lock, record, provider)
submission = trial_submission(trial_dir)
actual_digest = sha256(submission).hexdigest()
verifier = trial_dir / "verifier"
evidence = load(verifier / "answer-evidence.json")
if evidence != {"status": "read", "bytes_read": len(submission), "sha256": actual_digest}:
raise ValueError(f"Verifier received different bytes: {trial.trial_name}")
if submission != record["submission"].encode():
raise ValueError(f"Submission differs from planned control: {trial.trial_name}")
expected = int(is_correct("#### " + submission.decode(), {"answer": record["upstream_answer"]}))
reward_bytes = (verifier / "reward.txt").read_bytes()
if (expected != record["expected_reward"] or not trial.verifier_result
or trial.verifier_result.rewards != {"reward": expected} or reward_bytes.strip() != str(expected).encode()):
raise ValueError(f"Harbor and upstream rewards differ: {trial.trial_name}")
return {key: record[key] for key in ("case", "task_name", "task_digest", "source_row", "source_line_sha256")} | {
"trial_id": str(trial.id), "provider": provider, "reward": expected,
"upstream_reward": expected, "submission_bytes": len(submission), "submission_sha256": actual_digest,
"trial_sha256": sha256(result_path.read_bytes()).hexdigest(),
"reward_sha256": sha256(reward_bytes).hexdigest(), "harbor_version": HARBOR_VERSION,
}


def collect_case(job, records, provider, is_correct):
pending = {record["task_name"]: record for record in records}
receipts, failures = [], []
for path in sorted(job.glob("*/result.json")):
trial = TrialResult.model_validate_json(path.read_bytes())
record = pending.pop(trial.task_name.removeprefix("gsm8k/"), None)
if record is None:
raise ValueError(f"Unexpected or duplicate trial: {path}")
if trial.exception_info:
failures.append({"task_name": record["task_name"], "case": record["case"],
"exception_type": trial.exception_info.exception_type, "trial_id": str(trial.id)})
else:
receipts.append(reconcile(path, trial, record, provider, is_correct))
failures.extend({"task_name": record["task_name"], "case": record["case"], "exception_type": "NoTrialResult"}
for record in pending.values())
return receipts, failures
Loading