File size: 12,741 Bytes
987b273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Regenerate or verify the CHRONO-SHEAF III Hugging Face Dataset Viewer tables.

Uses only the Python standard library. Pass the archived results/ directory
and the dataset repository root. Use --verify to compare without writing.
"""

import argparse
from collections import Counter, defaultdict
import csv
import gzip
import hashlib
import json
import math
from pathlib import Path
import statistics


SWEEPS = (("initial", ""), ("repeat", "repeat"))
CONDITION = {"B": "baseline", "A": "hook"}
SPLITS = {True: "paced", False: "unpaced"}
CONFIGS = {
    "runs": {"observed": "data/runs.jsonl"},
    "input_events": {split: f"data/input_events_{split}.jsonl" for split in SPLITS.values()},
    "frame_timings": {split: f"data/frame_timings_{split}.jsonl" for split in SPLITS.values()},
}
RAW_FIELDS = ["run", "mode", "paced", "kind", "id", "frame", "t0_us", "t1_us",
              "application_return_us"]


def require(check, context):
    if not check:
        raise ValueError(context)


def nearest_rank(numbers, quantile):
    return sorted(numbers)[math.ceil(quantile * len(numbers)) - 1]


def matches(actual, reference, context):
    for key, value in actual.items():
        expected = reference[key]
        if isinstance(value, float):
            equal = math.isclose(value, expected, rel_tol=0, abs_tol=1e-10)
        else:
            equal = value == expected
        require(equal, f"{context}: {key}: calculated {value!r}, archived {expected!r}")


def tagged_run(sweep, info):
    return {
        "sweep": sweep,
        "run_key": f"{sweep}:{info['run']:02d}",
        "run_index": info["run"],
        "condition": CONDITION[info["mode"]],
        "paced": info["paced"],
    }


def parse_run(sweep, info, rows, warmup):
    tags = tagged_run(sweep, info)
    details = dict(field.split("=", 1) for field in info["details"].split())
    require(details["driver"] == "dummy", f"{tags['run_key']}: expected SDL dummy driver")
    total_frames = int(details["frames"])
    total_events = int(details["consumed"])
    require(int(details["warmup"]) == warmup, f"{tags['run_key']}: warm-up mismatch")
    valid_symbols = {"F", "E"}
    require({row["kind"] for row in rows} <= valid_symbols, f"{tags['run_key']}: unknown row kind")
    expected_paced = "1" if info["paced"] else "0"
    for row in rows:
        require(row["mode"] == info["mode"] and row["paced"] == expected_paced,
                f"{tags['run_key']}: archived run labels mismatch")
    frame_rows = sorted(
        (row for row in rows if row["kind"] == "F"), key=lambda row: int(row["frame"])
    )
    event_rows = sorted(
        (row for row in rows if row["kind"] == "E"), key=lambda row: int(row["id"])
    )
    require(len(frame_rows) == total_frames and len(event_rows) == total_events,
            f"{tags['run_key']}: run totals mismatch")
    require(all(int(row["frame"]) == index for index, row in enumerate(frame_rows)),
            f"{tags['run_key']}: invalid frame indices")

    frames = []
    prev_return = 0
    prev_consumed = 0
    for row in frame_rows:
        frame = int(row["frame"])
        consumed = int(row["id"])
        archived_previous = int(row["t0_us"])
        present = int(row["t1_us"])
        application = int(row["application_return_us"])
        require(archived_previous == prev_return < present <= application,
                f"{tags['run_key']} frame {frame}: invalid present sequence")
        require(prev_consumed <= consumed, f"{tags['run_key']} frame {frame}: reversed counter")
        frames.append({
            **tags,
            "frame_index": frame,
            "scored": frame >= warmup,
            "events_consumed_total": consumed,
            "events_consumed_this_frame": consumed - prev_consumed,
            "previous_present_return_us": prev_return or None,
            "present_return_us": present,
            "application_return_us": application,
            "present_return_interval_us": present - prev_return if prev_return else None,
            "post_present_return_us": application - present,
        })
        prev_return = present
        prev_consumed = consumed

    events = []
    for event_id, row in enumerate(event_rows, 1):
        frame_index = int(row["frame"])
        require(int(row["id"]) == event_id and 0 <= frame_index < total_frames,
                f"{tags['run_key']} event {event_id}: invalid identifiers")
        frame = frames[frame_index]
        before = frame["events_consumed_total"] - frame["events_consumed_this_frame"]
        require(before < event_id <= frame["events_consumed_total"],
                f"{tags['run_key']} event {event_id}: conflicting consumption history")
        created = int(row["t0_us"])
        present = int(row["t1_us"])
        require(0 < created <= present == frame["present_return_us"],
                f"{tags['run_key']} event {event_id}: clock or frame join mismatch")
        require(int(row["application_return_us"]) == 0,
                f"{tags['run_key']} event {event_id}: expected event-only sentinel")
        events.append({
            **tags,
            "event_id": event_id,
            "frame_index": frame_index,
            "scored": frame["scored"],
            "event_created_us": created,
            "present_return_us": present,
            "latency_us": present - created,
        })
    require(prev_consumed == total_events, f"{tags['run_key']}: final counter mismatch")

    scored_frames = [row for row in frames if row["scored"]]
    scored_events = [row for row in events if row["scored"]]
    intervals = [row["present_return_interval_us"] / 1000 for row in scored_frames]
    post = [row["post_present_return_us"] / 1000 for row in scored_frames]
    latencies = [row["latency_us"] / 1000 for row in scored_events]
    measure = {
        "events": len(scored_events),
        "frames": len(scored_frames),
        "mean_ms": statistics.mean(latencies),
        "p50_ms": nearest_rank(latencies, 0.50),
        "p95_ms": nearest_rank(latencies, 0.95),
        "p99_ms": nearest_rank(latencies, 0.99),
        "mean_cadence_ms": statistics.mean(intervals),
        "post_delay_over_500us": sum(value > 0.5 for value in post),
        "median_post_delay_ms": nearest_rank(post, 0.50),
    }
    matches(measure, info, tags["run_key"])
    run = {
        **tags,
        "matched_pair": info["run"] // 2 + 1,
        "seed": info["seed"],
        "base_work_us": info["work_us"],
        "video_driver": details["driver"],
        "warmup_frames": warmup,
        "total_frames": total_frames,
        "events_consumed_total": total_events,
        "events_trailing_unconsumed": int(details["trailing"]),
        "scored_frames": measure["frames"],
        "scored_events": measure["events"],
        "mean_event_to_present_return_ms": measure["mean_ms"],
        "p50_event_to_present_return_ms": measure["p50_ms"],
        "p95_event_to_present_return_ms": measure["p95_ms"],
        "p99_event_to_present_return_ms": measure["p99_ms"],
        "mean_present_return_interval_ms": measure["mean_cadence_ms"],
        "scored_frames_post_present_over_500us": measure["post_delay_over_500us"],
        "p50_post_present_return_ms": measure["median_post_delay_ms"],
    }
    return run, frames, events, measure


def paced_groups(details, source, sweep):
    groups = {}
    for code, condition in CONDITION.items():
        rows = [metrics for run, metrics in details if run["condition"] == condition and run["paced"]]
        require(len(rows) == 4, f"{sweep} {condition}: expected four scored paced runs")
        values = {
            k: statistics.mean(row[k] for row in rows)
            for k in ("mean_ms", "mean_cadence_ms", "median_post_delay_ms")
        }
        values.update(
            events=sum(row["events"] for row in rows),
            frames=sum(row["frames"] for row in rows),
            delayed_frames=sum(row["post_delay_over_500us"] for row in rows),
        )
        matches(values, source[code], f"{sweep} {condition}")
        groups[condition] = values
    gain = groups["baseline"]["mean_ms"] - groups["hook"]["mean_ms"]
    return {"conditions": groups, "equal_run_mean_difference_ms": gain}


def as_jsonl(rows):
    return "".join(json.dumps(row, separators=(",", ":")) + "\n" for row in rows).encode()


def checksum(blob):
    return hashlib.sha256(blob).hexdigest()


def generate(results):
    tables = {path: [] for splits in CONFIGS.values() for path in splits.values()}
    manifest = {
        "version": 1,
        "primary_endpoint": "synthetic SDL event timestamp immediately before SDL_PushEvent to underlying SDL_RenderPresent return",
        "scope": "Linux SDL2 software renderer, dummy video driver, no physical click or photon measurement",
        "configurations": CONFIGS,
        "sweeps": {},
        "sources": {},
        "tables": {},
    }
    for sweep, subdirectory in SWEEPS:
        raw_path = results / subdirectory / "sdl_raw.csv.gz"
        summary_path = results / subdirectory / "sdl_summary.json"
        for source in (raw_path, summary_path):
            manifest["sources"][source.relative_to(results).as_posix()] = checksum(source.read_bytes())
        summary = json.loads(summary_path.read_text(encoding="utf-8"))
        with gzip.open(raw_path, "rt", encoding="utf-8", newline="") as handle:
            reader = csv.DictReader(handle)
            require(reader.fieldnames == RAW_FIELDS, f"{sweep}: raw CSV header mismatch")
            by_run = defaultdict(list)
            for row in reader:
                by_run[int(row["run"])].append(row)
        ordered_runs = summary["runs"]
        require([row["run"] for row in ordered_runs] == sorted(by_run) == list(range(10)),
                f"{sweep}: missing or unordered runs")
        combination = "".join(row["mode"] for row in ordered_runs if row["paced"])
        require(combination == summary["order"] == "BAABABBA", f"{sweep}: paced order mismatch")
        require([(row["mode"], row["paced"]) for row in ordered_runs[8:]] == [("B", False), ("A", False)],
                f"{sweep}: unpaced controls mismatch")
        details = []
        for run_info in ordered_runs:
            split = SPLITS[run_info["paced"]]
            run, frames, events, metrics = parse_run(sweep, run_info, by_run[run_info["run"]], summary["warmup_frames"])
            tables[CONFIGS["runs"]["observed"]].append(run)
            tables[CONFIGS["frame_timings"][split]].extend(frames)
            tables[CONFIGS["input_events"][split]].extend(events)
            details.append((run, metrics))
        manifest["sweeps"][sweep] = {
            "paced_order": combination,
            **paced_groups(details, summary["groups"], sweep),
        }

    payloads = {}
    for path, rows in tables.items():
        payload = as_jsonl(rows)
        payloads[path] = payload
        tally = Counter(row.get("scored") for row in rows)
        record = {"rows": len(rows), "sha256": checksum(payload)}
        if True in tally or False in tally:
            record.update(scored_rows=tally[True], warmup_rows=tally[False])
        manifest["tables"][path] = record
    require(manifest["tables"][CONFIGS["input_events"]["paced"]]["scored_rows"] == 7781,
            "total scored paced events must match the published manuscript")
    payloads["DATA_MANIFEST.json"] = (json.dumps(manifest, indent=2) + "\n").encode()
    return payloads, manifest


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--results", type=Path, required=True, help="directory containing archived SDL2 results")
    parser.add_argument("--output", type=Path, default=Path("."), help="destination dataset repository root")
    parser.add_argument("--verify", action="store_true", help="require expected bytes without writing")
    args = parser.parse_args()
    payloads, manifest = generate(args.results)
    for name, content in payloads.items():
        target = args.output / name
        if args.verify:
            require(target.is_file() and target.read_bytes() == content, f"missing or changed output: {target}")
        else:
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_bytes(content)
    print("Viewer tables verified." if args.verify else "Viewer tables generated and archive metrics checked.")
    for name, table in manifest["tables"].items():
        suffix = f", {table['scored_rows']:,} scored" if "scored_rows" in table else ""
        print(f"{name}: {table['rows']:,} rows{suffix}")
    for name, value in manifest["sweeps"].items():
        print(f"{name} paced equal-run mean difference: {value['equal_run_mean_difference_ms']:.5f} ms")


if __name__ == "__main__":
    main()