JackAILab's picture
Add files using upload-large-folder tool
6aa6c12 verified
Raw History Blame Contribute Delete
13.4 kB
"""Explicit official-source deployment; independent of the local archive track.
Preparation copies verified files to a new root. Native imports/reset are never
part of preparation or runtime capture. Runtime bytes are pinned by the passed
manifest digest, not claimed to be upstream's recommended package versions.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib
import importlib.metadata
import importlib.util
import json
import os
import shutil
import sys
from pathlib import Path
from benchkit.errors import CompatibilityError
from benchmarks.simBenchmarks.Robotwin.environment import deployment, runtime
TRACK = "official_ea8b211_sapien303_v1"
PROTOCOL = "robotwin-official-ea8b211/clean-fixed-seed/qpos14-rgb320-state14-sapien303/fast-v1"
REVISION = "ea8b21121ebb3cd201ff5b3fe361944ac94eda3f"
SOURCE_INVENTORY = "17574b6a38a5660ec147c3edf0695fe5890cb8f18227d3c41762906cdb2eaed6"
SOURCE_SNAPSHOT = Path(__file__).with_name("official_source_snapshot.json")
SCHEMA = "starvla-rsi.robotwin-official-deployment/v1"
RUNTIME_SCHEMA = "starvla-rsi.robotwin-official-runtime/v1"
VERSIONS = {"sapien": "3.0.3", "mplib": "0.2.1", "toppra": "0.6.3",
"numpy": "1.26.4", "torch": "2.5.1+cu121"}
ASSET_TREES = ("assets/embodiments/aloha-agilex/", "assets/objects/050_bell/",
"assets/objects/060_kitchenpot/")
ASSET_FILES = ("assets/objects/objaverse/list.json", "assets/objects/same.json")
ASSET_REVISION = "3dc3b798668feb99ac61cc9086d84cbcc3d79186"
ASSET_ARCHIVES = {
"embodiments.zip": "85ffeff55a5066def5931224a85cfa3f8abaa1fbf779bd17789a7fb3f85bc789",
"objects.zip": "6aa56b3cf1e1064f7c809308144da36b00815f8b137fef2d7e4de856f8becf27",
}
# 1,547 selected files extracted from both complete SHA-256-verified official ZIPs.
ASSET_INVENTORY = "3e0bb720efcf4a516cbaa14af27f50803d33c2ac4124a0bf25f2ebdbde95c3f5"
def _rows(root, names):
return [{"path": name, "size_bytes": deployment._regular(root, name).stat().st_size,
"sha256": deployment.digest(root / name)} for name in sorted(names)]
def _files(root, *, runtime_package=False):
result = []
for directory, children, names in os.walk(root, followlinks=False):
if runtime_package:
children[:] = [name for name in children if name not in deployment.IGNORED_DIRS]
if any((Path(directory) / name).is_symlink() for name in children):
raise ValueError("unverified package directory symlink")
for name in names:
if not runtime_package or not name.endswith((".pyc", ".pyo")):
result.append((Path(directory) / name).relative_to(root).as_posix())
return sorted(result)
def _verify_rows(root, rows):
names = [deployment._relative(row["path"]) for row in rows]
if len(names) != len(set(names)) or rows != _rows(root, names):
raise ValueError("source, asset or runtime file content differs")
def source_snapshot():
snapshot = deployment._json(SOURCE_SNAPSHOT)
if (snapshot["revision"] != REVISION or snapshot["inventory_sha256"] != SOURCE_INVENTORY
or hashlib.sha256(deployment._canonical(snapshot["files"])).hexdigest() != SOURCE_INVENTORY):
raise ValueError("official source snapshot identity changed")
return snapshot
def capture_runtime():
"""Capture installed package bytes without importing native modules."""
if sys.version.split()[0] != "3.10.12":
raise CompatibilityError("official image track requires Python 3.10.12")
versions = {name: importlib.metadata.version(name) for name in VERSIONS}
if versions != VERSIONS:
raise CompatibilityError("official image track package versions differ")
packages = {}
for name in ("sapien", "mplib", "toppra", "curobo"):
spec = importlib.util.find_spec(name)
if spec is None or spec.origin is None:
raise CompatibilityError(f"missing runtime package {name}")
root = Path(spec.origin).resolve().parent
packages[name] = {"root": str(root), "files": _rows(root, _files(root, runtime_package=True))}
# SAPIEN's sibling binary directory is outside its Python package.
if name == "sapien" and (root.parent / "sapien.libs").is_dir():
libs = root.parent / "sapien.libs"
packages["sapien.libs"] = {"root": str(libs), "files": _rows(libs, _files(libs, runtime_package=True))}
return {"schema_version": RUNTIME_SCHEMA, "python": sys.version.split()[0],
"versions": versions, "packages": packages,
"scope": ("SAPIEN/MPLib/TOPPRA/CuRobo file hashes and listed versions; "
"not driver, all transitive dependencies, JIT or loaded-memory attestation")}
def verify_runtime(document):
if (document.get("schema_version") != RUNTIME_SCHEMA or document.get("python") != "3.10.12"
or document.get("versions") != VERSIONS):
raise CompatibilityError("runtime manifest is not the declared official-source image track")
actual = capture_runtime()
if actual != document:
raise CompatibilityError("installed runtime content differs from deployment manifest")
return actual
def _asset_rows(receipt):
if (receipt.get("repo_id") != "TianxingChen/RoboTwin2.0"
or receipt.get("revision") != ASSET_REVISION):
raise ValueError("asset receipt must bind the official Hugging Face revision")
archives = receipt.get("archives")
if (not isinstance(archives, list) or len(archives) != 2
or {row.get("name"): row.get("sha256") for row in archives} != ASSET_ARCHIVES):
raise ValueError("asset receipt must bind the two official archive SHA-256 hashes")
rows = [row for row in receipt["files"] if row["path"].startswith(ASSET_TREES)
or row["path"] in ASSET_FILES]
if hashlib.sha256(deployment._canonical(rows)).hexdigest() != ASSET_INVENTORY:
raise ValueError("asset file inventory is not the verified official archive extraction")
names = {row["path"] for row in rows}
if (not all(any(name.startswith(tree) for name in names) for tree in ASSET_TREES)
or not set(ASSET_FILES).issubset(names)
or not set(deployment.TEMPLATES).issubset(names)):
raise ValueError("official asset receipt misses clean-task asset closure")
return rows
def prepare(source_root, assets_root, asset_receipt, runtime_snapshot, output):
source_root, assets_root = source_root.resolve(strict=True), assets_root.resolve(strict=True)
output = output.absolute()
if (output.exists() or output != output.resolve() or output.is_relative_to(source_root)
or output.is_relative_to(assets_root)):
raise ValueError("official deployment root must be new and independent")
snapshot = source_snapshot()
_verify_rows(source_root, snapshot["files"])
receipt = deployment._json(asset_receipt)
asset_rows = _asset_rows(receipt)
# assets_root is the directory containing assets/, matching receipt paths.
_verify_rows(assets_root, asset_rows)
runtime_document = deployment._json(runtime_snapshot)
if (runtime_document.get("schema_version") != RUNTIME_SCHEMA
or runtime_document.get("versions") != VERSIONS):
raise ValueError("wrong runtime manifest for official track")
output.mkdir(parents=True, exist_ok=False)
for root, rows in ((source_root, snapshot["files"]), (assets_root, asset_rows)):
for row in rows:
target = output / row["path"]
target.parent.mkdir(parents=True, exist_ok=True)
with deployment._regular(root, row["path"]).open("rb") as reader, target.open("xb") as writer:
shutil.copyfileobj(reader, writer)
for config, template in zip(deployment.CONFIGS, deployment.TEMPLATES, strict=True):
payload = (output / template).read_text()
if "${ASSETS_PATH}" not in payload and "$ASSETS_PATH" not in payload:
raise ValueError("official CuRobo path template has no expected placeholder")
(output / config).write_text(payload.replace("${ASSETS_PATH}", str(output)).replace("$ASSETS_PATH", str(output)))
rows = _rows(output, _files(output))
document = {"schema_version": SCHEMA, "track": TRACK, "root": str(output),
"native_source_revision": REVISION, "source_inventory_sha256": SOURCE_INVENTORY,
"asset_receipt": receipt, "runtime": runtime_document, "files": rows,
"derived_files": list(deployment.CONFIGS)}
(output / "deployment.json").write_text(json.dumps(document, indent=2) + "\n")
return verify(output, deployment.digest(output / "deployment.json"))
def verify(root, manifest_sha256):
root = Path(root).absolute()
if (root != root.resolve(strict=True)
or deployment.digest(deployment._regular(root, "deployment.json")) != manifest_sha256):
raise ValueError("official deployment manifest root/hash differs")
document = deployment._json(root / "deployment.json")
if (document.get("schema_version") != SCHEMA or document.get("track") != TRACK
or document.get("root") != str(root) or document.get("native_source_revision") != REVISION
or document.get("source_inventory_sha256") != SOURCE_INVENTORY):
raise ValueError("official deployment identity differs")
source_rows = source_snapshot()["files"]
_verify_rows(root, source_rows)
asset_rows = _asset_rows(document["asset_receipt"])
_verify_rows(root, [row for row in asset_rows if row["path"] not in deployment.CONFIGS])
expected_paths = {row["path"] for row in source_rows + asset_rows} | set(deployment.CONFIGS)
if {row["path"] for row in document["files"]} != expected_paths:
raise ValueError("official deployment file inventory exceeds the declared closure")
_verify_rows(root, document["files"])
if set(_files(root)) != {row["path"] for row in document["files"]} | {"deployment.json"}:
raise ValueError("official deployment has unrecorded files")
if document.get("derived_files") != list(deployment.CONFIGS):
raise ValueError("unexpected official deployment transformations")
for config, template in zip(deployment.CONFIGS, deployment.TEMPLATES, strict=True):
expected = (root / template).read_text().replace("${ASSETS_PATH}", str(root)).replace("$ASSETS_PATH", str(root))
if (root / config).read_text() != expected:
raise ValueError("official CuRobo template expansion differs")
return {"deployment_root": str(root), "deployment_manifest_sha256": manifest_sha256,
"native_source_revision": REVISION, "source_inventory_sha256": SOURCE_INVENTORY,
"asset_repository": document["asset_receipt"]["repo_id"],
"asset_revision": document["asset_receipt"]["revision"],
"file_count": len(document["files"]), "status": "files_verified_not_native_validated"}
def readiness(root, manifest_sha256):
report = verify(root, manifest_sha256)
document = deployment._json(root / "deployment.json")
return {"deployment": report, "runtime": verify_runtime(document["runtime"]), "native_resets": 0,
"status": "files_verified_not_native_validated"}
def resolved_native_config(root, task):
return runtime.resolved_native_config(root, task, config_directory="env_cfg/task_config")
def create_native(root, task):
# CuRobo is an explicitly byte-pinned installed dependency on this track.
if not sys.dont_write_bytecode:
raise CompatibilityError("start RoboTwin with python -B")
for name, module in tuple(sys.modules.items()):
if name == "envs" or name.startswith("envs."):
filename = getattr(module, "__file__", None)
if filename and not Path(filename).resolve().is_relative_to(root / "envs"):
raise CompatibilityError("native envs already imported from a different root")
sys.path.insert(0, str(root))
with runtime.native_directory(root):
module = importlib.import_module(f"envs.{task}")
if not Path(module.__file__).resolve().is_relative_to(root / "envs"):
raise CompatibilityError("official native module origin differs")
return getattr(module, task)()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
capture = sub.add_parser("capture-runtime")
capture.add_argument("--output", type=Path, required=True)
prepare_parser = sub.add_parser("prepare")
for name in ("source-root", "assets-root", "asset-receipt", "runtime-snapshot", "output"):
prepare_parser.add_argument("--" + name, type=Path, required=True)
check = sub.add_parser("check")
check.add_argument("--root", type=Path, required=True)
check.add_argument("--manifest-sha256", required=True)
args = parser.parse_args(argv)
if args.command == "capture-runtime":
result = capture_runtime()
with args.output.open("x") as stream:
json.dump(result, stream, indent=2)
elif args.command == "prepare":
result = prepare(args.source_root, args.assets_root, args.asset_receipt, args.runtime_snapshot, args.output)
else:
result = verify(args.root, args.manifest_sha256)
print(json.dumps(result, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())