File size: 15,128 Bytes
de6f3d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python3
"""Build an NL/Graph/Code variant whose durations and targets match Code minutes.

The pinned raw files are read-only inputs.  Generated training and evaluation
files are written to separate directories so the reproduction data remain
unchanged.
"""
from __future__ import annotations

import argparse
import ast
import hashlib
import json
import re
from collections import Counter
from pathlib import Path


FORMS = ("natural", "graph", "python")
SPLITS = ("train", "test")
STEP_RE = re.compile(r"^(Step \d+\..*?)\s+\(([^()]*)\)\s*$", re.MULTILINE)
DICT_RE = re.compile(r"\{[^\n]+\}")
CODE_INPUT_RE = re.compile(r"adj_list = (\{.*\})\nsource = ([^\n]+)\ntarget = ([^\n]+)")
ANSWER_INSTRUCTION_RE = re.compile(
    r"Then, encode your final answer in <answer></answer> \(e\.g\. <answer>1 min</answer>\)"
)
NUMBER_UNIT_RE = re.compile(r"([-+]?\d+(?:\.\d+)?)\s*([A-Za-z]+)")

MINUTES_PER_UNIT = {
    "second": 1 / 60,
    "seconds": 1 / 60,
    "sec": 1 / 60,
    "minute": 1,
    "minutes": 1,
    "min": 1,
    "hour": 60,
    "hours": 60,
    "day": 1440,
    "days": 1440,
    "week": 10080,
    "weeks": 10080,
    # These match the released Code generator: 30-day months, 365-day years.
    "month": 43200,
    "months": 43200,
    "year": 525600,
    "years": 525600,
}


def sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def read_jsonl(path: Path) -> list[dict]:
    return [json.loads(line) for line in path.open(encoding="utf-8")]


def write_jsonl(path: Path, rows: list[dict]) -> None:
    path.write_text(
        "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows),
        encoding="utf-8",
    )


def code_number(value: object) -> float:
    number = float(value)
    if not (number >= 0):
        raise ValueError(f"invalid Code target: {value!r}")
    return number


def shown_number(value: float) -> str:
    """Use the same compact decimal style as the released Code weights."""
    return str(int(value)) if value.is_integer() else f"{value:.2f}"


def duration_to_code_minutes(text: str) -> float:
    """Convert one released duration phrase, rounding as the Code generator did."""
    matches = list(NUMBER_UNIT_RE.finditer(text))
    if not matches or " ".join(match.group(0) for match in matches) != " ".join(text.split()):
        raise ValueError(f"unsupported duration: {text!r}")
    total = 0.0
    for match in matches:
        unit = match.group(2)
        if unit not in MINUTES_PER_UNIT:
            raise ValueError(f"unsupported duration unit {unit!r} in {text!r}")
        total += float(match.group(1)) * MINUTES_PER_UNIT[unit]
    return round(total, 2)


def align_answer_prompt(question: str) -> str:
    replacement = (
        "Report the result as a number of minutes. Then, encode only that number "
        "in <answer></answer> (e.g. <answer>1</answer>)"
    )
    question, count = ANSWER_INSTRUCTION_RE.subn(replacement, question)
    if count != 1:
        raise ValueError("expected exactly one NL/Graph answer instruction")
    return question


def convert_natural_question(question: str) -> tuple[str, list[float]]:
    minutes: list[float] = []

    def replace(match: re.Match[str]) -> str:
        value = duration_to_code_minutes(match.group(2))
        minutes.append(value)
        return f"{match.group(1)} ({shown_number(value)} minutes)"

    question, count = STEP_RE.subn(replace, question)
    if count == 0:
        raise ValueError("no NL step durations found")
    return align_answer_prompt(question), minutes


def convert_graph_question(question: str) -> tuple[str, list[float]]:
    dictionaries = list(DICT_RE.finditer(question))
    if len(dictionaries) != 2:
        raise ValueError("expected adjacency and duration dictionaries")
    duration_match = dictionaries[1]
    durations = ast.literal_eval(duration_match.group(0))
    converted = {node: f"{shown_number(duration_to_code_minutes(value))} minutes"
                 for node, value in durations.items()}
    question = question[:duration_match.start()] + repr(converted) + question[duration_match.end():]
    return align_answer_prompt(question), [duration_to_code_minutes(value) for value in durations.values()]


