Datasets:
Download dataset.py from OpenWAM-Stanford/LIBERO-CF64k: direct link, hf CLI and curl.
- Browser
- Download file 9.72 kB
-
https://huggingface.co/datasets/OpenWAM-Stanford/LIBERO-CF64k/resolve/main/dataset.py
- Command line
-
hf download hf://datasets/OpenWAM-Stanford/LIBERO-CF64k/dataset.py
-
curl -L -o dataset.py https://huggingface.co/datasets/OpenWAM-Stanford/LIBERO-CF64k/resolve/main/dataset.py
9.72 kB
| """Read and verify the common CF64k download using NumPy and the standard library.""" | |
| import argparse | |
| from collections import Counter | |
| import hashlib | |
| import io | |
| import json | |
| from pathlib import Path | |
| import tarfile | |
| import numpy as np | |
| VIEWS = ("observation.images.agentview_rgb", "observation.images.eye_in_hand_rgb") | |
| SAMPLE_FIELDS = (*VIEWS, "future_actions", "observation.state", "frame_index", "timestamp") | |
| CONTEXT_FIELDS = ("simulator_state",) | |
| def digest(path): | |
| with path.open("rb") as handle: | |
| return hashlib.file_digest(handle, "sha256").hexdigest() | |
| def validate_npz(data, *, context): | |
| with np.load(io.BytesIO(data), allow_pickle=False) as payload: | |
| fields = CONTEXT_FIELDS if context else SAMPLE_FIELDS | |
| if set(payload.files) != set(fields) or len(payload.files) != len(fields): | |
| raise ValueError("Unexpected public NPZ fields") | |
| for field in fields: | |
| array = payload[field] | |
| if array.dtype.hasobject or not np.isfinite(array).all(): | |
| raise ValueError("Nonfinite or object public array") | |
| if context: | |
| state = payload["simulator_state"] | |
| if state.ndim != 1 or state.size < 2 or state.dtype != np.float64: | |
| raise ValueError("Invalid boundary physics state") | |
| return {"state_length": state.size} | |
| shapes = {**{key: ((129, 128, 128, 3), np.uint8) for key in VIEWS}, | |
| "future_actions": ((128, 7), np.float32), | |
| "observation.state": ((129, 8), np.float32), | |
| "frame_index": ((129,), np.int64), "timestamp": ((129,), np.float64)} | |
| for key, (shape, dtype) in shapes.items(): | |
| if payload[key].shape != shape or payload[key].dtype != dtype: | |
| raise ValueError(f"Invalid public array: {key}") | |
| if not np.array_equal(payload["frame_index"], np.arange(129)) or not np.array_equal( | |
| payload["timestamp"], np.arange(129) / 20.0 | |
| ): | |
| raise ValueError("Invalid public control clock") | |
| boundary = hashlib.sha256() | |
| for key in (*VIEWS, "observation.state"): | |
| boundary.update(payload[key][0].tobytes()) | |
| return {"boundary_sha256": boundary.hexdigest()} | |
| class Dataset: | |
| def __init__(self, root): | |
| self.root = Path(root) | |
| self.metadata = json.loads((self.root / "dataset.json").read_text()) | |
| if set(self.metadata) != {"samples", "contexts", "parent_trajectories", "split", | |
| "control_frequency_hz", "duration_seconds", "frames", "actions", | |
| "views", "perturbations", "tasks", "indices"}: | |
| raise ValueError("Unexpected dataset metadata fields") | |
| for key, value in {"samples": 64000, "contexts": 10000, "split": "train", | |
| "control_frequency_hz": 20, "duration_seconds": 6.4, | |
| "frames": 129, "actions": 128, "views": list(VIEWS)}.items(): | |
| if self.metadata[key] != value: | |
| raise ValueError(f"Incorrect dataset contract: {key}") | |
| for name in ("samples.jsonl", "contexts.jsonl", "shards.json"): | |
| if digest(self.root / name) != self.metadata["indices"][name]: | |
| raise ValueError("Index checksum mismatch") | |
| read_rows = lambda name: [json.loads(line) for line in (self.root / name).read_text().splitlines()] | |
| self.samples = read_rows("samples.jsonl") | |
| self.contexts = read_rows("contexts.jsonl") | |
| self.shards = json.loads((self.root / "shards.json").read_text()) | |
| self.entries = {} | |
| for kind, rows, count, fields in ( | |
| ("samples", self.samples, 64000, {"sample_id", "context_id", "task_id", "perturbation"}), | |
| ("contexts", self.contexts, 10000, {"context_id", "task_id", "parent_id", "state_length"}), | |
| ): | |
| id_key = "sample_id" if kind == "samples" else "context_id" | |
| if [row[id_key] for row in rows] != list(range(count)): | |
| raise ValueError("Incomplete or duplicate membership") | |
| for row in rows: | |
| if set(row) != fields | {"path", "shard", "sha256", "bytes"}: | |
| raise ValueError("Unexpected public index fields") | |
| if row["path"] != f"{kind}/{row[id_key]:05d}.npz": | |
| raise ValueError("Invalid member path") | |
| if row["shard"] != f"shards/{kind}-{row[id_key] // 512:05d}.tar": | |
| raise ValueError("Invalid shard assignment") | |
| self.entries[row["path"]] = row | |
| if Counter(row["task_id"] for row in self.samples) != Counter({i: 6400 for i in range(10)}): | |
| raise ValueError("Invalid task composition") | |
| if set(row["parent_id"] for row in self.contexts) != set(range(self.metadata["parent_trajectories"])): | |
| raise ValueError("Invalid parent groups") | |
| for row in self.samples: | |
| if type(row["context_id"]) is not int or not 0 <= row["context_id"] < 10000: | |
| raise ValueError("Invalid context reference") | |
| context = self.contexts[row["context_id"]] | |
| if row["task_id"] != context["task_id"]: | |
| raise ValueError("Sample/context task mismatch") | |
| if dict(Counter(row["perturbation"] for row in self.samples)) != self.metadata["perturbations"]: | |
| raise ValueError("Perturbation counts disagree") | |
| if [row["task_id"] for row in self.metadata["tasks"]] != list(range(10)): | |
| raise ValueError("Invalid task table") | |
| for task in self.metadata["tasks"]: | |
| if set(task) != {"task_id", "prompt", "samples", "simulator_state_length"} or task["samples"] != 6400: | |
| raise ValueError("Invalid task metadata") | |
| expected_shards = {row["shard"] for row in self.entries.values()} | |
| if len(self.shards) != len(expected_shards) or {row["path"] for row in self.shards} != expected_shards: | |
| raise ValueError("Missing or duplicate shard index") | |
| def read(self, sample_id): | |
| """Read one lossless sequence without extracting a tar to disk.""" | |
| row = self.samples[sample_id] | |
| return row, self._read_member(row) | |
| def read_context(self, context_id): | |
| row = self.contexts[context_id] | |
| return row, self._read_member(row) | |
| def _read_member(self, row): | |
| with tarfile.open(self.root / row["shard"]) as archive: | |
| member = archive.getmember(row["path"]) | |
| if not member.isfile() or member.size != row["bytes"]: | |
| raise ValueError("Invalid member") | |
| with archive.extractfile(member) as handle: | |
| data = handle.read() | |
| if hashlib.sha256(data).hexdigest() != row["sha256"]: | |
| raise ValueError("Member checksum mismatch") | |
| validate_npz(data, context="sample_id" not in row) | |
| with np.load(io.BytesIO(data), allow_pickle=False) as payload: | |
| return {key: payload[key] for key in payload.files} | |
| def verify(self): | |
| seen, boundaries = set(), {} | |
| layouts = {task["task_id"]: task["simulator_state_length"] for task in self.metadata["tasks"]} | |
| for index, shard in enumerate(self.shards): | |
| path = self.root / shard["path"] | |
| if path.stat().st_size != shard["bytes"] or digest(path) != shard["sha256"]: | |
| raise ValueError("Archive checksum mismatch") | |
| count = 0 | |
| with tarfile.open(path, "r|") as archive: | |
| for member in archive: | |
| if not member.isfile() or member.name not in self.entries or member.name in seen: | |
| raise ValueError("Unexpected or duplicate member") | |
| row = self.entries[member.name] | |
| if row["shard"] != shard["path"] or member.size != row["bytes"]: | |
| raise ValueError("Wrong member placement or size") | |
| with archive.extractfile(member) as handle: | |
| data = handle.read() | |
| if hashlib.sha256(data).hexdigest() != row["sha256"]: | |
| raise ValueError("Member checksum mismatch") | |
| detail = validate_npz(data, context="sample_id" not in row) | |
| if "sample_id" in row: | |
| boundary = detail["boundary_sha256"] | |
| if boundaries.setdefault(row["context_id"], boundary) != boundary: | |
| raise ValueError("Inconsistent branch boundary") | |
| elif detail["state_length"] != row["state_length"] or row["state_length"] != layouts[row["task_id"]]: | |
| raise ValueError("Wrong physics layout") | |
| seen.add(member.name) | |
| count += 1 | |
| if count != shard["members"]: | |
| raise ValueError("Wrong archive member count") | |
| print(json.dumps({"verified_shards": index + 1, "verified_members": len(seen)}), flush=True) | |
| if seen != self.entries.keys() or set(boundaries) != set(range(10000)): | |
| raise ValueError("Incomplete downloaded data") | |
| return {"status": "verified", "samples": len(self.samples), "contexts": len(self.contexts), | |
| "shards": len(self.shards), "dataset_sha256": digest(self.root / "dataset.json")} | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("root", type=Path) | |
| parser.add_argument("--receipt", type=Path) | |
| args = parser.parse_args() | |
| report = Dataset(args.root).verify() | |
| if args.receipt: | |
| args.receipt.write_text(json.dumps(report, indent=2) + "\n") | |
| print(json.dumps(report), flush=True) | |