XinyueDu commited on
Commit
de6f3d0
·
verified ·
1 Parent(s): dfcbcd4

Add conversion script

Browse files
Files changed (1) hide show
  1. prepare_code_aligned_minutes.py +369 -0
prepare_code_aligned_minutes.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build an NL/Graph/Code variant whose durations and targets match Code minutes.
3
+
4
+ The pinned raw files are read-only inputs. Generated training and evaluation
5
+ files are written to separate directories so the reproduction data remain
6
+ unchanged.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import ast
12
+ import hashlib
13
+ import json
14
+ import re
15
+ from collections import Counter
16
+ from pathlib import Path
17
+
18
+
19
+ FORMS = ("natural", "graph", "python")
20
+ SPLITS = ("train", "test")
21
+ STEP_RE = re.compile(r"^(Step \d+\..*?)\s+\(([^()]*)\)\s*$", re.MULTILINE)
22
+ DICT_RE = re.compile(r"\{[^\n]+\}")
23
+ CODE_INPUT_RE = re.compile(r"adj_list = (\{.*\})\nsource = ([^\n]+)\ntarget = ([^\n]+)")
24
+ ANSWER_INSTRUCTION_RE = re.compile(
25
+ r"Then, encode your final answer in <answer></answer> \(e\.g\. <answer>1 min</answer>\)"
26
+ )
27
+ NUMBER_UNIT_RE = re.compile(r"([-+]?\d+(?:\.\d+)?)\s*([A-Za-z]+)")
28
+
29
+ MINUTES_PER_UNIT = {
30
+ "second": 1 / 60,
31
+ "seconds": 1 / 60,
32
+ "sec": 1 / 60,
33
+ "minute": 1,
34
+ "minutes": 1,
35
+ "min": 1,
36
+ "hour": 60,
37
+ "hours": 60,
38
+ "day": 1440,
39
+ "days": 1440,
40
+ "week": 10080,
41
+ "weeks": 10080,
42
+ # These match the released Code generator: 30-day months, 365-day years.
43
+ "month": 43200,
44
+ "months": 43200,
45
+ "year": 525600,
46
+ "years": 525600,
47
+ }
48
+
49
+
50
+ def sha256(path: Path) -> str:
51
+ return hashlib.sha256(path.read_bytes()).hexdigest()
52
+
53
+
54
+ def read_jsonl(path: Path) -> list[dict]:
55
+ return [json.loads(line) for line in path.open(encoding="utf-8")]
56
+
57
+
58
+ def write_jsonl(path: Path, rows: list[dict]) -> None:
59
+ path.write_text(
60
+ "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows),
61
+ encoding="utf-8",
62
+ )
63
+
64
+
65
+ def code_number(value: object) -> float:
66
+ number = float(value)
67
+ if not (number >= 0):
68
+ raise ValueError(f"invalid Code target: {value!r}")
69
+ return number
70
+
71
+
72
+ def shown_number(value: float) -> str:
73
+ """Use the same compact decimal style as the released Code weights."""
74
+ return str(int(value)) if value.is_integer() else f"{value:.2f}"
75
+
76
+
77
+ def duration_to_code_minutes(text: str) -> float:
78
+ """Convert one released duration phrase, rounding as the Code generator did."""
79
+ matches = list(NUMBER_UNIT_RE.finditer(text))
80
+ if not matches or " ".join(match.group(0) for match in matches) != " ".join(text.split()):
81
+ raise ValueError(f"unsupported duration: {text!r}")
82
+ total = 0.0
83
+ for match in matches:
84
+ unit = match.group(2)
85
+ if unit not in MINUTES_PER_UNIT:
86
+ raise ValueError(f"unsupported duration unit {unit!r} in {text!r}")
87
+ total += float(match.group(1)) * MINUTES_PER_UNIT[unit]
88
+ return round(total, 2)
89
+
90
+
91
+ def align_answer_prompt(question: str) -> str:
92
+ replacement = (
93
+ "Report the result as a number of minutes. Then, encode only that number "
94
+ "in <answer></answer> (e.g. <answer>1</answer>)"
95
+ )
96
+ question, count = ANSWER_INSTRUCTION_RE.subn(replacement, question)
97
+ if count != 1:
98
+ raise ValueError("expected exactly one NL/Graph answer instruction")
99
+ return question
100
+
101
+
102
+ def convert_natural_question(question: str) -> tuple[str, list[float]]:
103
+ minutes: list[float] = []
104
+
105
+ def replace(match: re.Match[str]) -> str:
106
+ value = duration_to_code_minutes(match.group(2))
107
+ minutes.append(value)
108
+ return f"{match.group(1)} ({shown_number(value)} minutes)"
109
+
110
+ question, count = STEP_RE.subn(replace, question)
111
+ if count == 0:
112
+ raise ValueError("no NL step durations found")
113
+ return align_answer_prompt(question), minutes
114
+
115
+
116
+ def convert_graph_question(question: str) -> tuple[str, list[float]]:
117
+ dictionaries = list(DICT_RE.finditer(question))
118
+ if len(dictionaries) != 2:
119
+ raise ValueError("expected adjacency and duration dictionaries")
120
+ duration_match = dictionaries[1]
121
+ durations = ast.literal_eval(duration_match.group(0))
122
+ converted = {node: f"{shown_number(duration_to_code_minutes(value))} minutes"
123
+ for node, value in durations.items()}
124
+ question = question[:duration_match.start()] + repr(converted) + question[duration_match.end():]
125
+ return align_answer_prompt(question), [duration_to_code_minutes(value) for value in durations.values()]
126
+
127
+
128
+ def longest_code_path(question: str) -> float:
129
+ match = CODE_INPUT_RE.search(question)
130
+ if not match:
131
+ raise ValueError("could not parse Code inputs")
132
+ adjacency = ast.literal_eval(match.group(1))
133
+ source, target = ast.literal_eval(match.group(2)), ast.literal_eval(match.group(3))
134
+ visiting: set[object] = set()
135
+ memo: dict[object, float] = {}
136
+
137
+ def visit(node: object) -> float:
138
+ if node == target:
139
+ return 0.0
140
+ if node in memo:
141
+ return memo[node]
142
+ if node in visiting:
143
+ raise ValueError("Code graph is cyclic")
144
+ visiting.add(node)
145
+ candidates = [float(weight) + visit(next_node)
146
+ for next_node, weight in adjacency.get(node, [])]
147
+ visiting.remove(node)
148
+ if not candidates:
149
+ raise ValueError(f"Code target is unreachable from node {node!r}")
150
+ memo[node] = max(candidates)
151
+ return memo[node]
152
+
153
+ return visit(source)
154
+
155
+
156
+ def assert_graph_code_equivalent(graph_question: str, code_question: str) -> None:
157
+ """Check directed structure and rounded node weights up to a node renaming."""
158
+ dictionaries = DICT_RE.findall(graph_question)
159
+ graph_adj = ast.literal_eval(dictionaries[0])
160
+ graph_labels = ast.literal_eval(dictionaries[1])
161
+ match = CODE_INPUT_RE.search(code_question)
162
+ if not match:
163
+ raise ValueError("could not parse Code inputs")
164
+ code_adj = ast.literal_eval(match.group(1))
165
+ code_source, code_target = ast.literal_eval(match.group(2)), ast.literal_eval(match.group(3))
166
+
167
+ graph_nodes = set(graph_adj) | {node for targets in graph_adj.values() for node in targets}
168
+ code_nodes = set(code_adj) | {node for targets in code_adj.values() for node, _ in targets}
169
+ graph_in = Counter(node for targets in graph_adj.values() for node in targets)
170
+ code_in = Counter(node for targets in code_adj.values() for node, _ in targets)
171
+ incoming_weights: dict[object, set[float]] = {node: set() for node in code_nodes}
172
+ for targets in code_adj.values():
173
+ for node, weight in targets:
174
+ incoming_weights[node].add(float(weight))
175
+ if any(len(weights) > 1 for weights in incoming_weights.values()):
176
+ raise ValueError("a Code node has inconsistent incoming weights")
177
+
178
+ graph_attr = {node: 0.0 if node in {"START", "END"}
179
+ else duration_to_code_minutes(graph_labels[node]) for node in graph_nodes}
180
+ code_attr = {}
181
+ for node in code_nodes:
182
+ if node in {code_source, code_target}:
183
+ code_attr[node] = 0.0
184
+ elif not incoming_weights[node]:
185
+ raise ValueError(f"non-source Code node {node!r} has no incoming edge")
186
+ else:
187
+ code_attr[node] = next(iter(incoming_weights[node]))
188
+
189
+ graph_edges = {(source, target) for source, targets in graph_adj.items() for target in targets}
190
+ code_edges = {(source, target) for source, targets in code_adj.items() for target, _ in targets}
191
+ if len(graph_nodes) != len(code_nodes) or len(graph_edges) != len(code_edges):
192
+ raise ValueError("Graph/Code node or edge counts differ")
193
+
194
+ def signature(node: object, adjacency: dict, indegree: Counter, attrs: dict) -> tuple:
195
+ return (attrs[node], indegree[node], len(adjacency.get(node, [])))
196
+
197
+ candidates = {
198
+ node: [other for other in code_nodes
199
+ if signature(node, graph_adj, graph_in, graph_attr)
200
+ == signature(other, code_adj, code_in, code_attr)]
201
+ for node in graph_nodes
202
+ }
203
+ candidates["START"] = [code_source]
204
+ candidates["END"] = [code_target]
205
+ if any(not values for values in candidates.values()):
206
+ raise ValueError("Graph/Code node signatures differ")
207
+
208
+ mapping: dict[object, object] = {}
209
+ used: set[object] = set()
210
+
211
+ def search() -> bool:
212
+ if len(mapping) == len(graph_nodes):
213
+ return {(mapping[a], mapping[b]) for a, b in graph_edges} == code_edges
214
+ remaining = [node for node in graph_nodes if node not in mapping]
215
+ node = min(remaining, key=lambda item: sum(candidate not in used for candidate in candidates[item]))
216
+ for candidate in candidates[node]:
217
+ if candidate in used:
218
+ continue
219
+ if any(((node, other) in graph_edges) != ((candidate, mapped) in code_edges)
220
+ or ((other, node) in graph_edges) != ((mapped, candidate) in code_edges)
221
+ for other, mapped in mapping.items()):
222
+ continue
223
+ mapping[node] = candidate
224
+ used.add(candidate)
225
+ if search():
226
+ return True
227
+ used.remove(candidate)
228
+ del mapping[node]
229
+ return False
230
+
231
+ if not search():
232
+ raise ValueError("Graph and Code are not isomorphic after minute conversion")
233
+
234
+
235
+ def build_split(raw_dir: Path, split: str) -> tuple[dict[str, list[dict]], dict[str, list[dict]], dict]:
236
+ raw = {form: read_jsonl(raw_dir / f"asynchow_{form}_{split}.jsonl") for form in FORMS}
237
+ lengths = {form: len(rows) for form, rows in raw.items()}
238
+ if len(set(lengths.values())) != 1:
239
+ raise ValueError(f"unaligned {split} lengths: {lengths}")
240
+
241
+ training = {form: [] for form in FORMS}
242
+ evaluation = {form: [] for form in FORMS}
243
+ changed_release_targets = 0
244
+ rounded_targets = 0
245
+ for source_row, (natural, graph, code) in enumerate(zip(*(raw[form] for form in FORMS))):
246
+ code_target = code_number(code["answer"])
247
+ calculated = longest_code_path(code["question"])
248
+ if abs(calculated - code_target) > 1e-6:
249
+ raise ValueError(
250
+ f"{split}:{source_row}: Code graph gives {calculated}, label is {code_target}"
251
+ )
252
+ natural_question, natural_minutes = convert_natural_question(natural["question"])
253
+ graph_question, graph_minutes = convert_graph_question(graph["question"])
254
+ if Counter(natural_minutes) != Counter(graph_minutes):
255
+ raise ValueError(f"{split}:{source_row}: converted NL/Graph durations differ")
256
+ try:
257
+ assert_graph_code_equivalent(graph["question"], code["question"])
258
+ except ValueError as error:
259
+ raise ValueError(f"{split}:{source_row}: {error}") from error
260
+
261
+ target = f"<answer>{code_target}</answer>"
262
+ questions = {
263
+ "natural": natural_question,
264
+ "graph": graph_question,
265
+ "python": code["question"],
266
+ }
267
+ for form in FORMS:
268
+ training[form].append({"instruction": questions[form], "input": "", "output": target})
269
+ evaluation[form].append({
270
+ "source_row": source_row,
271
+ "question": questions[form],
272
+ "answer": code_target,
273
+ "source_answer": raw[form][source_row]["answer"],
274
+ })
275
+
276
+ # Audit how often Code's rounded target differs from the exact released range.
277
+ endpoints = []
278
+ for value in re.findall(r"datetime\.timedelta\(([^)]*)\)", natural["answer"]):
279
+ fields = {key: float(number) for key, number in re.findall(
280
+ r"(days|seconds|microseconds)\s*=\s*([-+]?\d+(?:\.\d+)?)", value
281
+ )}
282
+ endpoints.append((fields.get("days", 0) * 86400 + fields.get("seconds", 0)
283
+ + fields.get("microseconds", 0) / 1e6) / 60)
284
+ if len(endpoints) != 2:
285
+ raise ValueError(f"{split}:{source_row}: invalid released answer interval")
286
+ if not (endpoints[0] <= code_target <= endpoints[1]):
287
+ changed_release_targets += 1
288
+ if all(abs(code_target - endpoint) > 1e-9 for endpoint in endpoints):
289
+ rounded_targets += 1
290
+
291
+ audit = {
292
+ "examples": lengths["natural"],
293
+ "code_target_outside_released_nl_graph_interval": changed_release_targets,
294
+ "code_target_differs_from_both_exact_interval_endpoints": rounded_targets,
295
+ }
296
+ return training, evaluation, audit
297
+
298
+
299
+ def main() -> None:
300
+ parser = argparse.ArgumentParser()
301
+ parser.add_argument("--root", type=Path, default=Path(__file__).parent)
302
+ parser.add_argument("--output-dir", type=Path)
303
+ parser.add_argument("--eval-dir", type=Path)
304
+ args = parser.parse_args()
305
+ root = args.root.resolve()
306
+ raw_dir = root / "raw"
307
+ output_dir = (args.output_dir or root / "data_code_aligned_minutes").resolve()
308
+ eval_dir = (args.eval_dir or root / "eval_code_aligned_minutes").resolve()
309
+ if output_dir == raw_dir or eval_dir == raw_dir:
310
+ raise ValueError("refusing to write generated data into raw/")
311
+ output_dir.mkdir(parents=True, exist_ok=True)
312
+ eval_dir.mkdir(parents=True, exist_ok=True)
313
+
314
+ manifest = {
315
+ "variant": "code_aligned_minutes",
316
+ "source": "fangru-lin/procedure_generalization_llm",
317
+ "source_commit": "d9bf3485cd41c1050d33471d922c826f474efec1",
318
+ "policy": {
319
+ "input_units": "NL and Graph durations converted to minutes and rounded to two decimals like Code",
320
+ "targets": "all three forms use the released Code numeric target",
321
+ "months": "30 days",
322
+ "years": "365 days",
323
+ "raw_files_modified": False,
324
+ },
325
+ "raw_sha256": {},
326
+ "splits": {},
327
+ }
328
+ for path in sorted(raw_dir.glob("asynchow_*_*.jsonl")):
329
+ manifest["raw_sha256"][path.name] = sha256(path)
330
+
331
+ all_training: dict[str, list[dict]] = {form: [] for form in FORMS}
332
+ for split in SPLITS:
333
+ training, evaluation, audit = build_split(raw_dir, split)
334
+ manifest["splits"][split] = audit
335
+ for form in FORMS:
336
+ if split == "train":
337
+ all_training[form] = training[form]
338
+ write_jsonl(eval_dir / f"asynchow_{form}_{split}.jsonl", evaluation[form])
339
+ print(f"{split}: {audit}")
340
+
341
+ dataset_info = {}
342
+ for form in FORMS:
343
+ name = f"asynchow_{form}_code_minutes"
344
+ file_name = f"{name}_train.json"
345
+ (output_dir / file_name).write_text(
346
+ json.dumps(all_training[form], ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
347
+ )
348
+ dataset_info[name] = {
349
+ "file_name": file_name,
350
+ "columns": {"prompt": "instruction", "query": "input", "response": "output"},
351
+ }
352
+ (output_dir / "dataset_info.json").write_text(
353
+ json.dumps(dataset_info, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
354
+ )
355
+ manifest["generated_sha256"] = {
356
+ str(path.relative_to(root)): sha256(path)
357
+ for directory in (output_dir, eval_dir)
358
+ for path in sorted(directory.glob("*"))
359
+ if path.is_file() and path != output_dir / "manifest.json"
360
+ }
361
+ (output_dir / "manifest.json").write_text(
362
+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
363
+ )
364
+ print(f"training data: {output_dir}")
365
+ print(f"evaluation data: {eval_dir}")
366
+
367
+
368
+ if __name__ == "__main__":
369
+ main()