File size: 7,915 Bytes
539087b | 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 | #!/usr/bin/env python3
"""Write a collection out in the layout the world model is trained from.
Run against a collection root -- the directory holding ``<domain>/<task_id>/``
-- and it walks every trajectory it finds. Nothing is read from a VM, so this
is safe to re-run and safe to run while collection continues elsewhere.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
def walked_to_the_end(trajectory: Path) -> bool:
"""Whether every recorded step of this trajectory was reproduced.
Read from the run summary rather than recomputed, because the summary is
what the collector concluded at the time and the pairs file cannot
distinguish "the recording had four steps and we walked four" from "the
recording had nine and we walked four".
"""
for summary in sorted(trajectory.glob("runs/*.json")):
try:
record = json.loads(summary.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
walked = record.get("validated_transition_count")
total = record.get("spine_action_count")
if isinstance(walked, int) and isinstance(total, int) and total > 0:
if record.get("priming_action_count", 0) > 0:
alignment = record.get("initial_alignment")
if alignment is None:
try:
state = json.loads(
(trajectory / "states" / "state_000" / "state.json")
.read_text(encoding="utf-8")
)
alignment = state.get("priming")
except (OSError, ValueError):
alignment = None
if not isinstance(alignment, dict) or alignment.get("passed") is not True:
return False
return walked == total
return False
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--destination", type=Path, required=True)
parser.add_argument("--repository", type=Path, default=Path(__file__).parent.parent)
parser.add_argument(
"--manifest",
type=Path,
action="append",
default=[],
help=(
"a manifest, for the task instruction each prompt needs. "
"Repeatable: a collection may draw on several archives."
),
)
parser.add_argument(
"--collection-mode",
default="",
help="fills `collection_mode` for rows collected before the field existed",
)
parser.add_argument(
"--anchor-agent",
default="",
help=(
"what reached the states: `recording` for a replayed archive, or "
"the model that walked them, e.g. `OpenCUA-7B`"
),
)
parser.add_argument(
"--only-listed",
type=Path,
default=None,
help=(
"a file of `<domain>/<task_id>` lines; deliver only those. A "
"collection root accumulates -- Mode B keeps walking into the same "
"root for days -- so re-exporting all of it would republish "
"trajectories already shipped. This delivers the increment."
),
)
parser.add_argument(
"--full-spine-only",
action="store_true",
help=(
"deliver only trajectories walked end to end. A partial walk "
"stops where the desktop and the recording part company, and its "
"prompts carry a task instruction the trajectory never went on to "
"satisfy -- so the steps are true about the desktop and misleading "
"about the task. The collection keeps them either way; this "
"decides what leaves it."
),
)
parser.add_argument(
"--keep-duplicates", action="store_true",
help="Export every transition, including ones the dataset already "
"carries. Deduplication is on by default because a published "
"set that repeats itself overstates what was collected; this "
"exists for inspecting what would have been removed.")
args = parser.parse_args()
repository = args.repository.resolve()
if str(repository) not in sys.path:
sys.path.insert(0, str(repository))
from guiwm_collector.dataset.export import (
export_trajectory, scan_for_duplicates)
from guiwm_collector.dataset.dedup import Ledger
instructions: dict[str, str] = {}
# One manifest means one archive, so its name can fill in for records
# collected before the provenance field existed. Several means the
# collection is mixed and the export must not guess.
archive_name = ""
if len(args.manifest) == 1 and args.manifest[0].is_file():
archive_name = str(
(json.loads(args.manifest[0].read_text(encoding="utf-8")).get(
"source_archive") or {}).get("name") or ""
)
for source in args.manifest:
if not source.is_file():
continue
manifest = json.loads(source.read_text(encoding="utf-8"))
for task in manifest.get("tasks", []):
path = task.get("task_config_path")
if not path or not Path(path).is_file():
continue
config = json.loads(Path(path).read_text(encoding="utf-8"))
instructions[str(task["task_id"])] = str(config.get("instruction") or "")
wanted: set[str] | None = None
if args.only_listed:
wanted = {line.strip() for line in
args.only_listed.read_text(encoding="utf-8").splitlines()
if line.strip()}
# Which trajectories are in scope has to be settled before anything is
# written, because deduplication is a property of the set: the same
# transition in two tasks is a duplicate only if both tasks are exported.
partial = 0
selected: list[Path] = []
for pairs in sorted(args.source.glob("*/*/pairs.jsonl")):
trajectory = pairs.parent
if wanted is not None and (
f"{trajectory.parent.name}/{trajectory.name}" not in wanted):
continue
if args.full_spine_only and not walked_to_the_end(trajectory):
partial += 1
continue
selected.append(trajectory)
ledger = None
if not args.keep_duplicates:
print(f"scanning {len(selected)} trajectories for duplicates...", flush=True)
ledger = scan_for_duplicates(selected, Ledger())
counts = ledger.counts()
print(" " + " · ".join(f"{k} {v}" for k, v in counts.items()), flush=True)
total_steps = total_skipped = trajectories = 0
total_deduplicated = 0
for trajectory in selected:
task_id = trajectory.name
summary = export_trajectory(
source=trajectory,
destination=args.destination / trajectory.parent.name / task_id,
instruction=instructions.get(task_id, ""),
source_archive=archive_name,
collection_mode=args.collection_mode,
anchor_agent=args.anchor_agent,
ledger=ledger,
)
trajectories += 1
total_steps += summary.steps
total_skipped += summary.skipped
total_deduplicated += summary.deduplicated
print(f"{trajectory.parent.name}/{task_id}: {summary.steps} steps "
f"({summary.skipped} skipped, {summary.deduplicated} duplicate)",
flush=True)
print(f"\n{trajectories} trajectories, {total_steps} steps, "
f"{total_skipped} skipped, {total_deduplicated} deduplicated"
+ (f", {partial} partial trajectories withheld" if partial else "")
+ f" -> {args.destination}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|