Datasets:

Modalities:
Text
Formats:
json
Languages:
English
ArXiv:
License:
File size: 11,992 Bytes
2216567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# Copyright (c) 2026 Salesforce, Inc.
# SPDX-License-Identifier: Apache-2.0
"""Verify the upload bundle and reproduce v25 pre-decode dataset statistics."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import sys
import tarfile
from collections import Counter, defaultdict
from datetime import UTC, datetime
from pathlib import Path

DEFAULT_PACKAGE = Path(__file__).resolve().parents[1]
DEFAULT_REPO = None
EXPECTED_RECORDS = {"train": 176_021, "val": 1_768}
EXPECTED_TRAIN_EPISODES = 26_091


def sha256_file(path: Path, chunk_size: int = 8 * 1024**2) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        while chunk := handle.read(chunk_size):
            digest.update(chunk)
    return digest.hexdigest()


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


def annotation_video(record: dict) -> str:
    user = next(message for message in record["conversations"] if message["role"] == "user")
    return next(item["video"] for item in user["content"] if item["type"] == "video")


def verify_checksums(package: Path) -> dict[str, str]:
    checksum_path = package / "manifests" / "checksums.sha256"
    expected: dict[str, str] = {}
    with checksum_path.open(encoding="utf-8") as handle:
        for line in handle:
            digest, relative = line.rstrip("\n").split("  ", 1)
            if relative in expected:
                raise RuntimeError(f"duplicate checksum entry: {relative}")
            expected[relative] = digest
    for index, (relative, digest) in enumerate(expected.items(), 1):
        path = package / relative
        if not path.is_file():
            raise FileNotFoundError(f"checksummed file is missing: {relative}")
        actual = sha256_file(path)
        if actual != digest:
            raise RuntimeError(f"checksum mismatch: {relative}")
        print(f"[checksum {index}/{len(expected)}] {relative}")
    return expected


def verify_structure(package: Path, verify_tar_members: bool) -> dict:
    with (package / "metadata" / "metadata.json").open(encoding="utf-8") as handle:
        metadata = json.load(handle)
    serialized_metadata = json.dumps(metadata, ensure_ascii=False)
    if "/fsx/" in serialized_metadata:
        raise RuntimeError("portable metadata still contains an internal /fsx/ path")
    if any(isinstance(value, dict) and "path" in value for value in metadata.values()):
        raise RuntimeError("portable metadata still contains a top-level video path field")

    global_rows = load_jsonl(package / "manifests" / "videos.jsonl")
    by_path = {row["path"]: row for row in global_rows}
    if len(by_path) != len(global_rows):
        raise RuntimeError("duplicate paths in global video manifest")
    by_shard: dict[str, set[str]] = defaultdict(set)
    for row in global_rows:
        by_shard[row["shard"]].add(row["path"])
        key = os.path.splitext(row["path"].removeprefix("videos/"))[0]
        if key != row["key"]:
            raise RuntimeError(f"video manifest key mismatch: {row['path']}")
        if key not in metadata:
            raise RuntimeError(f"video manifest key missing metadata: {key}")

    split_summary: dict[str, dict] = {}
    split_references: dict[str, set[str]] = {}
    for split, expected_records in EXPECTED_RECORDS.items():
        annotation_path = package / "annotations" / f"{split}.jsonl"
        references: set[str] = set()
        record_count = 0
        malformed = 0
        with annotation_path.open(encoding="utf-8") as handle:
            for line in handle:
                record_count += 1
                try:
                    relative = annotation_video(json.loads(line))
                except (json.JSONDecodeError, KeyError, StopIteration, TypeError):
                    malformed += 1
                    continue
                path = f"videos/{relative}"
                references.add(path)
                if path not in by_path:
                    raise RuntimeError(f"{split} references unpackaged video: {path}")
        if record_count != expected_records:
            raise RuntimeError(
                f"{split} record count changed: {record_count}, expected {expected_records}"
            )
        split_manifest = load_jsonl(package / "manifests" / f"{split}-videos.jsonl")
        manifest_paths = {row["path"] for row in split_manifest}
        if manifest_paths != references:
            raise RuntimeError(f"{split} manifest does not match annotation references")
        split_references[split] = references
        split_summary[split] = {
            "records": record_count,
            "malformed": malformed,
            "unique_videos": len(references),
        }

    if verify_tar_members:
        for index, (shard, expected_members) in enumerate(sorted(by_shard.items()), 1):
            with tarfile.open(package / shard, mode="r:") as archive:
                actual_members = set(archive.getnames())
            if actual_members != expected_members:
                raise RuntimeError(f"tar membership mismatch: {shard}")
            print(f"[tar {index}/{len(by_shard)}] {shard}")

    return {
        "metadata_entries": len(metadata),
        "unique_videos": len(global_rows),
        "train_val_video_overlap": len(
            split_references["train"] & split_references["val"]
        ),
        "splits": split_summary,
    }


def dataset_stats(package: Path, repo: Path) -> dict:
    sys.path.insert(0, str(repo / "src"))
    from stream_gemma.data import _conversation_and_range, _parse_record
    from stream_gemma.episode import build_v25_episodes, flatten_stream_conversation

    with (package / "metadata" / "metadata.json").open(encoding="utf-8") as handle:
        metadata = json.load(handle)

    output: dict[str, dict] = {}
    for split, stride in (("train", 10), ("val", 1)):
        base: list[tuple[list[dict], range]] = []
        skips: Counter = Counter()
        with (package / "annotations" / f"{split}.jsonl").open(encoding="utf-8") as handle:
            for line in handle:
                try:
                    relative, question, text_stream = _parse_record(json.loads(line))
                except (
                    json.JSONDecodeError,
                    KeyError,
                    StopIteration,
                    TypeError,
                    ValueError,
                ):
                    skips["parse"] += 1
                    continue
                if not question or not text_stream:
                    skips["empty"] += 1
                    continue
                key = os.path.splitext(relative)[0]
                item_metadata = metadata.get(key)
                if item_metadata is None:
                    skips["metadata"] += 1
                    continue
                built = _conversation_and_range(
                    question=question,
                    text_stream=text_stream,
                    metadata=item_metadata,
                    source_fps=1,
                )
                if built is None:
                    skips["conversation"] += 1
                    continue
                base.append(built)

        sampled = base[::stride]
        episodes = 0
        frames = 0
        supervised = Counter()
        state_steps = Counter()
        for base_index, (conversation, _source_range) in enumerate(sampled):
            frame_emits = flatten_stream_conversation(conversation)
            if not frame_emits:
                continue
            seed = (base_index * 0x9E3779B1) & 0xFFFFFFFF
            chunks = build_v25_episodes(
                frame_emits,
                seed=seed,
                frame_fps=1,
                standby_lead_seconds=4,
                drop_first_fire_at_zero=True,
                zero_fire_silence_quota=2,
                keep_first_of_run=True,
                continuation_keep_silence=2,
                continuation_keep_standby=2,
                standby_override_hold=True,
                max_frames=32,
            )
            episodes += len(chunks)
            for chunk in chunks:
                frames += len(chunk.turns)
                for turn in chunk.turns:
                    state_steps[turn["state"]] += 1
                    if turn["learn"]:
                        supervised[turn["state"]] += 1

        response = supervised["Response"]
        supervised_total = sum(supervised.values())
        output[split] = {
            "stride": stride,
            "valid_base_records": len(base),
            "sampled_videos": len(sampled),
            "episodes": episodes,
            "frames": frames,
            "state_steps": dict(state_steps),
            "supervised": dict(supervised),
            "supervised_ratio": {
                state: round(supervised[state] / response, 6)
                for state in ("Silence", "Standby", "Response")
            },
            "response_percent": round(100 * response / supervised_total, 6),
            "skips": dict(skips),
        }

    if output["train"]["episodes"] != EXPECTED_TRAIN_EPISODES:
        raise RuntimeError(
            "v25 train episode count mismatch: "
            f"{output['train']['episodes']}, expected {EXPECTED_TRAIN_EPISODES}"
        )
    return output


def verify_extracted(
    package: Path,
    extracted_root: Path,
    verify_hashes: bool,
) -> dict:
    rows = load_jsonl(package / "manifests" / "videos.jsonl")
    for index, row in enumerate(rows, 1):
        path = extracted_root / row["path"]
        if not path.is_file():
            raise FileNotFoundError(f"extracted video is missing: {path}")
        if path.stat().st_size != row["size"]:
            raise RuntimeError(f"extracted video size mismatch: {path}")
        if verify_hashes and sha256_file(path) != row["sha256"]:
            raise RuntimeError(f"extracted video checksum mismatch: {path}")
        if index % 1000 == 0:
            print(f"[extracted {index}/{len(rows)}]")
    return {"root": str(extracted_root), "videos": len(rows), "hashes": verify_hashes}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--package", type=Path, default=DEFAULT_PACKAGE)
    parser.add_argument("--stream-gemma-repo", type=Path, default=DEFAULT_REPO)
    parser.add_argument("--skip-checksums", action="store_true")
    parser.add_argument("--skip-tar-members", action="store_true")
    parser.add_argument("--skip-dataset-stats", action="store_true")
    parser.add_argument("--extracted-root", type=Path)
    parser.add_argument("--verify-extracted-hashes", action="store_true")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    package = args.package.resolve()
    result = {
        "verified_at": datetime.now(UTC).isoformat(),
        "package": str(package),
    }
    incomplete = list(package.rglob("*.incomplete"))
    if incomplete:
        raise RuntimeError(f"incomplete package files remain: {incomplete[:5]}")
    if not args.skip_checksums:
        result["checksums"] = len(verify_checksums(package))
    result["structure"] = verify_structure(package, not args.skip_tar_members)
    if not args.skip_dataset_stats and args.stream_gemma_repo is not None:
        result["dataset_stats"] = dataset_stats(package, args.stream_gemma_repo.resolve())
    if args.extracted_root:
        result["extracted"] = verify_extracted(
            package,
            args.extracted_root.resolve(),
            args.verify_extracted_hashes,
        )

    output = package / "manifests" / "verification.json"
    temporary = output.with_suffix(".json.incomplete")
    temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
    os.replace(temporary, output)
    print(json.dumps(result, indent=2))
    print("VERIFICATION_COMPLETE")


if __name__ == "__main__":
    main()