def longest_code_path(question: str) -> float:
    match = CODE_INPUT_RE.search(question)
    if not match:
        raise ValueError("could not parse Code inputs")
    adjacency = ast.literal_eval(match.group(1))
    source, target = ast.literal_eval(match.group(2)), ast.literal_eval(match.group(3))
    visiting: set[object] = set()
    memo: dict[object, float] = {}

    def visit(node: object) -> float:
        if node == target:
            return 0.0
        if node in memo:
            return memo[node]
        if node in visiting:
            raise ValueError("Code graph is cyclic")
        visiting.add(node)
        candidates = [float(weight) + visit(next_node)
                      for next_node, weight in adjacency.get(node, [])]
        visiting.remove(node)
        if not candidates:
            raise ValueError(f"Code target is unreachable from node {node!r}")
        memo[node] = max(candidates)
        return memo[node]

    return visit(source)


def assert_graph_code_equivalent(graph_question: str, code_question: str) -> None:
    """Check directed structure and rounded node weights up to a node renaming."""
    dictionaries = DICT_RE.findall(graph_question)
    graph_adj = ast.literal_eval(dictionaries[0])
    graph_labels = ast.literal_eval(dictionaries[1])
    match = CODE_INPUT_RE.search(code_question)
    if not match:
        raise ValueError("could not parse Code inputs")
    code_adj = ast.literal_eval(match.group(1))
    code_source, code_target = ast.literal_eval(match.group(2)), ast.literal_eval(match.group(3))

    graph_nodes = set(graph_adj) | {node for targets in graph_adj.values() for node in targets}
    code_nodes = set(code_adj) | {node for targets in code_adj.values() for node, _ in targets}
    graph_in = Counter(node for targets in graph_adj.values() for node in targets)
    code_in = Counter(node for targets in code_adj.values() for node, _ in targets)
    incoming_weights: dict[object, set[float]] = {node: set() for node in code_nodes}
    for targets in code_adj.values():
        for node, weight in targets:
            incoming_weights[node].add(float(weight))
    if any(len(weights) > 1 for weights in incoming_weights.values()):
        raise ValueError("a Code node has inconsistent incoming weights")

    graph_attr = {node: 0.0 if node in {"START", "END"}
                  else duration_to_code_minutes(graph_labels[node]) for node in graph_nodes}
    code_attr = {}
    for node in code_nodes:
        if node in {code_source, code_target}:
            code_attr[node] = 0.0
        elif not incoming_weights[node]:
            raise ValueError(f"non-source Code node {node!r} has no incoming edge")
        else:
            code_attr[node] = next(iter(incoming_weights[node]))

    graph_edges = {(source, target) for source, targets in graph_adj.items() for target in targets}
    code_edges = {(source, target) for source, targets in code_adj.items() for target, _ in targets}
    if len(graph_nodes) != len(code_nodes) or len(graph_edges) != len(code_edges):
        raise ValueError("Graph/Code node or edge counts differ")

    def signature(node: object, adjacency: dict, indegree: Counter, attrs: dict) -> tuple:
        return (attrs[node], indegree[node], len(adjacency.get(node, [])))

    candidates = {
        node: [other for other in code_nodes
               if signature(node, graph_adj, graph_in, graph_attr)
               == signature(other, code_adj, code_in, code_attr)]
        for node in graph_nodes
    }
    candidates["START"] = [code_source]
    candidates["END"] = [code_target]
    if any(not values for values in candidates.values()):
        raise ValueError("Graph/Code node signatures differ")

    mapping: dict[object, object] = {}
    used: set[object] = set()

    def search() -> bool:
        if len(mapping) == len(graph_nodes):
            return {(mapping[a], mapping[b]) for a, b in graph_edges} == code_edges
        remaining = [node for node in graph_nodes if node not in mapping]
        node = min(remaining, key=lambda item: sum(candidate not in used for candidate in candidates[item]))
        for candidate in candidates[node]:
            if candidate in used:
                continue
            if any(((node, other) in graph_edges) != ((candidate, mapped) in code_edges)
                   or ((other, node) in graph_edges) != ((mapped, candidate) in code_edges)
                   for other, mapped in mapping.items()):
                continue
            mapping[node] = candidate
            used.add(candidate)
            if search():
                return True
            used.remove(candidate)
            del mapping[node]
        return False

    if not search():
        raise ValueError("Graph and Code are not isomorphic after minute conversion")


