Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 10,153 Bytes
e3a266f
 
6db0e7c
e3a266f
6db0e7c
 
 
eae0824
6db0e7c
 
e3a266f
 
 
 
 
 
 
 
 
eae0824
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6db0e7c
e3a266f
 
 
 
6db0e7c
eae0824
6db0e7c
48157bc
 
6db0e7c
e3a266f
48157bc
e3a266f
 
6db0e7c
 
 
e3a266f
 
 
 
 
 
 
6db0e7c
48157bc
e3a266f
6db0e7c
 
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6db0e7c
e3a266f
 
 
6db0e7c
e3a266f
 
 
 
 
 
 
6db0e7c
e3a266f
 
 
 
 
 
 
6db0e7c
 
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
24df058
 
 
 
 
8d461e0
 
 
 
 
 
 
 
 
 
 
 
e3a266f
 
24df058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a266f
 
 
 
 
 
24df058
 
e3a266f
 
24df058
8d461e0
 
 
 
 
 
 
24df058
e3a266f
24df058
 
 
e3a266f
 
 
 
 
24df058
e3a266f
 
24df058
e3a266f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48157bc
e3a266f
 
 
 
 
6db0e7c
 
 
 
 
 
 
 
e3a266f
 
 
 
6db0e7c
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""Regenerate s3-aggregation from its seed: `python generate.py` (Python 3.10+, no dependencies).

Writes `problems.json` and `tasks/` next to this file, replacing what is there:
- 32 problems, each 16 integers drawn uniformly from 1 to 99 (repeats allowed), from SEED;
- per problem and team size N in SIZES, a team `agg-pPP-nNN` that holds the problem's first N
  numbers, and one task per slot of it, `agg-pPP-nNN-sKK` (K = 1..N, zero-padded so that name
  order is slot order): its instruction states that slot's number, and only that one. Every
  slot of a team shares the grader and the answer. Legion runs a team with the selector
  `agg-pPP-nNN-s*`, `agents.count: N` and `naming: consecutive-id`: agent K gets slot K's task,
  and no other agent's.

check.py checks that this reproduces the committed files byte for byte.
"""

import json
import random
import shutil
from pathlib import Path

SEED = 115  # huggingface/legion#115
PROBLEMS = 32  # the paper's held-out set size
NUMBERS = 16  # per problem; a team of N holds the first N
SIZES = (1, 2, 4, 8, 16)
LOW, HIGH = 1, 99
IMAGE = "python:3.12-slim"  # public and prebuilt: HF Sandboxes need one, docker and podman too

ONES = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
        "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
        "eighteen", "nineteen"]
TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

HERE = Path(__file__).resolve().parent


def words(n: int) -> str:
    """1..99 in English words, e.g. 73 -> "seventy-three"."""
    if not LOW <= n <= HIGH:
        raise ValueError(f"{n} is outside {LOW}..{HIGH}")
    if n < 20:
        return ONES[n]
    return TENS[n // 10] + (f"-{ONES[n % 10]}" if n % 10 else "")


def problems(seed: int = SEED) -> list[list[int]]:
    rng = random.Random(seed)
    return [[rng.randint(LOW, HIGH) for _ in range(NUMBERS)] for _ in range(PROBLEMS)]


def team_name(problem: int, n: int) -> str:
    """`problem` counts from 1."""
    return f"agg-p{problem:02d}-n{n:02d}"


def task_name(problem: int, n: int, slot: int) -> str:
    """Slot `slot` (from 1) of the team: Legion's agent `agent-00K` (naming: consecutive-id)."""
    return f"{team_name(problem, n)}-s{slot:02d}"


def instruction(n: int, number: int) -> str:
    if n == 1:
        return f"""# Sort the team's private numbers

You are the only agent on this team, solving a private-information number sorting task. You
hold one private integer from 1 to 99, written in English words.

Your private number is {words(number)}.

Write `/app/answer.json` (create `/app` if needed): a JSON array holding your number's numeric
value, as digits. Then stop.
"""
    return f"""# Sort the team's private numbers

You are on a team of {n} agents solving a private-information number sorting task. Each agent
holds one private integer from 1 to 99, written in English words. You know only your own
number, and the others don't know it unless you tell them.

Your private number is {words(number)}.

The team must find all {n} numbers and list their numeric values in ascending order. Keep equal
numbers from different agents as separate entries: each agent's number appears once in the list,
even when another agent holds the same value.

1. Share your number with the team on the message board.
2. Read the board for the other participants' numbers. Note which participant each number came
   from, so that a number posted more than once is counted once.
3. Once you have one number from every participant, yourself included, write `/app/answer.json`
   (create `/app` if needed): a JSON array of the {n} integers, as digits, in ascending order.
   Then stop.

Any agent may write the full answer, and the team succeeds if at least one agent's answer is
correct. Your instructions name the other participants and explain the board's tools.
"""


def task_toml(problem: int, n: int, slot: int) -> str:
    return f"""schema_version = "1.4"

[task]
name = "HuggingFaceSwarms/{task_name(problem, n, slot)}"
version = "0.1.0"
description = "s3-aggregation: {n} agents each hold a private number; the team lists them all in ascending order."
keywords = ["multi-agent", "message-board", "s3", "aggregation"]

[metadata]
problem = {problem}
agents = {n}
slot = {slot}
seed = {SEED}

[agent]
timeout_sec = 1800

[environment]
# Prebuilt and public, with no Dockerfile: HF Sandboxes need one, and docker and podman use it
# too. Nothing task-specific is in the container: the slot's number is only in its instruction,
# and tests/ arrive only when the agent is done.
docker_image = "{IMAGE}"
cpus = 1
memory_mb = 1024

[verifier]
timeout_sec = 60
"""


