Balab2021 commited on
Commit
8da747c
·
verified ·
1 Parent(s): 5a96eb2

Agentic cricket scorebook tasks built with NeMo Curator

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ scorebook/deliveries.jsonl filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc0-1.0
3
+ task_categories: [question-answering, text-generation]
4
+ tags: [agents, tool-use, function-calling, reinforcement-learning, rlvr, cricket, t20, synthetic, nemo-curator, nemo-gym]
5
+ size_categories: [100K<n<1M]
6
+ configs:
7
+ - config_name: default
8
+ data_files:
9
+ - split: train
10
+ path: data/train-*.parquet
11
+ - split: test
12
+ path: data/test-*.parquet
13
+ - split: benchmark
14
+ path: data/benchmark-*.parquet
15
+ ---
16
+
17
+ # Cricket T20I scorebook agent tasks (multi-step tool use, exact answers)
18
+
19
+ **101,098 tool-use tasks** built from
20
+ [Balab2021/CricketData-T20-Reasoning-Qwen3.8-Full](https://huggingface.co/datasets/Balab2021/CricketData-T20-Reasoning-Qwen3.8-Full) with
21
+ [NeMo Curator](https://github.com/NVIDIA-NeMo/Curator) (nemo-curator 1.4.0).
22
+
23
+ The source dataset asks cricket arithmetic questions with all numbers given in the prompt. Here the numbers are
24
+ removed from the question and placed behind tools: the agent has to find the match, look up the state of an innings
25
+ at one or two points, calculate, and report a number. Every answer is computed exactly from the data, so a run can be
26
+ scored without a judge model. The dataset is meant for post-training and evaluating agents with verifiable rewards.
27
+
28
+ ## What is in the repository
29
+
30
+ | Path | Content |
31
+ |---|---|
32
+ | `data/train-*.parquet` | 95,788 tasks from 1,597 matches |
33
+ | `data/test-*.parquet` | 5,310 tasks from 177 other matches (no match is in both splits) |
34
+ | `data/benchmark-*.parquet` | 600 test tasks, 60 per task type (subset of `test`) |
35
+ | `scorebook/matches.jsonl` | 1,774 matches: id, date, venue, team batting first, team batting second |
36
+ | `scorebook/deliveries.jsonl` | 394,701 innings states, one per legal delivery |
37
+ | `scorebook.py` | the four tools, the task builders and the answer checker (Python standard library only) |
38
+ | `stats.json` | counts from every pipeline stage |
39
+
40
+ ## Tools
41
+
42
+ | Tool | Arguments | Returns |
43
+ |---|---|---|
44
+ | `find_match` | `team_a`, `team_b`, `date` | `match_id`, venue, which team batted first and second |
45
+ | `get_score` | `match_id`, `innings`, `overs` | runs, wickets, balls bowled, balls remaining, target (second innings) |
46
+ | `get_batter` | `match_id`, `innings`, `overs` | batter on strike, that batter's runs and balls faced, bowler |
47
+ | `calculate` | `expression` | value of an arithmetic expression |
48
+
49
+ A point in an innings is written `overs.balls` (`14.3` = 14 overs and 3 balls). A lookup returns the state right after
50
+ the legal delivery that completed that point. Tool errors come back as `{"error": "..."}`.
51
+
52
+ ## Task types
53
+
54
+ | Type | Question | Score/batter lookups in the reference solution | train | test | benchmark |
55
+ |---|---|---|---|---|---|
56
+ | `run_rate` | run rate after a given point | 1 | 9,582 | 531 | 60 |
57
+ | `required_rate` | run rate a chasing side still needs | 1 | 9,569 | 531 | 60 |
58
+ | `projection` | projected 20-over total at the current rate | 1 | 9,582 | 531 | 60 |
59
+ | `phase_runs` | runs scored between two points of an innings | 2 | 9,578 | 531 | 60 |
60
+ | `phase_rate` | run rate between two points of an innings | 2 | 9,581 | 531 | 60 |
61
+ | `phase_wickets` | wickets lost between two points of an innings | 2 | 9,580 | 531 | 60 |
62
+ | `innings_compare` | lead of the chasing side over the other side at the same stage (two innings) | 2 | 9,572 | 531 | 60 |
63
+ | `strike_rate` | strike rate of the batter on strike | 1 | 9,582 | 531 | 60 |
64
+ | `milestone` | balls the batter on strike needs for the next multiple of 50 | 1 | 9,580 | 531 | 60 |
65
+ | `batter_share` | share of the team's runs scored by the batter on strike | 2 | 9,582 | 531 | 60 |
66
+
67
+ Every reference solution is: `find_match`, then the lookups, then one `calculate` call, then the answer
68
+ (3.5 tool calls on average).
69
+
70
+ ## Columns
71
+
72
+ | Column | Meaning |
73
+ |---|---|
74
+ | `id` | `<match_id>-<innings>-<balls>[-<innings>-<balls>]-<type>` |
75
+ | `split`, `qtype`, `match_id` | split, task type, match |
76
+ | `question` | user message |
77
+ | `gold`, `answer_kind` | exact answer; `rate` answers are accepted within 0.011, `int` answers must match |
78
+ | `tools` | JSON string: the four tool definitions (OpenAI Responses format) |
79
+ | `messages` | JSON string: reference conversation (system, user, assistant tool calls, tool results, final answer) |
80
+ | `num_reference_tool_calls` | tool calls in the reference conversation |
81
+ | `source_row_indices` | JSON string: row numbers in `Valarmathy/CricketData` that the task uses |
82
+
83
+ ## Example
84
+
85
+ ```
86
+ T20 International Indonesia v Japan at Sano International Cricket Ground on 2022-10-16.
87
+
88
+ Japan were chasing. After 3.5 overs of the chase, what run rate (runs per over) did they need over the rest of their 20 overs to reach the target? Round to 2 decimal places.
89
+ ```
90
+
91
+ Reference solution (answer 2.35):
92
+
93
+ ```
94
+ assistant -> find_match({"team_a": "Indonesia", "team_b": "Japan", "date": "2022-10-16"})
95
+ tool <- {"match_id": 1336953, "date": "2022-10-16", "venue": "Sano International Cricket Ground", "bat_first": "Indonesia", "bat_second": "Japan"}
96
+ assistant -> get_score({"match_id": 1336953, "innings": 2, "overs": "3.5"})
97
+ tool <- {"match_id": 1336953, "innings": 2, "batting_team": "Japan", "bowling_team": "Indonesia", "overs": "3.5", "balls_bowled": 23, "balls_remaining": 97, "runs": 46, "wickets": 2, "target": 84}
98
+ assistant -> calculate({"expression": "round((84 - 46) * 6 / 97, 2)"})
99
+ tool <- {"value": 2.35}
100
+ assistant: Using the scorebook figures, round((84 - 46) * 6 / 97, 2) = 2.35. / Final answer: 2.35
101
+ ```
102
+
103
+ ## How it was built
104
+
105
+ 1. **Extract** - the `source` record of every question row becomes one scorebook entry (state after a delivery).
106
+ Rows for wides and no-balls and rain-revised matches are dropped: 500,000 question rows,
107
+ 34,947 unusable, 69,538 repeats of a delivery already seen.
108
+ 2. **Clean** - exact de-duplication per match, innings and ball (1 removed); rows with
109
+ impossible values (813) and innings whose score ever decreases
110
+ (0) are dropped.
111
+ 3. **Generate** - per match, up to 6 tasks of each type for training matches and
112
+ 3 for test matches, at points between 2.0 and 18.0 overs; two-point tasks span
113
+ at least 2 overs.
114
+ 4. **Validate** - the reference conversation of every task is replayed through the scorebook and its final answer is
115
+ checked against the gold answer with the dataset's own checker (0 mismatches and
116
+ 0 malformed tasks were dropped; 101,098 kept).
117
+
118
+ The train/test split follows the source dataset: a match that has any test row is a test match.
119
+
120
+ ## Use
121
+
122
+ ```python
123
+ import json
124
+ from datasets import load_dataset
125
+ ds = load_dataset("Balab2021/CricketData-T20-Agentic-ToolUse", split="benchmark")
126
+ row = ds[0]
127
+ tools, reference = json.loads(row["tools"]), json.loads(row["messages"])
128
+ ```
129
+
130
+ To run an agent, download `scorebook.py` and the `scorebook/` folder:
131
+
132
+ ```python
133
+ import json, scorebook as S
134
+ book = S.Scorebook(map(json.loads, open("scorebook/matches.jsonl")), map(json.loads, open("scorebook/deliveries.jsonl")))
135
+ result = book.call("get_score", {"match_id": 1001349, "innings": 1, "overs": "14.3"})
136
+ ok = S.is_correct(S.parse_answer("Final answer: 7.25"), 7.25, "rate")
137
+ ```
138
+
139
+ ## Limits
140
+
141
+ - The reference conversations are produced by a program, not by a model. They show one valid tool sequence without
142
+ reasoning text.
143
+ - All tasks are arithmetic over scorebook lookups in one domain. Results here say little about open-ended agent work.
144
+ - Numbers come from `Valarmathy/CricketData` as they are; they were checked for internal consistency, not against
145
+ official scorecards.
146
+
147
+ ## Licence
148
+
149
+ CC0-1.0, the same as the source data.
data/benchmark-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4051a9db306be70d274b65a98754a911a2aca8bb2a0fa1d5ba0bc4d79197fc01
3
+ size 314740
data/test-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4a7c49b7ea1baaabdf09743489e69ffcbef9f08ebdc095b867b42f4db428587
3
+ size 2564403
data/train-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d20836d83442435138043c051c68ab601ba7ce8efff48a7efff901acc603c656
3
+ size 12171422
data/train-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9dcf46fc850263918470fa570f94877bf90532490502e4c108c0c8b42614d572
3
+ size 12181514
data/train-00002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de827f3d0306dcfa40f6eb4b770af43db0923173dcf8d09d45318c87170b5250
3
+ size 10131540
data/train-00003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74feacc4435601f1dc3163c325378884773be3ff1d7f2440c4d0a3ff01a99a04
3
+ size 12181539
scorebook.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cricket scorebook: the tools an agent can call, the task types built on them, and the answer checker.
2
+
3
+ One module shared by the dataset pipeline (builds tasks and reference tool traces), the NeMo Gym environment
4
+ (serves the tools, scores answers) and the evaluation scripts, so that all three agree. Standard library only.
5
+
6
+ Data model
7
+ match : {match_id, date, venue, bat_first, bat_second}
8
+ delivery : state of an innings right after a LEGAL delivery, keyed by (match_id, innings, balls_bowled):
9
+ runs, wickets, target (innings 2), striker, striker_runs, striker_balls, bowler
10
+ A point in an innings is written in cricket notation "overs.balls" (14.3 = 14 overs and 3 balls = 87 balls).
11
+
12
+ Tools (what the agent sees): find_match, get_score, get_batter, calculate.
13
+ The question never contains the numbers needed for the answer; they have to be looked up with the tools.
14
+ """
15
+ import ast
16
+ import math
17
+ import operator
18
+ import re
19
+
20
+ SYSTEM_PROMPT = (
21
+ "You are a cricket analyst with access to a T20 International scorebook through tools. "
22
+ "The question does not contain the numbers you need: look them up with the tools, one call at a time, "
23
+ "and use the calculate tool for arithmetic. Points in an innings are written as overs.balls "
24
+ "(14.3 means 14 overs and 3 balls). When you have the answer, reply with a short explanation and give the "
25
+ "result on its own last line as 'Final answer: <number>'."
26
+ )
27
+
28
+ # Tool definitions in the OpenAI Responses API format used by NeMo Gym task rows.
29
+ TOOLS = [
30
+ {"type": "function", "name": "find_match",
31
+ "description": "Find a T20 International by the two teams and the date. Returns match_id, venue and which team batted first and second.",
32
+ "parameters": {"type": "object", "properties": {
33
+ "team_a": {"type": "string", "description": "One of the two teams, for example 'Australia'."},
34
+ "team_b": {"type": "string", "description": "The other team."},
35
+ "date": {"type": "string", "description": "Match date as YYYY-MM-DD."}},
36
+ "required": ["team_a", "team_b", "date"], "additionalProperties": False}, "strict": True},
37
+ {"type": "function", "name": "get_score",
38
+ "description": "Team score of one innings right after the given point: runs, wickets, balls bowled, balls remaining and, for the second innings, the target.",
39
+ "parameters": {"type": "object", "properties": {
40
+ "match_id": {"type": "integer", "description": "match_id returned by find_match."},
41
+ "innings": {"type": "integer", "description": "1 for the team batting first, 2 for the team batting second."},
42
+ "overs": {"type": "string", "description": "Point in the innings as overs.balls, for example '14.3'."}},
43
+ "required": ["match_id", "innings", "overs"], "additionalProperties": False}, "strict": True},
44
+ {"type": "function", "name": "get_batter",
45
+ "description": "The batter on strike for the delivery that completed the given point, with that batter's runs and balls faced so far, and the bowler.",
46
+ "parameters": {"type": "object", "properties": {
47
+ "match_id": {"type": "integer", "description": "match_id returned by find_match."},
48
+ "innings": {"type": "integer", "description": "1 for the team batting first, 2 for the team batting second."},
49
+ "overs": {"type": "string", "description": "Point in the innings as overs.balls, for example '14.3'."}},
50
+ "required": ["match_id", "innings", "overs"], "additionalProperties": False}, "strict": True},
51
+ {"type": "function", "name": "calculate",
52
+ "description": "Evaluate an arithmetic expression. Supports + - * / // % ** and round(x, n), ceil(x), floor(x), abs(x), min(...), max(...).",
53
+ "parameters": {"type": "object", "properties": {
54
+ "expression": {"type": "string", "description": "For example '(152 - 96) * 6 / 33'."}},
55
+ "required": ["expression"], "additionalProperties": False}, "strict": True},
56
+ ]
57
+ TOOL_NAMES = [t["name"] for t in TOOLS]
58
+
59
+
60
+ def chat_tools():
61
+ """The same tools in the Chat Completions format ({"type": "function", "function": {...}})."""
62
+ return [{"type": "function", "function": {k: t[k] for k in ("name", "description", "parameters")}} for t in TOOLS]
63
+
64
+
65
+ # ---------------------------------------------------------------- overs notation
66
+ def overs_str(balls: int) -> str:
67
+ return f"{balls // 6}.{balls % 6}"
68
+
69
+
70
+ def parse_overs(text) -> int:
71
+ """'14.3' -> 87 balls. Accepts '14' and 14.0; rejects ball digits above 5."""
72
+ m = re.fullmatch(r"\s*(\d{1,2})(?:\.(\d))?\s*", str(text))
73
+ if not m:
74
+ raise ValueError("overs must look like '14.3' (overs.balls)")
75
+ o, b = int(m.group(1)), int(m.group(2) or 0)
76
+ if b > 5:
77
+ raise ValueError("the balls digit must be 0 to 5")
78
+ return o * 6 + b
79
+
80
+
81
+ # ---------------------------------------------------------------- calculator
82
+ _BIN = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv,
83
+ ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: operator.pow}
84
+ _FUNCS = {"round": round, "ceil": math.ceil, "floor": math.floor, "abs": abs, "min": min, "max": max}
85
+
86
+
87
+ def _ev(node):
88
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool):
89
+ return node.value
90
+ if isinstance(node, ast.BinOp) and type(node.op) in _BIN:
91
+ a, b = _ev(node.left), _ev(node.right)
92
+ if isinstance(node.op, ast.Pow) and (abs(a) > 1e6 or abs(b) > 64):
93
+ raise ValueError("power too large")
94
+ return _BIN[type(node.op)](a, b)
95
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
96
+ v = _ev(node.operand)
97
+ return -v if isinstance(node.op, ast.USub) else v
98
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _FUNCS and not node.keywords:
99
+ return _FUNCS[node.func.id](*[_ev(a) for a in node.args])
100
+ raise ValueError("only numbers, + - * / // % **, parentheses and round/ceil/floor/abs/min/max are allowed")
101
+
102
+
103
+ def calculate(expression: str):
104
+ if not isinstance(expression, str) or len(expression) > 300:
105
+ raise ValueError("expression must be a string of at most 300 characters")
106
+ value = _ev(ast.parse(expression.strip(), mode="eval").body)
107
+ if isinstance(value, float):
108
+ if math.isnan(value) or math.isinf(value):
109
+ raise ValueError("result is not a finite number")
110
+ value = round(value, 6)
111
+ if value == int(value) and abs(value) < 1e15:
112
+ value = int(value)
113
+ return value
114
+
115
+
116
+ # ---------------------------------------------------------------- scorebook
117
+ class Scorebook:
118
+ """In-memory scorebook. matches: iterable of match dicts; deliveries: iterable of delivery dicts."""
119
+
120
+ def __init__(self, matches, deliveries):
121
+ self.matches = {int(m["match_id"]): m for m in matches}
122
+ self.by_key = {}
123
+ for m in self.matches.values():
124
+ for key in ((m["bat_first"], m["bat_second"]), (m["bat_second"], m["bat_first"])):
125
+ self.by_key.setdefault((key[0].lower(), key[1].lower(), m["date"]), []).append(m)
126
+ self.state = {}
127
+ for d in deliveries:
128
+ self.state[(int(d["match_id"]), int(d["innings"]), int(d["balls_bowled"]))] = d
129
+
130
+ # each tool returns a JSON-serialisable dict; problems are reported as {"error": "..."} so the agent can recover
131
+ def find_match(self, team_a, team_b, date):
132
+ hits = self.by_key.get((str(team_a).strip().lower(), str(team_b).strip().lower(), str(date).strip()[:10]))
133
+ if not hits:
134
+ return {"error": "no match found for these two teams on that date; check the team names and the date (YYYY-MM-DD)"}
135
+ if len(hits) > 1:
136
+ return {"matches": [dict(m) for m in hits], "note": "more than one match that day; choose by venue"}
137
+ return dict(hits[0])
138
+
139
+ def _state(self, match_id, innings, overs):
140
+ try:
141
+ mid, inn = int(match_id), int(innings)
142
+ except (TypeError, ValueError):
143
+ return None, {"error": "match_id and innings must be integers"}
144
+ if mid not in self.matches:
145
+ return None, {"error": f"unknown match_id {match_id}; use find_match first"}
146
+ if inn not in (1, 2):
147
+ return None, {"error": "innings must be 1 or 2"}
148
+ try:
149
+ balls = parse_overs(overs)
150
+ except ValueError as e:
151
+ return None, {"error": str(e)}
152
+ d = self.state.get((mid, inn, balls))
153
+ if d is None:
154
+ return None, {"error": f"no record for innings {inn} after {overs_str(balls)} overs in match {mid}"}
155
+ return d, None
156
+
157
+ def get_score(self, match_id, innings, overs):
158
+ d, err = self._state(match_id, innings, overs)
159
+ if err:
160
+ return err
161
+ m = self.matches[int(match_id)]
162
+ inn = int(innings)
163
+ return {"match_id": int(match_id), "innings": inn,
164
+ "batting_team": m["bat_first"] if inn == 1 else m["bat_second"],
165
+ "bowling_team": m["bat_second"] if inn == 1 else m["bat_first"],
166
+ "overs": overs_str(d["balls_bowled"]), "balls_bowled": d["balls_bowled"],
167
+ "balls_remaining": 120 - d["balls_bowled"], "runs": d["runs"], "wickets": d["wickets"],
168
+ "target": d.get("target")}
169
+
170
+ def get_batter(self, match_id, innings, overs):
171
+ d, err = self._state(match_id, innings, overs)
172
+ if err:
173
+ return err
174
+ return {"match_id": int(match_id), "innings": int(innings), "overs": overs_str(d["balls_bowled"]),
175
+ "batter": d["striker"], "batter_runs": d["striker_runs"], "batter_balls_faced": d["striker_balls"],
176
+ "bowler": d["bowler"]}
177
+
178
+ def call(self, name, args):
179
+ """Dispatch a tool call by name with a dict of arguments. Never raises."""
180
+ try:
181
+ if name == "find_match":
182
+ return self.find_match(args.get("team_a"), args.get("team_b"), args.get("date"))
183
+ if name == "get_score":
184
+ return self.get_score(args.get("match_id"), args.get("innings"), args.get("overs"))
185
+ if name == "get_batter":
186
+ return self.get_batter(args.get("match_id"), args.get("innings"), args.get("overs"))
187
+ if name == "calculate":
188
+ return {"value": calculate(args.get("expression"))}
189
+ return {"error": f"unknown tool {name}"}
190
+ except Exception as e: # noqa: BLE001
191
+ return {"error": f"{type(e).__name__}: {e}"[:200]}
192
+
193
+
194
+ # ---------------------------------------------------------------- answers
195
+ RATE_TOL = 0.011 # rates are rounded to 2 decimals; allow one unit of rounding difference
196
+ _NUM = r"[-+]?\d[\d,]*(?:\.\d+)?"
197
+
198
+
199
+ def parse_answer(text):
200
+ """Number on the LAST 'Final answer:' line of the reply, or None."""
201
+ if not text:
202
+ return None
203
+ hits = re.findall(rf"Final answer\s*:\s*\**\s*({_NUM})", text, flags=re.I)
204
+ if not hits:
205
+ return None
206
+ try:
207
+ return float(hits[-1].replace(",", ""))
208
+ except ValueError:
209
+ return None
210
+
211
+
212
+ def is_correct(pred, gold, kind) -> bool:
213
+ if pred is None:
214
+ return False
215
+ if kind == "int":
216
+ return abs(pred - gold) < 1e-9
217
+ return abs(pred - gold) <= RATE_TOL
218
+
219
+
220
+ def round_half_up(x: float) -> int:
221
+ return int(math.floor(x + 0.5))
222
+
223
+
224
+ # ---------------------------------------------------------------- task types
225
+ # Every task type: which tool lookups the reference solution makes, the question text, the exact answer and the
226
+ # expression the reference solution passes to `calculate`.
227
+ QTYPES = ("run_rate", "required_rate", "projection", "phase_runs", "phase_rate", "phase_wickets",
228
+ "innings_compare", "strike_rate", "milestone", "batter_share")
229
+ MULTI_POINT = {"phase_runs", "phase_rate", "phase_wickets", "innings_compare", "batter_share"}
230
+
231
+
232
+ def _intro(m, d=None):
233
+ return f"T20 International {m['bat_first']} v {m['bat_second']} at {m['venue']} on {m['date']}."
234
+
235
+
236
+ def _team(m, innings):
237
+ return m["bat_first"] if innings == 1 else m["bat_second"]
238
+
239
+
240
+ def make_task(qtype, m, a, b=None):
241
+ """Build one task. a (and b) are delivery states of match m. Returns None if the type does not apply.
242
+
243
+ Result: {"qtype", "question", "gold", "answer_kind", "lookups": [(tool, args)], "expression"}.
244
+ """
245
+ mid = int(m["match_id"])
246
+ intro = _intro(m)
247
+ team = _team(m, a["innings"])
248
+ pa = overs_str(a["balls_bowled"])
249
+ look_a = ("get_score", {"match_id": mid, "innings": a["innings"], "overs": pa})
250
+ bat_a = ("get_batter", {"match_id": mid, "innings": a["innings"], "overs": pa})
251
+ bb = a["balls_bowled"]
252
+ if qtype == "run_rate":
253
+ q = f"What was {team}'s run rate in runs per over after {pa} overs of their innings? Round to 2 decimal places."
254
+ return _t(qtype, intro, q, round(a["runs"] * 6 / bb, 2), "rate", [look_a], f"round({a['runs']} * 6 / {bb}, 2)")
255
+ if qtype == "required_rate":
256
+ if a["innings"] != 2 or not a.get("target") or a["target"] <= a["runs"] or bb >= 120:
257
+ return None
258
+ need, rem = a["target"] - a["runs"], 120 - bb
259
+ q = (f"{team} were chasing. After {pa} overs of the chase, what run rate (runs per over) did they need over "
260
+ f"the rest of their 20 overs to reach the target? Round to 2 decimal places.")
261
+ return _t(qtype, intro, q, round(need * 6 / rem, 2), "rate", [look_a], f"round(({a['target']} - {a['runs']}) * 6 / {rem}, 2)")
262
+ if qtype == "projection":
263
+ q = (f"Take {team}'s run rate after {pa} overs of their innings (runs so far divided by overs bowled so far). "
264
+ f"If they had kept scoring at exactly that rate for all 20 overs, what total would they have finished on? "
265
+ f"Round to the nearest whole run (halves round up).")
266
+ return _t(qtype, intro, q, round_half_up(a["runs"] * 120 / bb), "int", [look_a], f"floor({a['runs']} * 120 / {bb} + 0.5)")
267
+ if qtype == "strike_rate":
268
+ if a["striker_balls"] < 1:
269
+ return None
270
+ q = (f"Look at the delivery that completed {pa} overs of {team}'s innings. What was the strike rate (runs per "
271
+ f"100 balls faced) of the batter on strike at that point? Round to 2 decimal places.")
272
+ return _t(qtype, intro, q, round(a["striker_runs"] * 100 / a["striker_balls"], 2), "rate", [bat_a],
273
+ f"round({a['striker_runs']} * 100 / {a['striker_balls']}, 2)")
274
+ if qtype == "milestone":
275
+ br, bf = a["striker_runs"], a["striker_balls"]
276
+ if br < 1 or bf < 4:
277
+ return None
278
+ ms = (br // 50 + 1) * 50
279
+ q = (f"Look at the delivery that completed {pa} overs of {team}'s innings. If the batter on strike had kept "
280
+ f"scoring at their own strike rate up to that point (runs per ball faced), how many more balls would they "
281
+ f"have needed to reach {ms} runs? Round up to a whole number of balls.")
282
+ return _t(qtype, intro, q, -(-(ms - br) * bf // br), "int", [bat_a], f"ceil(({ms} - {br}) * {bf} / {br})")
283
+ if qtype == "batter_share":
284
+ if a["runs"] < 1:
285
+ return None
286
+ q = (f"Look at the delivery that completed {pa} overs of {team}'s innings. What percentage of {team}'s total "
287
+ f"runs at that point had been scored by the batter on strike? Round to 2 decimal places.")
288
+ return _t(qtype, intro, q, round(a["striker_runs"] * 100 / a["runs"], 2), "rate", [look_a, bat_a],
289
+ f"round({a['striker_runs']} * 100 / {a['runs']}, 2)")
290
+ if b is None:
291
+ return None
292
+ pb = overs_str(b["balls_bowled"])
293
+ look_b = ("get_score", {"match_id": mid, "innings": b["innings"], "overs": pb})
294
+ if qtype == "innings_compare":
295
+ if a["innings"] != 2 or b["innings"] != 1 or a["balls_bowled"] != b["balls_bowled"]:
296
+ return None
297
+ other = _team(m, 1)
298
+ q = (f"Compare the two innings at the same stage: after {pa} overs of each innings, how many runs ahead of "
299
+ f"{other} were {team}? Give {team}'s runs minus {other}'s runs (negative if {team} were behind).")
300
+ return _t(qtype, intro, q, a["runs"] - b["runs"], "int", [look_a, look_b], f"{a['runs']} - {b['runs']}")
301
+ if a["innings"] != b["innings"] or b["balls_bowled"] <= a["balls_bowled"]:
302
+ return None
303
+ span = b["balls_bowled"] - a["balls_bowled"]
304
+ if qtype == "phase_runs":
305
+ q = f"How many runs did {team} score between the {pa}-over point and the {pb}-over point of their innings?"
306
+ return _t(qtype, intro, q, b["runs"] - a["runs"], "int", [look_a, look_b], f"{b['runs']} - {a['runs']}")
307
+ if qtype == "phase_rate":
308
+ q = (f"What was {team}'s run rate (runs per over) between the {pa}-over point and the {pb}-over point of "
309
+ f"their innings? Round to 2 decimal places.")
310
+ return _t(qtype, intro, q, round((b["runs"] - a["runs"]) * 6 / span, 2), "rate", [look_a, look_b],
311
+ f"round(({b['runs']} - {a['runs']}) * 6 / {span}, 2)")
312
+ if qtype == "phase_wickets":
313
+ q = f"How many wickets did {team} lose between the {pa}-over point and the {pb}-over point of their innings?"
314
+ return _t(qtype, intro, q, b["wickets"] - a["wickets"], "int", [look_a, look_b], f"{b['wickets']} - {a['wickets']}")
315
+ return None
316
+
317
+
318
+ def _t(qtype, intro, question, gold, kind, lookups, expression):
319
+ return {"qtype": qtype, "question": f"{intro}\n\n{question}", "gold": gold, "answer_kind": kind,
320
+ "lookups": lookups, "expression": expression}
321
+
322
+
323
+ def reference_trace(book: Scorebook, m, task):
324
+ """Reference solution as chat messages: find_match, the lookups, one calculate call, the final answer.
325
+
326
+ Tool results come from the scorebook itself, so the trace is exactly what the environment would return.
327
+ Returns (messages, n_tool_calls). The final number is checked against the task's gold answer by the caller.
328
+ """
329
+ import json
330
+
331
+ msgs = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": task["question"]}]
332
+ calls = [("find_match", {"team_a": m["bat_first"], "team_b": m["bat_second"], "date": m["date"]})]
333
+ calls += list(task["lookups"]) + [("calculate", {"expression": task["expression"]})]
334
+ result = None
335
+ for i, (name, args) in enumerate(calls):
336
+ cid = f"call_{i + 1}"
337
+ result = book.call(name, args)
338
+ msgs.append({"role": "assistant", "content": "", "tool_calls": [
339
+ {"id": cid, "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}]})
340
+ msgs.append({"role": "tool", "tool_call_id": cid, "name": name, "content": json.dumps(result)})
341
+ value = result.get("value") if isinstance(result, dict) else None
342
+ shown = f"{value:.2f}" if task["answer_kind"] == "rate" and value is not None else str(value)
343
+ msgs.append({"role": "assistant", "content": f"Using the scorebook figures, {task['expression']} = {shown}.\n\nFinal answer: {shown}"})
344
+ return msgs, len(calls)
scorebook/deliveries.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a53a9b963b563a831e2d6e53d33999324746c13a4cc274d451d5f015bef48f9
3
+ size 73900948
scorebook/matches.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
stats.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "question_rows": 500000,
3
+ "rows_unusable": 34947,
4
+ "rows_same_delivery": 69538,
5
+ "deliveries": 395515,
6
+ "dedup_in": 395515,
7
+ "dedup_removed": 1,
8
+ "rows_impossible": 813,
9
+ "innings_inconsistent": 0,
10
+ "deliveries_clean": 394701,
11
+ "matches": 1774,
12
+ "task_candidates": 116251,
13
+ "trace_mismatch": 0,
14
+ "tasks_generated": 101098,
15
+ "tasks_invalid": 0,
16
+ "tasks_valid": 101098,
17
+ "source_dataset": "Balab2021/CricketData-T20-Reasoning-Qwen3.8-Full",
18
+ "curator": "nemo-curator 1.4.0",
19
+ "matches_in_scorebook": 1774,
20
+ "deliveries_in_scorebook": 394701,
21
+ "matches_train": 1597,
22
+ "matches_test": 177,
23
+ "tasks_train": 95788,
24
+ "tasks_test": 5310,
25
+ "tasks_benchmark": 600,
26
+ "tasks_by_split_and_type": {
27
+ "train": {
28
+ "run_rate": 9582,
29
+ "required_rate": 9569,
30
+ "projection": 9582,
31
+ "phase_runs": 9578,
32
+ "phase_rate": 9581,
33
+ "phase_wickets": 9580,
34
+ "innings_compare": 9572,
35
+ "strike_rate": 9582,
36
+ "milestone": 9580,
37
+ "batter_share": 9582
38
+ },
39
+ "test": {
40
+ "run_rate": 531,
41
+ "required_rate": 531,
42
+ "projection": 531,
43
+ "phase_runs": 531,
44
+ "phase_rate": 531,
45
+ "phase_wickets": 531,
46
+ "innings_compare": 531,
47
+ "strike_rate": 531,
48
+ "milestone": 531,
49
+ "batter_share": 531
50
+ },
51
+ "benchmark": {
52
+ "run_rate": 60,
53
+ "required_rate": 60,
54
+ "projection": 60,
55
+ "phase_runs": 60,
56
+ "phase_rate": 60,
57
+ "phase_wickets": 60,
58
+ "innings_compare": 60,
59
+ "strike_rate": 60,
60
+ "milestone": 60,
61
+ "batter_share": 60
62
+ }
63
+ },
64
+ "reference_tool_calls_mean": 3.5,
65
+ "settings": {
66
+ "train_per_type": 6,
67
+ "test_per_type": 3,
68
+ "benchmark_per_type": 60,
69
+ "seed": 0
70
+ },
71
+ "seconds": 560.5
72
+ }