def build_split(raw_dir: Path, split: str) -> tuple[dict[str, list[dict]], dict[str, list[dict]], dict]:
    raw = {form: read_jsonl(raw_dir / f"asynchow_{form}_{split}.jsonl") for form in FORMS}
    lengths = {form: len(rows) for form, rows in raw.items()}
    if len(set(lengths.values())) != 1:
        raise ValueError(f"unaligned {split} lengths: {lengths}")

    training = {form: [] for form in FORMS}
    evaluation = {form: [] for form in FORMS}
    changed_release_targets = 0
    rounded_targets = 0
    for source_row, (natural, graph, code) in enumerate(zip(*(raw[form] for form in FORMS))):
        code_target = code_number(code["answer"])
        calculated = longest_code_path(code["question"])
        if abs(calculated - code_target) > 1e-6:
            raise ValueError(
                f"{split}:{source_row}: Code graph gives {calculated}, label is {code_target}"
            )
        natural_question, natural_minutes = convert_natural_question(natural["question"])
        graph_question, graph_minutes = convert_graph_question(graph["question"])
        if Counter(natural_minutes) != Counter(graph_minutes):
            raise ValueError(f"{split}:{source_row}: converted NL/Graph durations differ")
        try:
            assert_graph_code_equivalent(graph["question"], code["question"])
        except ValueError as error:
            raise ValueError(f"{split}:{source_row}: {error}") from error

        target = f"<answer>{code_target}</answer>"
        questions = {
            "natural": natural_question,
            "graph": graph_question,
            "python": code["question"],
        }
        for form in FORMS:
            training[form].append({"instruction": questions[form], "input": "", "output": target})
            evaluation[form].append({
                "source_row": source_row,
                "question": questions[form],
                "answer": code_target,
                "source_answer": raw[form][source_row]["answer"],
            })

        # Audit how often Code's rounded target differs from the exact released range.
        endpoints = []
        for value in re.findall(r"datetime\.timedelta\(([^)]*)\)", natural["answer"]):
            fields = {key: float(number) for key, number in re.findall(
                r"(days|seconds|microseconds)\s*=\s*([-+]?\d+(?:\.\d+)?)", value
            )}
            endpoints.append((fields.get("days", 0) * 86400 + fields.get("seconds", 0)
                              + fields.get("microseconds", 0) / 1e6) / 60)
        if len(endpoints) != 2:
            raise ValueError(f"{split}:{source_row}: invalid released answer interval")
        if not (endpoints[0] <= code_target <= endpoints[1]):
            changed_release_targets += 1
        if all(abs(code_target - endpoint) > 1e-9 for endpoint in endpoints):
            rounded_targets += 1

    audit = {
        "examples": lengths["natural"],
        "code_target_outside_released_nl_graph_interval": changed_release_targets,
        "code_target_differs_from_both_exact_interval_endpoints": rounded_targets,
    }
    return training, evaluation, audit


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, default=Path(__file__).parent)
    parser.add_argument("--output-dir", type=Path)
    parser.add_argument("--eval-dir", type=Path)
    args = parser.parse_args()
    root = args.root.resolve()
    raw_dir = root / "raw"
    output_dir = (args.output_dir or root / "data_code_aligned_minutes").resolve()
    eval_dir = (args.eval_dir or root / "eval_code_aligned_minutes").resolve()
    if output_dir == raw_dir or eval_dir == raw_dir:
        raise ValueError("refusing to write generated data into raw/")
    output_dir.mkdir(parents=True, exist_ok=True)
    eval_dir.mkdir(parents=True, exist_ok=True)

    manifest = {
        "variant": "code_aligned_minutes",
        "source": "fangru-lin/procedure_generalization_llm",
        "source_commit": "d9bf3485cd41c1050d33471d922c826f474efec1",
        "policy": {
            "input_units": "NL and Graph durations converted to minutes and rounded to two decimals like Code",
            "targets": "all three forms use the released Code numeric target",
            "months": "30 days",
            "years": "365 days",
            "raw_files_modified": False,
        },
        "raw_sha256": {},
        "splits": {},
    }
    for path in sorted(raw_dir.glob("asynchow_*_*.jsonl")):
        manifest["raw_sha256"][path.name] = sha256(path)

    all_training: dict[str, list[dict]] = {form: [] for form in FORMS}
    for split in SPLITS:
        training, evaluation, audit = build_split(raw_dir, split)
        manifest["splits"][split] = audit
        for form in FORMS:
            if split == "train":
                all_training[form] = training[form]
            write_jsonl(eval_dir / f"asynchow_{form}_{split}.jsonl", evaluation[form])
        print(f"{split}: {audit}")

    dataset_info = {}
    for form in FORMS:
        name = f"asynchow_{form}_code_minutes"
        file_name = f"{name}_train.json"
        (output_dir / file_name).write_text(
            json.dumps(all_training[form], ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
        )
        dataset_info[name] = {
            "file_name": file_name,
            "columns": {"prompt": "instruction", "query": "input", "response": "output"},
        }
    (output_dir / "dataset_info.json").write_text(
        json.dumps(dataset_info, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    manifest["generated_sha256"] = {
        str(path.relative_to(root)): sha256(path)
        for directory in (output_dir, eval_dir)
        for path in sorted(directory.glob("*"))
        if path.is_file() and path != output_dir / "manifest.json"
    }
    (output_dir / "manifest.json").write_text(
        json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    print(f"training data: {output_dir}")
    print(f"evaluation data: {eval_dir}")


if __name__ == "__main__":
    main()