TEST_SH = r"""#!/bin/bash
# Reward 1 if /app/answer.json is exactly expected.json: a JSON array of the team's integers in
# ascending order, one per agent (equal numbers kept). Anything else scores 0: a missing or
# unreadable file, invalid UTF-8 or JSON, NaN or Infinity, a non-array, strings, floats or
# booleans, a missing, extra or dropped duplicate number, and a wrong order.
# The answer counts only as a regular file of its own at exactly that path: a symlink (e.g. to
# /tests/expected.json, which arrives only now), a link anywhere on the path (a symlinked /app),
# a hardlink, a directory or a FIFO scores 0; expected.json is read the same way. Nothing here
# follows a link the agent may have left, and 0 is written before anything is checked, so a crash
# of the check also scores 0. A copy of the answer stays with the trial's results.
# Python runs isolated (-I -S): no module from the working directory, PYTHON* variables, the
# user's site or site-packages hooks (sitecustomize, usercustomize, .pth files) can replace what
# it imports. Besides bash, python3 is the only command this script runs (no dirname, mkdir or
# rm an agent could shadow on the PATH). ANSWER, EXPECTED and VERIFIER_DIR override the paths
# (no links in them), to test the grader locally.
case $0 in */*) here=${0%/*} ;; *) here=. ;; esac
export ANSWER=${ANSWER:-/app/answer.json}
export EXPECTED=${EXPECTED:-$here/expected.json}
export VERIFIER_DIR=${VERIFIER_DIR:-/logs/verifier}
[ -d "$VERIFIER_DIR" ] && echo 0 > "$VERIFIER_DIR/reward.txt"
python3 -I -S - <<'PY' || true
import json
import os
import stat

LIMIT = 1 << 20  # bytes


def read_own(path):
    # The bytes of the regular file at exactly `path`: every folder on the way is opened
    # without following a link, and so is the file (a FIFO cannot block it); one link only.
    parts = os.path.abspath(path).split("/")[1:]
    folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
    try:
        for part in parts[:-1]:
            inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)
            os.close(folder)
            folder = inner
        fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)
    finally:
        os.close(folder)
    with os.fdopen(fd, "rb") as stream:
        info = os.fstat(stream.fileno())
        if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
            raise ValueError("not a regular file of its own")
        data = stream.read(LIMIT + 1)
    if len(data) > LIMIT:
        raise ValueError("too large")
    return data


def write_new(path, text):
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644)
    with os.fdopen(fd, "w") as stream:
        stream.write(text)


def reject_constant(name):
    raise ValueError(f"{name} is not JSON")


def parse(data):
    return json.loads(data.decode("utf-8"), parse_constant=reject_constant)


verifier = os.environ["VERIFIER_DIR"]
os.makedirs(verifier, exist_ok=True)
for name in ("reward.txt", "reward.json", "answer.json"):  # never written through a link
    try:
        os.unlink(os.path.join(verifier, name))
    except FileNotFoundError:
        pass
write_new(os.path.join(verifier, "reward.txt"), "0")
valid = False
try:
    data = read_own(os.environ["ANSWER"])
    write_new(os.path.join(verifier, "answer.json"), data.decode("utf-8", "replace"))
    answer, expected = parse(data), parse(read_own(os.environ["EXPECTED"]))
    valid = (
        isinstance(answer, list)
        and all(type(x) is int for x in answer)  # not bool, float or str
        and answer == expected
    )
except Exception:  # missing, a link, not regular, invalid UTF-8 or JSON, NaN, RecursionError
    valid = False
if valid:
    write_new(os.path.join(verifier, "reward.txt"), "1")
print("reward:", 1 if valid else 0)
PY
"""


def solve_sh(answer: list[int]) -> str:
    return f"""#!/bin/bash
# Oracle: the team's answer from its own copy (not tests/), to validate the grader.
answer=${{ANSWER:-/app/answer.json}}
mkdir -p "$(dirname "$answer")"
echo '{json.dumps(answer)}' > "$answer"
"""


def write(path: Path, text: str, mode: int = 0o644) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")
    path.chmod(mode)


def generate(root: Path = HERE, seed: int = SEED) -> None:
    shutil.rmtree(root / "tasks", ignore_errors=True)
    drawn = problems(seed)
    rows = ",\n".join(f'  "p{i:02d}": {json.dumps(numbers)}' for i, numbers in enumerate(drawn, 1))
    write(root / "problems.json", f'{{"seed": {seed}, "problems": {{\n{rows}\n}}}}\n')
    for p, numbers in enumerate(drawn, 1):
        for n in SIZES:
            team = numbers[:n]
            for slot, number in enumerate(team, 1):
                task = root / "tasks" / task_name(p, n, slot)
                write(task / "instruction.md", instruction(n, number))
                write(task / "task.toml", task_toml(p, n, slot))
                write(task / "tests" / "test.sh", TEST_SH, 0o755)
                write(task / "tests" / "expected.json", json.dumps(sorted(team)) + "\n")
                write(task / "solution" / "solve.sh", solve_sh(sorted(team)), 0o755)


if __name__ == "__main__":
    generate()
    print(f"{PROBLEMS} problems x {len(SIZES)} team sizes = {PROBLEMS * len(SIZES)} teams, "
          f"{PROBLEMS * sum(SIZES)} tasks, one per slot (seed {SEED})")