AdithyaSK HF Staff commited on
Commit
9144e91
·
verified ·
1 Parent(s): 4de8125

Review fixes: bounded custom resets, clear errors, deduped train deals

Browse files
README.md CHANGED
@@ -50,10 +50,18 @@ Both hands are in the `video` split, as he played them.
50
  | `three-digit` | 6 | 100–999 | A step between 24 and the year. |
51
  | `year` | 8 | 1900–2100 | The play page and a bare `reset()` use the current year, as in the video. |
52
  | `four-digit` | 9 | 1000–9999 | "Give me your favourite four-digit number". |
53
- | custom | 4–9 | any up to 1,000,000 | `reset(target=6843)`; card count by size unless `n_cards` is given. |
54
 
55
  Cards come from one 52-card deck, so a value appears at most four times. Every generated deal is checked
56
- with the solver and redealt until it has a solution, so a task is never impossible.
 
 
 
 
 
 
 
 
57
 
58
  ## Episode
59
 
@@ -66,13 +74,16 @@ step(CardAction(expression="...")) -> reward, result, a reference solution (
66
 
67
  | Argument | Meaning |
68
  |---|---|
69
- | `split`, `index` | A fixed task from `train` (4,000), `test` (200) or `video` (2). Without `index`, a random one. |
70
  | `level` | A fresh deal at that level. |
71
  | `target`, `n_cards` | A fresh deal for your own number. |
72
- | `cards` + `target` | Your own hand, as values 1–13. It may have no solution. |
73
  | `seed` | Makes a fresh deal reproducible. |
74
  | `reward_mode` | `shaped` (default) or `binary`. |
75
 
 
 
 
76
  The observation carries `prompt` and `system_prompt`, the exact text a model reads. The answer goes in
77
  `CardAction.expression`; an empty expression gives up. After the step, the observation adds `result`
78
  (the grader's report), `solution` and `solution_steps` (one way to make the target, one combination
@@ -83,14 +94,14 @@ per line), and `elapsed_s`. The reference solution is never shown before the epi
83
  | Answer | Reward |
84
  |---|---|
85
  | Uses every card once and equals the target | 1.0 |
86
- | Uses every card once, within 10% of the target (shaped mode) | `0.3 × c²`, `c = 1 − |value − target| / (0.1 × target)` |
87
  | Anything else: no answer, parse error, division by zero, a missing or extra card | 0 |
88
 
89
  The grader parses the expression with Python's `ast`, allows only non-negative integers, + − × ÷ and
90
  parentheses, compares the multiset of numbers to the cards, and evaluates with exact fractions. × ÷ −
91
- and the letters A J Q K are accepted; anything after `=` is ignored. Partial credit keeps a GRPO group of
92
- near misses from all scoring 0, and is capped far below an exact answer, so getting close never pays
93
- more than getting it right.
94
 
95
  ## Use it
96
 
@@ -135,7 +146,7 @@ pytest
135
 
136
  ## Evaluations
137
 
138
- `eval/rollout.py` in the [FineEnvs repository](https://github.com/adithya-s-k/FineEnvs/tree/main/12-scott-wu-math)
139
  runs OpenAI, Anthropic and open models on Hugging Face Inference Providers against a running server, in
140
  parallel, one OpenEnv session per episode.
141
 
 
50
  | `three-digit` | 6 | 100–999 | A step between 24 and the year. |
51
  | `year` | 8 | 1900–2100 | The play page and a bare `reset()` use the current year, as in the video. |
52
  | `four-digit` | 9 | 1000–9999 | "Give me your favourite four-digit number". |
53
+ | custom | 2–9 | 0–9,999 | `reset(target=6843)`; card count by size (4–9) unless `n_cards` (2–9) is given. |
54
 
55
  Cards come from one 52-card deck, so a value appears at most four times. Every generated deal is checked
56
+ with the solver and redealt until it has a solution, so a task is never impossible. The server gives the
57
+ solver 1 s per deal and 3 s per reset; a custom target it cannot deal in that time is refused.
58
+
59
+ The fixed splits come from `scripts/build_tasks.py`. `test` is 50 deals per level (seed 2026). `train` is
60
+ 1,000 draws per level (seed 7), minus every draw that repeats a test deal or an earlier train deal in what
61
+ grading sees, the target and the card values: 639 deals remain at level 24, where only 1,362 four-card
62
+ hands can make 24, and 1,000 at each other level. `test` is kept as first built, since the results below
63
+ were computed on it, so it still has two pairs of level-24 deals with the same values (`test-24-0008` and
64
+ `test-24-0023`, `test-24-0011` and `test-24-0013`).
65
 
66
  ## Episode
67
 
 
74
 
75
  | Argument | Meaning |
76
  |---|---|
77
+ | `split`, `index` | A fixed task from `train` (3,639), `test` (200) or `video` (2). Without `index`, a random one. |
78
  | `level` | A fresh deal at that level. |
79
  | `target`, `n_cards` | A fresh deal for your own number. |
80
+ | `cards` + `target` | Your own hand of 2–9 cards, as values 1–13. It may have no solution. |
81
  | `seed` | Makes a fresh deal reproducible. |
82
  | `reward_mode` | `shaped` (default) or `binary`. |
83
 
84
+ A reset the server cannot deal (an unknown split or level, an `index` outside the split, a target above
85
+ 9,999, more than nine cards) is refused with the reason: HTTP 400 on `/reset`, an error message on `/ws`.
86
+
87
  The observation carries `prompt` and `system_prompt`, the exact text a model reads. The answer goes in
88
  `CardAction.expression`; an empty expression gives up. After the step, the observation adds `result`
89
  (the grader's report), `solution` and `solution_steps` (one way to make the target, one combination
 
94
  | Answer | Reward |
95
  |---|---|
96
  | Uses every card once and equals the target | 1.0 |
97
+ | Uses every card once, within 10% of the target (shaped mode) | `0.3 × c²`, `c = 1 − \|value − target\| / max(1, 0.1 × target)` |
98
  | Anything else: no answer, parse error, division by zero, a missing or extra card | 0 |
99
 
100
  The grader parses the expression with Python's `ast`, allows only non-negative integers, + − × ÷ and
101
  parentheses, compares the multiset of numbers to the cards, and evaluates with exact fractions. × ÷ −
102
+ (and look-alikes such as ∗ / +), no-break spaces and the letters A J Q K are accepted; anything after
103
+ `=` is ignored. Partial credit keeps a GRPO group of near misses from all scoring 0, and is capped far
104
+ below an exact answer, so getting close never pays more than getting it right.
105
 
106
  ## Use it
107
 
 
146
 
147
  ## Evaluations
148
 
149
+ `eval/rollout.py` in the [FineEnvs repository](https://github.com/adithya-s-k/FineEnvs/tree/main/08-math-environments/scott-wu-math)
150
  runs OpenAI, Anthropic and open models on Hugging Face Inference Providers against a running server, in
151
  parallel, one OpenEnv session per episode.
152
 
data/tasks/train.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
game/expr.py CHANGED
@@ -25,7 +25,7 @@ _AST_OPS = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/"}
25
  _LETTERS = {"A": "1", "J": "11", "Q": "12", "K": "13"}
26
  MAX_LENGTH = 400
27
 
28
- # What people and models type for the four operators.
29
  _SYMBOLS = str.maketrans(
30
  {
31
  "×": "*",
@@ -33,14 +33,27 @@ _SYMBOLS = str.maketrans(
33
  "X": "*",
34
  "·": "*",
35
  "∙": "*",
 
 
 
36
  "÷": "/",
 
 
 
37
  "−": "-",
38
  "–": "-",
39
  "—": "-",
 
40
  "[": "(",
41
  "]": ")",
42
  "{": "(",
43
  "}": ")",
 
 
 
 
 
 
44
  }
45
  )
46
 
@@ -137,7 +150,8 @@ def parse(text: str) -> Tree:
137
  raise ExpressionError("powers are not allowed")
138
  try:
139
  node = ast.parse(source, mode="eval").body
140
- except SyntaxError as exc:
 
141
  raise ExpressionError(f"not an arithmetic expression: {source!r}") from exc
142
 
143
  def build(n: ast.AST) -> Tree:
 
25
  _LETTERS = {"A": "1", "J": "11", "Q": "12", "K": "13"}
26
  MAX_LENGTH = 400
27
 
28
+ # What people and models type for the four operators, brackets and spaces.
29
  _SYMBOLS = str.maketrans(
30
  {
31
  "×": "*",
 
33
  "X": "*",
34
  "·": "*",
35
  "∙": "*",
36
+ "⋅": "*",
37
+ "∗": "*",
38
+ "*": "*",
39
  "÷": "/",
40
+ "/": "/",
41
+ "∕": "/",
42
+ "+": "+",
43
  "−": "-",
44
  "–": "-",
45
  "—": "-",
46
+ "-": "-",
47
  "[": "(",
48
  "]": ")",
49
  "{": "(",
50
  "}": ")",
51
+ "(": "(",
52
+ ")": ")",
53
+ "\u00a0": " ", # no-break space
54
+ "\u2009": " ", # thin space
55
+ "\u202f": " ", # narrow no-break space
56
+ "\u3000": " ", # ideographic space
57
  }
58
  )
59
 
 
150
  raise ExpressionError("powers are not allowed")
151
  try:
152
  node = ast.parse(source, mode="eval").body
153
+ except (SyntaxError, ValueError, RecursionError) as exc:
154
+ # ValueError: a null byte on some Python versions; RecursionError: nesting too deep to parse.
155
  raise ExpressionError(f"not an arithmetic expression: {source!r}") from exc
156
 
157
  def build(n: ast.AST) -> Tree:
game/reward.py CHANGED
@@ -2,9 +2,10 @@
2
 
3
  - 1.0 for an expression that uses every card exactly once and equals the target.
4
  - Shaped mode (default) adds partial credit up to 0.3 for an expression that uses every card
5
- exactly once but misses: ``0.3 * c**2`` with ``c = max(0, 1 - |value - target| / (0.1 * target))``,
6
- so only answers within 10% of the target earn anything. A group of failed attempts still
7
- differs, which GRPO needs, and an exact answer is always worth far more than a near one.
 
8
  - 0 for anything else: no answer, a parse error, a division by zero, a missing or extra card.
9
 
10
  Binary mode gives 1 or 0.
 
2
 
3
  - 1.0 for an expression that uses every card exactly once and equals the target.
4
  - Shaped mode (default) adds partial credit up to 0.3 for an expression that uses every card
5
+ exactly once but misses: ``0.3 * c**2`` with
6
+ ``c = max(0, 1 - |value - target| / max(1, 0.1 * target))``, so only answers within 10% of the
7
+ target (within 1 for targets under 10) earn anything. A group of failed attempts still differs,
8
+ which GRPO needs, and an exact answer is always worth far more than a near one.
9
  - 0 for anything else: no answer, a parse error, a division by zero, a missing or extra card.
10
 
11
  Binary mode gives 1 or 0.
game/solver.py CHANGED
@@ -9,7 +9,8 @@ the search complete for up to nine cards, and in practice it finds an answer in
9
  because big targets have many.
10
 
11
  A first pass keeps every intermediate value a whole number (the way people play, as in the
12
- video); a second pass allows fractions. Both stop at a deadline.
 
13
  """
14
 
15
  from __future__ import annotations
@@ -22,15 +23,31 @@ from itertools import combinations
22
  from .expr import Tree, evaluate, leaves
23
 
24
  LOOKUP_SIZE = 4
 
25
 
26
 
27
  class Timeout(Exception):
28
  pass
29
 
30
 
31
- @lru_cache(maxsize=200_000)
32
- def _reach(values: tuple[int, ...], integers: bool) -> dict[Fraction, Tree]:
33
- """Every value a sorted group of cards can make, with one tree for each."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  if len(values) == 1:
35
  return {Fraction(values[0]): values[0]}
36
  out: dict[Fraction, Tree] = {}
@@ -45,8 +62,10 @@ def _reach(values: tuple[int, ...], integers: bool) -> dict[Fraction, Tree]:
45
  right = tuple(v for i, v in enumerate(values) if i not in idx)
46
  if k * 2 == n and right in seen and right != left:
47
  continue
48
- lr, rr = _reach(left, integers), _reach(right, integers)
49
  for a, ta in lr.items():
 
 
50
  for b, tb in rr.items():
51
  _add(out, a + b, ("+", ta, tb), integers)
52
  _add(out, a * b, ("*", ta, tb), integers)
@@ -70,7 +89,6 @@ class _Search:
70
  self.integers = integers
71
  self.deadline = deadline
72
  self.failed: set[tuple[Fraction, tuple[int, ...]]] = set()
73
- self.nodes = 0
74
 
75
  def solve(self, target: Fraction, values: tuple[int, ...]) -> Tree | None:
76
  if len(values) <= LOOKUP_SIZE:
@@ -78,8 +96,7 @@ class _Search:
78
  key = (target, values)
79
  if key in self.failed:
80
  return None
81
- self.nodes += 1
82
- if self.nodes % 256 == 0 and time.monotonic() > self.deadline:
83
  raise Timeout
84
  n = len(values)
85
  seen: set[tuple[int, ...]] = set()
@@ -90,7 +107,7 @@ class _Search:
90
  continue
91
  seen.add(group)
92
  rest = tuple(v for i, v in enumerate(values) if i not in idx)
93
- for v, tv in _reach(group, self.integers).items():
94
  for need, build in self._needs(target, v, tv):
95
  if self.integers and (need.denominator != 1 or need < 0):
96
  continue
 
9
  because big targets have many.
10
 
11
  A first pass keeps every intermediate value a whole number (the way people play, as in the
12
+ video); a second pass allows fractions. Both stop at a deadline, which is checked at every step of
13
+ the search and while building the values of any group bigger than the cached ones.
14
  """
15
 
16
  from __future__ import annotations
 
23
  from .expr import Tree, evaluate, leaves
24
 
25
  LOOKUP_SIZE = 4
26
+ CACHE_SIZE = 8_192 # every group of up to LOOKUP_SIZE values 1-13, for both passes, is 4,758 entries
27
 
28
 
29
  class Timeout(Exception):
30
  pass
31
 
32
 
33
+ def _reach(values: tuple[int, ...], integers: bool, deadline: float | None = None) -> dict[Fraction, Tree]:
34
+ """Every value a sorted group of cards can make, with one tree for each.
35
+
36
+ Groups of up to LOOKUP_SIZE cards are cached: with values 1-13 there are 2,379 of them, so the
37
+ cache holds every one for both passes. A bigger group, which only a hand of more than nine cards
38
+ needs, is built fresh and stops at the deadline.
39
+ """
40
+ if len(values) <= LOOKUP_SIZE:
41
+ return _reach_small(values, integers)
42
+ return _combine(values, integers, deadline)
43
+
44
+
45
+ @lru_cache(maxsize=CACHE_SIZE)
46
+ def _reach_small(values: tuple[int, ...], integers: bool) -> dict[Fraction, Tree]:
47
+ return _combine(values, integers, None)
48
+
49
+
50
+ def _combine(values: tuple[int, ...], integers: bool, deadline: float | None) -> dict[Fraction, Tree]:
51
  if len(values) == 1:
52
  return {Fraction(values[0]): values[0]}
53
  out: dict[Fraction, Tree] = {}
 
62
  right = tuple(v for i, v in enumerate(values) if i not in idx)
63
  if k * 2 == n and right in seen and right != left:
64
  continue
65
+ lr, rr = _reach(left, integers, deadline), _reach(right, integers, deadline)
66
  for a, ta in lr.items():
67
+ if deadline is not None and time.monotonic() > deadline:
68
+ raise Timeout
69
  for b, tb in rr.items():
70
  _add(out, a + b, ("+", ta, tb), integers)
71
  _add(out, a * b, ("*", ta, tb), integers)
 
89
  self.integers = integers
90
  self.deadline = deadline
91
  self.failed: set[tuple[Fraction, tuple[int, ...]]] = set()
 
92
 
93
  def solve(self, target: Fraction, values: tuple[int, ...]) -> Tree | None:
94
  if len(values) <= LOOKUP_SIZE:
 
96
  key = (target, values)
97
  if key in self.failed:
98
  return None
99
+ if time.monotonic() > self.deadline:
 
100
  raise Timeout
101
  n = len(values)
102
  seen: set[tuple[int, ...]] = set()
 
107
  continue
108
  seen.add(group)
109
  rest = tuple(v for i, v in enumerate(values) if i not in idx)
110
+ for v, tv in _reach(group, self.integers, self.deadline).items():
111
  for need, build in self._needs(target, v, tv):
112
  if self.integers and (need.denominator != 1 or need < 0):
113
  continue
game/tasks.py CHANGED
@@ -11,6 +11,7 @@ from __future__ import annotations
11
 
12
  import datetime as _dt
13
  import random
 
14
  from dataclasses import dataclass
15
 
16
  from .cards import Card, cards_from_ranks, deal
@@ -37,6 +38,11 @@ LEVELS = {
37
  }
38
  DEFAULT_LEVEL = "year"
39
 
 
 
 
 
 
40
 
41
  def cards_for_target(target: int) -> int:
42
  """How many cards a custom target gets: 4 for up to 99, 6 for three digits, 8 for 1000-2999, then 9."""
@@ -58,12 +64,16 @@ def make_task(
58
  task_id: str | None = None,
59
  time_limit: float = 2.0,
60
  max_deals: int = 50,
 
61
  ) -> dict:
62
  """Deal a solvable task.
63
 
64
  With no `target`, the level picks one from its range. A given `target` keeps the level's card
65
  count, or without a level picks one by size (`cards_for_target`). Given `ranks` are dealt as
66
  they are and may have no solution (then `solution` is None).
 
 
 
67
  """
68
  if level is not None and level not in LEVELS:
69
  raise ValueError(f"unknown level {level!r}; choose one of {', '.join(LEVELS)}")
@@ -71,21 +81,33 @@ def make_task(
71
  lvl = LEVELS[level or DEFAULT_LEVEL]
72
  level, target = lvl.name, rng.randint(lvl.low, lvl.high)
73
  target = int(target)
74
- if not 0 <= target <= 1_000_000:
75
- raise ValueError("target must be a whole number from 0 to 1,000,000")
 
76
  if ranks is not None:
 
 
77
  cards = cards_from_ranks(list(ranks), rng)
78
- tree = solve([c.rank for c in cards], target, time_limit)
 
79
  return _task(cards, target, tree, level or "custom", task_id)
80
  n = n_cards or (LEVELS[level].n_cards if level else cards_for_target(target))
81
- if not 2 <= n <= 12:
82
- raise ValueError("deal between 2 and 12 cards")
83
  for _ in range(max_deals):
 
 
 
 
 
84
  cards = deal(n, rng)
85
- tree = solve([c.rank for c in cards], target, time_limit)
86
  if tree is not None:
87
  return _task(cards, target, tree, level or "custom", task_id)
88
- raise RuntimeError(f"no solvable deal of {n} cards for {target} in {max_deals} tries")
 
 
 
89
 
90
 
91
  def _task(cards: list[Card], target: int, tree: Tree | None, level: str, task_id: str | None) -> dict:
 
11
 
12
  import datetime as _dt
13
  import random
14
+ import time
15
  from dataclasses import dataclass
16
 
17
  from .cards import Card, cards_from_ranks, deal
 
38
  }
39
  DEFAULT_LEVEL = "year"
40
 
41
+ # A deal is solved while the caller waits, so custom deals stay where the solver answers in well under
42
+ # a second: up to nine cards (where it is complete) and four-digit targets, as in the video.
43
+ MIN_CARDS, MAX_CARDS = 2, 9
44
+ MAX_TARGET = 9_999
45
+
46
 
47
  def cards_for_target(target: int) -> int:
48
  """How many cards a custom target gets: 4 for up to 99, 6 for three digits, 8 for 1000-2999, then 9."""
 
64
  task_id: str | None = None,
65
  time_limit: float = 2.0,
66
  max_deals: int = 50,
67
+ budget: float | None = None,
68
  ) -> dict:
69
  """Deal a solvable task.
70
 
71
  With no `target`, the level picks one from its range. A given `target` keeps the level's card
72
  count, or without a level picks one by size (`cards_for_target`). Given `ranks` are dealt as
73
  they are and may have no solution (then `solution` is None).
74
+
75
+ The solver gets `time_limit` seconds per deal and at most `max_deals` deals; `budget`, if given,
76
+ caps the seconds spent on all of them together.
77
  """
78
  if level is not None and level not in LEVELS:
79
  raise ValueError(f"unknown level {level!r}; choose one of {', '.join(LEVELS)}")
 
81
  lvl = LEVELS[level or DEFAULT_LEVEL]
82
  level, target = lvl.name, rng.randint(lvl.low, lvl.high)
83
  target = int(target)
84
+ if not 0 <= target <= MAX_TARGET:
85
+ raise ValueError(f"target must be a whole number from 0 to {MAX_TARGET:,}")
86
+ started = time.monotonic()
87
  if ranks is not None:
88
+ if not MIN_CARDS <= len(ranks) <= MAX_CARDS:
89
+ raise ValueError(f"play between {MIN_CARDS} and {MAX_CARDS} cards, not {len(ranks)}")
90
  cards = cards_from_ranks(list(ranks), rng)
91
+ limit = time_limit if budget is None else min(time_limit, budget)
92
+ tree = solve([c.rank for c in cards], target, limit)
93
  return _task(cards, target, tree, level or "custom", task_id)
94
  n = n_cards or (LEVELS[level].n_cards if level else cards_for_target(target))
95
+ if not MIN_CARDS <= n <= MAX_CARDS:
96
+ raise ValueError(f"deal between {MIN_CARDS} and {MAX_CARDS} cards, not {n}")
97
  for _ in range(max_deals):
98
+ limit = time_limit
99
+ if budget is not None:
100
+ limit = min(limit, budget - (time.monotonic() - started))
101
+ if limit <= 0:
102
+ break
103
  cards = deal(n, rng)
104
+ tree = solve([c.rank for c in cards], target, limit)
105
  if tree is not None:
106
  return _task(cards, target, tree, level or "custom", task_id)
107
+ limits = f"{max_deals} deals" + ("" if budget is None else f" and {budget:g} s")
108
+ raise ValueError(
109
+ f"no solvable deal of {n} cards for {target} found within {limits}; try another target or card count"
110
+ )
111
 
112
 
113
  def _task(cards: list[Card], target: int, tree: Tree | None, level: str, task_id: str | None) -> dict:
pyproject.toml CHANGED
@@ -16,7 +16,7 @@ dependencies = [
16
 
17
  [project.optional-dependencies]
18
  dev = ["pytest>=8.0.0", "httpx>=0.27.0", "websockets>=12.0"]
19
- eval = ["openai>=1.50.0", "python-dotenv>=1.0.0"]
20
 
21
  [project.scripts]
22
  scott-wu-math-server = "scott_wu_math.server.app:main"
 
16
 
17
  [project.optional-dependencies]
18
  dev = ["pytest>=8.0.0", "httpx>=0.27.0", "websockets>=12.0"]
19
+ eval = ["openai>=1.50.0", "anthropic>=2.1.0", "python-dotenv>=1.0.0"]
20
 
21
  [project.scripts]
22
  scott-wu-math-server = "scott_wu_math.server.app:main"
scripts/build_tasks.py CHANGED
@@ -3,8 +3,14 @@
3
  python -m scott_wu_math.scripts.build_tasks # or: python scripts/build_tasks.py from the env dir
4
 
5
  test: 50 deals per level (200), seed 2026
6
- train: 1,000 deals per level (4,000), seed 7, none sharing an id with test
 
 
 
7
  video: the two hands from the video, 2025 from eight cards and 6,843 from nine
 
 
 
8
  """
9
 
10
  from __future__ import annotations
@@ -12,6 +18,7 @@ from __future__ import annotations
12
  import json
13
  import random
14
  import sys
 
15
  from pathlib import Path
16
 
17
  HERE = Path(__file__).resolve().parents[1]
@@ -39,7 +46,16 @@ VIDEO = [
39
  ]
40
 
41
 
42
- def build(seed: int, per_level: int, prefix: str, skip: set[str]) -> list[dict]:
 
 
 
 
 
 
 
 
 
43
  rng = random.Random(seed)
44
  tasks: list[dict] = []
45
  for level in LEVELS:
@@ -50,24 +66,29 @@ def build(seed: int, per_level: int, prefix: str, skip: set[str]) -> list[dict]:
50
  if key in skip:
51
  continue
52
  skip.add(key)
53
- task["id"] = f"{prefix}-{level}-{made:04d}"
 
 
 
 
 
54
  task["key"] = key
55
  tasks.append(task)
56
- made += 1
57
  return tasks
58
 
59
 
60
  def write(name: str, tasks: list[dict]) -> None:
61
  path = OUT / f"{name}.jsonl"
62
  path.write_text("".join(json.dumps(t, ensure_ascii=False) + "\n" for t in tasks))
63
- print(f"{path.relative_to(HERE)}: {len(tasks)} tasks")
 
64
 
65
 
66
  def main() -> None:
67
  OUT.mkdir(parents=True, exist_ok=True)
68
  seen: set[str] = set()
69
  test = build(2026, 50, "test", seen)
70
- train = build(7, 1000, "train", seen)
71
  video = []
72
  for v in VIDEO:
73
  cards = [Card(r, s) for r, s in v["cards"]]
 
3
  python -m scott_wu_math.scripts.build_tasks # or: python scripts/build_tasks.py from the env dir
4
 
5
  test: 50 deals per level (200), seed 2026
6
+ train: 1,000 draws per level, seed 7, keeping only deals that differ from every test deal and every
7
+ earlier train deal in what grading sees: the target and the card values (suits do not matter).
8
+ Ids keep the draw number, so they have gaps where a draw was dropped. Level 24 keeps 639: only
9
+ 1,362 of the 1,820 four-card hands can make 24, so its draws repeat often.
10
  video: the two hands from the video, 2025 from eight cards and 6,843 from nine
11
+
12
+ Test is kept exactly as first built, since the published eval card was computed on it. It has two
13
+ pairs of level-24 deals with the same values (test-24-0008 / test-24-0023, test-24-0011 / test-24-0013).
14
  """
15
 
16
  from __future__ import annotations
 
18
  import json
19
  import random
20
  import sys
21
+ from collections import Counter
22
  from pathlib import Path
23
 
24
  HERE = Path(__file__).resolve().parents[1]
 
46
  ]
47
 
48
 
49
+ def deal_key(task: dict) -> tuple[int, tuple[int, ...]]:
50
+ """What grading depends on: the target and the card values, without suits."""
51
+ return task["target"], tuple(sorted(c["rank"] for c in task["cards"]))
52
+
53
+
54
+ def build(seed: int, per_level: int, prefix: str, skip: set[str], avoid: set | None = None) -> list[dict]:
55
+ """Draw per_level deals per level whose id (target and cards with suits) is not in `skip`.
56
+
57
+ With `avoid`, a draw whose `deal_key` is already there is dropped, and each kept deal's key is added.
58
+ """
59
  rng = random.Random(seed)
60
  tasks: list[dict] = []
61
  for level in LEVELS:
 
66
  if key in skip:
67
  continue
68
  skip.add(key)
69
+ number, made = made, made + 1
70
+ if avoid is not None:
71
+ if deal_key(task) in avoid:
72
+ continue
73
+ avoid.add(deal_key(task))
74
+ task["id"] = f"{prefix}-{level}-{number:04d}"
75
  task["key"] = key
76
  tasks.append(task)
 
77
  return tasks
78
 
79
 
80
  def write(name: str, tasks: list[dict]) -> None:
81
  path = OUT / f"{name}.jsonl"
82
  path.write_text("".join(json.dumps(t, ensure_ascii=False) + "\n" for t in tasks))
83
+ per_level = Counter(t["level"] for t in tasks)
84
+ print(f"{path.relative_to(HERE)}: {len(tasks)} tasks ({', '.join(f'{k} {v}' for k, v in per_level.items())})")
85
 
86
 
87
  def main() -> None:
88
  OUT.mkdir(parents=True, exist_ok=True)
89
  seen: set[str] = set()
90
  test = build(2026, 50, "test", seen)
91
+ train = build(7, 1000, "train", seen, avoid={deal_key(t) for t in test})
92
  video = []
93
  for v in VIDEO:
94
  cards = [Card(r, s) for r, s in v["cards"]]
server/app.py CHANGED
@@ -8,12 +8,13 @@ from __future__ import annotations
8
  import os
9
  from pathlib import Path
10
 
11
- from fastapi.responses import FileResponse, RedirectResponse
 
12
  from fastapi.staticfiles import StaticFiles
13
  from openenv.core.env_server.http_server import create_app
14
 
15
  from ..models import CardAction, CardObservation, CardState
16
- from .environment import ScottWuMathEnvironment
17
 
18
  WEB = Path(__file__).resolve().parent / "web"
19
  README = Path(__file__).resolve().parents[1] / "README.md"
@@ -32,6 +33,12 @@ app = create_app(
32
  app.mount("/static", StaticFiles(directory=WEB), name="static")
33
 
34
 
 
 
 
 
 
 
35
  @app.get("/", include_in_schema=False)
36
  def play_page() -> FileResponse:
37
  return FileResponse(WEB / "index.html", headers={"Cache-Control": "no-cache"})
 
8
  import os
9
  from pathlib import Path
10
 
11
+ from fastapi import Request
12
+ from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
13
  from fastapi.staticfiles import StaticFiles
14
  from openenv.core.env_server.http_server import create_app
15
 
16
  from ..models import CardAction, CardObservation, CardState
17
+ from .environment import InvalidReset, ScottWuMathEnvironment
18
 
19
  WEB = Path(__file__).resolve().parent / "web"
20
  README = Path(__file__).resolve().parents[1] / "README.md"
 
33
  app.mount("/static", StaticFiles(directory=WEB), name="static")
34
 
35
 
36
+ @app.exception_handler(InvalidReset)
37
+ async def invalid_reset(request: Request, exc: InvalidReset) -> JSONResponse:
38
+ """A reset the server cannot deal (index out of range, target too big, ...) is the client's error."""
39
+ return JSONResponse(status_code=400, content={"detail": str(exc)})
40
+
41
+
42
  @app.get("/", include_in_schema=False)
43
  def play_page() -> FileResponse:
44
  return FileResponse(WEB / "index.html", headers={"Cache-Control": "no-cache"})
server/environment.py CHANGED
@@ -26,6 +26,19 @@ TASKS_DIR = Path(__file__).resolve().parents[1] / "data" / "tasks"
26
  SPLITS = {"train": "train", "test": "test", "video": "test"}
27
  _TASKS: dict[str, list[dict]] = {}
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  def load_split(split: str) -> list[dict]:
31
  if split not in SPLITS:
@@ -36,6 +49,29 @@ def load_split(split: str) -> list[dict]:
36
  return _TASKS[split]
37
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  class ScottWuMathEnvironment(Environment[CardAction, CardObservation, CardState]):
40
  SUPPORTS_CONCURRENT_SESSIONS = True
41
 
@@ -64,25 +100,21 @@ class ScottWuMathEnvironment(Environment[CardAction, CardObservation, CardState]
64
 
65
  - `split` + `index`: a fixed task from `train`, `test` or `video` (the two hands from the video).
66
  - `level`: a fresh deal at `24` (4 cards), `three-digit` (6), `year` (8) or `four-digit` (9).
67
- - `target` (and optionally `n_cards`): a fresh deal for your own number, as in the video.
68
- - `cards` (values 1-13) with `target`: play a hand you choose; it may have no solution.
69
  - nothing: eight cards for the current year.
 
 
70
  """
71
- if reward_mode not in ("shaped", "binary"):
72
- raise ValueError("reward_mode is 'shaped' or 'binary'")
73
- rng = random.Random(seed)
74
- if split is not None:
75
- tasks = load_split(split)
76
- i = rng.randrange(len(tasks)) if index is None else int(index)
77
- task = tasks[i]
78
- elif cards:
79
- if target is None:
80
- raise ValueError("give a target with your cards")
81
- task = make_task(rng, level=level, target=target, ranks=[int(c) for c in cards])
82
- elif target is not None or level is not None:
83
- task = make_task(rng, level=level, target=target, n_cards=n_cards)
84
- else:
85
- task = make_task(rng, level="year", target=CURRENT_YEAR)
86
  self._task = task
87
  self._started = time.monotonic()
88
  self._state = CardState(
@@ -145,7 +177,11 @@ class ScottWuMathEnvironment(Environment[CardAction, CardObservation, CardState]
145
  return len(load_split(split))
146
 
147
  def get_task(self, split: str, index: int) -> dict:
 
 
148
  return public(load_split(split)[index])
149
 
150
  def get_task_range(self, split: str, start: int, stop: int) -> list[dict]:
 
 
151
  return [public(t) for t in load_split(split)[start:stop]]
 
26
  SPLITS = {"train": "train", "test": "test", "video": "test"}
27
  _TASKS: dict[str, list[dict]] = {}
28
 
29
+ # A fresh deal is solved while the request waits, so the server caps the solver: DEAL_SECONDS per
30
+ # deal, at most MAX_DEALS deals, DEAL_BUDGET seconds for all of them. Normal deals take milliseconds.
31
+ DEAL_SECONDS = 1.0
32
+ MAX_DEALS = 20
33
+ DEAL_BUDGET = 3.0
34
+
35
+
36
+ class InvalidReset(ValueError):
37
+ """A reset the server cannot deal: unknown split or level, index out of range, bad target or cards.
38
+
39
+ The HTTP app answers it with 400 and the message; over /ws the message comes back as an error.
40
+ """
41
+
42
 
43
  def load_split(split: str) -> list[dict]:
44
  if split not in SPLITS:
 
49
  return _TASKS[split]
50
 
51
 
52
+ def _deal(*, seed, split, index, level, target, n_cards, cards, reward_mode) -> dict:
53
+ """The task for one reset. Bad arguments raise ValueError (or TypeError), which `reset` reports."""
54
+ if reward_mode not in ("shaped", "binary"):
55
+ raise InvalidReset("reward_mode is 'shaped' or 'binary'")
56
+ rng = random.Random(seed)
57
+ if split is not None:
58
+ tasks = load_split(split)
59
+ if index is None:
60
+ return tasks[rng.randrange(len(tasks))]
61
+ i = int(index)
62
+ if not 0 <= i < len(tasks):
63
+ raise InvalidReset(f"index {i} is out of range: split {split!r} has tasks 0 to {len(tasks) - 1}")
64
+ return tasks[i]
65
+ limits = {"time_limit": DEAL_SECONDS, "max_deals": MAX_DEALS, "budget": DEAL_BUDGET}
66
+ if cards:
67
+ if target is None:
68
+ raise InvalidReset("give a target with your cards")
69
+ return make_task(rng, level=level, target=target, ranks=[int(c) for c in cards], **limits)
70
+ if target is not None or level is not None:
71
+ return make_task(rng, level=level, target=target, n_cards=n_cards, **limits)
72
+ return make_task(rng, level="year", target=CURRENT_YEAR, **limits)
73
+
74
+
75
  class ScottWuMathEnvironment(Environment[CardAction, CardObservation, CardState]):
76
  SUPPORTS_CONCURRENT_SESSIONS = True
77
 
 
100
 
101
  - `split` + `index`: a fixed task from `train`, `test` or `video` (the two hands from the video).
102
  - `level`: a fresh deal at `24` (4 cards), `three-digit` (6), `year` (8) or `four-digit` (9).
103
+ - `target` (0-9,999, and optionally `n_cards`, 2-9): a fresh deal for your own number, as in the video.
104
+ - `cards` (2-9 values, 1-13) with `target`: play a hand you choose; it may have no solution.
105
  - nothing: eight cards for the current year.
106
+
107
+ Anything the server cannot deal raises `InvalidReset` (HTTP 400) with the reason.
108
  """
109
+ try:
110
+ task = _deal(
111
+ seed=seed, split=split, index=index, level=level, target=target, n_cards=n_cards, cards=cards,
112
+ reward_mode=reward_mode,
113
+ )
114
+ except InvalidReset:
115
+ raise
116
+ except (ValueError, TypeError) as exc:
117
+ raise InvalidReset(str(exc)) from exc
 
 
 
 
 
 
118
  self._task = task
119
  self._started = time.monotonic()
120
  self._state = CardState(
 
177
  return len(load_split(split))
178
 
179
  def get_task(self, split: str, index: int) -> dict:
180
+ if index < 0:
181
+ raise IndexError(index) # OpenEnv answers 400 "Invalid task index", as for one past the end
182
  return public(load_split(split)[index])
183
 
184
  def get_task_range(self, split: str, start: int, stop: int) -> list[dict]:
185
+ if start < 0 or stop < 0:
186
+ raise IndexError(start if start < 0 else stop)
187
  return [public(t) for t in load_split(split)[start:stop]]
server/web/app.js CHANGED
@@ -82,7 +82,7 @@
82
  S.videoIndex = (S.videoIndex + 1) % 2;
83
  } else if (S.level === "custom") {
84
  const raw = $("custom-target").value.replace(/[,\s_]/g, "");
85
- if (!/^\d{1,6}$/.test(raw)) { setStatus("Type a whole number for the target first.", "warn"); $("custom-target").focus(); return; }
86
  data = { target: Number(raw) };
87
  } else if (S.level === "year") {
88
  data = { level: "year", target: new Date().getFullYear() };
 
82
  S.videoIndex = (S.videoIndex + 1) % 2;
83
  } else if (S.level === "custom") {
84
  const raw = $("custom-target").value.replace(/[,\s_]/g, "");
85
+ if (!/^\d{1,4}$/.test(raw)) { setStatus("Type a whole number up to 9,999 for the target first.", "warn"); $("custom-target").focus(); return; }
86
  data = { target: Number(raw) };
87
  } else if (S.level === "year") {
88
  data = { level: "year", target: new Date().getFullYear() };
server/web/card.html CHANGED
@@ -27,7 +27,7 @@
27
  <nav><a href="/">Play</a><a href="/static/card.html" aria-current="page">Environment card</a><a href="/docs">API</a></nav>
28
  </header>
29
  <article class="doc" id="doc">Loading…</article>
30
- <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.2/marked.min.js"></script>
31
  <script>
32
  fetch("/readme.md").then((r) => r.text()).then((md) => {
33
  md = md.replace(/^---[\s\S]*?\n---\n/, ""); // drop the Space front matter
 
27
  <nav><a href="/">Play</a><a href="/static/card.html" aria-current="page">Environment card</a><a href="/docs">API</a></nav>
28
  </header>
29
  <article class="doc" id="doc">Loading…</article>
30
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.2/marked.min.js" integrity="sha512-xeUh+KxNyTufZOje++oQHstlMQ8/rpyzPuM+gjMFYK3z5ILJGE7l2NvYL+XfliKURMpBIKKp1XoPN/qswlSMFA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
31
  <script>
32
  fetch("/readme.md").then((r) => r.text()).then((md) => {
33
  md = md.replace(/^---[\s\S]*?\n---\n/, ""); // drop the Space front matter
server/web/index.html CHANGED
@@ -31,9 +31,9 @@
31
 
32
  <form class="custom" id="custom" hidden>
33
  <label for="custom-target">Target</label>
34
- <input id="custom-target" inputmode="numeric" pattern="[0-9]*" maxlength="6" placeholder="6843" autocomplete="off">
35
  <button type="submit" class="btn">Deal</button>
36
- <span class="muted" id="custom-hint">Any number up to 999,999. 4 cards below 100, 6 below 1,000, 8 below 3,000, else 9.</span>
37
  </form>
38
 
39
  <div class="table" id="table">
 
31
 
32
  <form class="custom" id="custom" hidden>
33
  <label for="custom-target">Target</label>
34
+ <input id="custom-target" inputmode="numeric" pattern="[0-9]*" maxlength="5" placeholder="6843" autocomplete="off">
35
  <button type="submit" class="btn">Deal</button>
36
+ <span class="muted" id="custom-hint">Any number up to 9,999. 4 cards below 100, 6 below 1,000, 8 below 3,000, else 9.</span>
37
  </form>
38
 
39
  <div class="table" id="table">