Datasets:
Download code/robohome/src/engine/source/packages/benchmark/suite_builder.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/benchmark/suite_builder.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome@86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/benchmark/suite_builder.py
-
curl -L -o suite_builder.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/engine/source/packages/benchmark/suite_builder.py
16.5 kB
| from __future__ import annotations | |
| import json | |
| import os | |
| import shutil | |
| import time | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| from packages.benchmark.domain_randomization import DEFAULT_POLICY, DomainRandomizationCompiler | |
| from packages.benchmark.packager import BenchmarkPackager | |
| from packages.benchmark.portable import refresh_checksums | |
| from packages.benchmark.request import BenchmarkSuiteBuildRequest | |
| from packages.benchmark.suite_matrix import expand_episode_matrix | |
| from packages.benchmark.task_library import load_suite_task_library | |
| from packages.core.files import atomic_write_text | |
| from packages.scene_generation.dependency_graph import ( | |
| DEFAULT_DEPENDENCY_POLICY, | |
| load_dependency_policy, | |
| ) | |
| from packages.scene_generation.orchestrator import GenerationBackend, SceneGenerationOrchestrator | |
| from packages.schemas.models import ( | |
| BenchmarkSuiteManifest, | |
| PredicateSpec, | |
| SceneLayerPlan, | |
| SceneManifest, | |
| TaskEntity, | |
| TaskSpec, | |
| ) | |
| class ValidatedSuiteInputs: | |
| request: BenchmarkSuiteBuildRequest | |
| library_source: Path | |
| asset_source: Path | |
| policy_source: Path | |
| variants: list[Any] | |
| tasks: list[TaskSpec] | |
| asset_lock: dict[str, Any] | |
| randomization_compiler: DomainRandomizationCompiler | |
| scene_task: TaskSpec | |
| report: dict[str, Any] | |
| class BenchmarkSuiteBuilder: | |
| """Build a portable shared-scene suite entirely from declarative inputs.""" | |
| def __init__(self, scene_builder: SceneGenerationOrchestrator | None = None) -> None: | |
| self.scene_builder = scene_builder or SceneGenerationOrchestrator.from_env() | |
| def build( | |
| self, | |
| suite_path: Path, | |
| output_dir: Path, | |
| *, | |
| backend_override: GenerationBackend | None = None, | |
| ) -> BenchmarkSuiteManifest: | |
| started = time.perf_counter() | |
| validated = validate_suite_inputs(suite_path) | |
| request = validated.request | |
| variants = validated.variants | |
| tasks = validated.tasks | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| inputs = output_dir / "inputs" | |
| inputs.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(suite_path, inputs / "suite.yaml") | |
| library_source = validated.library_source | |
| shutil.copy2(library_source, inputs / library_source.name) | |
| asset_source = validated.asset_source | |
| asset_target = inputs / asset_source.name | |
| shutil.copy2(asset_source, asset_target) | |
| if conversion_declared := request.scene.asset_conversions: | |
| conversion_source = _resolve_input(suite_path, str(conversion_declared)) | |
| shutil.copy2(conversion_source, inputs / conversion_source.name) | |
| policy_source = validated.policy_source | |
| frozen_policy = inputs / "domain_randomization_policy.yaml" | |
| shutil.copy2(policy_source, frozen_policy) | |
| dependency_policy_source = Path( | |
| os.environ.get("RHG_SCENE_DEPENDENCY_POLICY", DEFAULT_DEPENDENCY_POLICY) | |
| ).expanduser().resolve() | |
| load_dependency_policy(dependency_policy_source) | |
| shutil.copy2(dependency_policy_source, inputs / "scene_dependency_policy.yaml") | |
| randomization_compiler = validated.randomization_compiler | |
| scene_task = validated.scene_task | |
| backend = backend_override or GenerationBackend(request.scene.backend) | |
| self.scene_builder.backend = backend | |
| shared_dir = output_dir / "shared_scene" | |
| shared_scene = self.scene_builder.build(scene_task, shared_dir, request.robot) | |
| packager = BenchmarkPackager() | |
| max_duration_s = request.runtime.max_duration_s | |
| split = request.output.split | |
| for variant, task in zip(variants, tasks, strict=True): | |
| episode_dir = output_dir / "episodes" / variant.episode_id | |
| _write_episode_composition( | |
| episode_dir, | |
| variant.factor_values, | |
| list(task.metadata.get("scene_overrides", [])), | |
| [item.model_dump(mode="json") for item in task.initial_predicates], | |
| shared_scene.entity_prim_paths, | |
| shared_scene.robot_prim_path, | |
| randomization_compiler, | |
| ) | |
| episode_scene = SceneManifest( | |
| scene_id=shared_scene.scene_id, | |
| task_id=task.task_id, | |
| random_seed=task.random_seed, | |
| layer_plan=SceneLayerPlan(root_layer="root.usda", layers={}), | |
| entity_prim_paths={ | |
| entity.entity_id: shared_scene.entity_prim_paths[entity.entity_id] | |
| for entity in task.entities | |
| }, | |
| robot_prim_path=shared_scene.robot_prim_path, | |
| source_checkpoints={ | |
| **shared_scene.source_checkpoints, | |
| "shared_scene": "../../shared_scene/root.usda", | |
| }, | |
| content_hash=shared_scene.content_hash, | |
| ) | |
| packager.package( | |
| task, | |
| episode_scene, | |
| request.robot, | |
| episode_dir, | |
| benchmark_version=request.benchmark_version, | |
| episode_id=variant.episode_id, | |
| max_duration_s=max_duration_s, | |
| split=split, | |
| factor_values={ | |
| "level": variant.level, | |
| "condition": variant.condition, | |
| **variant.factor_values, | |
| }, | |
| evaluator_policy=request.evaluation.model_dump(exclude_none=True), | |
| ) | |
| manifest = BenchmarkSuiteManifest( | |
| suite_id=request.suite_id, | |
| benchmark_version=request.benchmark_version, | |
| robot_profile=request.robot, | |
| shared_scene_uri="shared_scene/root.usda", | |
| asset_lock_uri=f"inputs/{asset_target.name}", | |
| episodes=variants, | |
| metrics=request.evaluation.metrics, | |
| ) | |
| manifests = output_dir / "manifests" | |
| manifests.mkdir(parents=True, exist_ok=True) | |
| atomic_write_text(manifests / "suite.json", manifest.model_dump_json(indent=2)) | |
| atomic_write_text( | |
| manifests / "build_timing.json", | |
| json.dumps( | |
| { | |
| "schema_version": "1.0", | |
| "episode_count": len(variants), | |
| "frozen_inputs": sorted( | |
| path.name for path in inputs.iterdir() if path.is_file() | |
| ), | |
| "total_duration_s": round(time.perf_counter() - started, 3), | |
| }, | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| + "\n", | |
| ) | |
| refresh_checksums(output_dir) | |
| return manifest | |
| def validate_suite_inputs(suite_path: Path) -> ValidatedSuiteInputs: | |
| """Validate every data-owned suite extension before starting an expensive backend.""" | |
| request = BenchmarkSuiteBuildRequest.from_yaml(suite_path) | |
| library = load_suite_task_library(suite_path, request) | |
| library_source = _resolve_input(suite_path, request.task_library) | |
| asset_source = _resolve_input(suite_path, request.scene.asset_lock) | |
| policy_source = ( | |
| _resolve_input(suite_path, request.scene.domain_randomization_policy) | |
| if request.scene.domain_randomization_policy | |
| else DEFAULT_POLICY.resolve() | |
| ) | |
| variants = expand_episode_matrix(request) | |
| tasks = [library.instantiate(request, variant) for variant in variants] | |
| referenced_templates = {group.template for group in request.episode_groups} | |
| missing_templates = referenced_templates - set(library.templates) | |
| if missing_templates: | |
| raise ValueError(f"suite references missing task templates: {sorted(missing_templates)}") | |
| metadata_only_factors: list[str] = [] | |
| for group in request.episode_groups: | |
| entry = library.templates[group.template] | |
| for variant_set in group.variant_sets: | |
| for factor in variant_set.factors: | |
| bound = ( | |
| factor.name in entry.factor_bindings | |
| or factor.name in entry.scene_factor_bindings | |
| or _contains_template_token(entry.model_dump(mode="json"), factor.name) | |
| ) | |
| if not bound: | |
| metadata_only_factors.append( | |
| f"{group.group_id}.{variant_set.label}.{factor.name}" | |
| ) | |
| entity_signatures: dict[str, tuple[str, str, bool]] = {} | |
| for task in tasks: | |
| for entity in task.entities: | |
| signature = (entity.role, entity.category, entity.required) | |
| previous = entity_signatures.setdefault(entity.entity_id, signature) | |
| if previous != signature: | |
| raise ValueError( | |
| f"shared entity {entity.entity_id!r} changes role/category/required " | |
| "between episode variants" | |
| ) | |
| entity_ids = set(entity_signatures) | |
| for raw in request.scene.base_placements: | |
| predicate = PredicateSpec.model_validate(raw) | |
| referenced = {predicate.subject} | |
| if predicate.object is not None: | |
| referenced.add(predicate.object) | |
| unknown = referenced - entity_ids - {"robot"} | |
| if unknown: | |
| raise ValueError(f"scene base placement references unknown entities: {sorted(unknown)}") | |
| raw_asset_lock = json.loads(asset_source.read_text(encoding="utf-8")) | |
| if not isinstance(raw_asset_lock, dict): | |
| raise ValueError("suite asset lock must contain a JSON object") | |
| asset_lock: dict[str, Any] = raw_asset_lock | |
| for section in ("task_asset_overrides", "procedural_assets"): | |
| records = asset_lock.get(section, {}) | |
| if not isinstance(records, dict): | |
| raise ValueError(f"asset lock {section} must be an object") | |
| unknown = set(records) - entity_ids | |
| if unknown: | |
| raise ValueError(f"asset lock {section} references unknown entities: {sorted(unknown)}") | |
| overrides = asset_lock.get("task_asset_overrides", {}) | |
| invalid_assets = [ | |
| key for key, value in overrides.items() if not isinstance(value, str) or not value | |
| ] | |
| if invalid_assets: | |
| raise ValueError(f"asset lock has invalid asset IDs for: {sorted(invalid_assets)}") | |
| randomization_compiler = DomainRandomizationCompiler(policy_source) | |
| operation_count = 0 | |
| for task in tasks: | |
| operations = list(task.metadata.get("scene_overrides", [])) | |
| randomization_compiler.validate(operations, entity_ids) | |
| operation_count += len(operations) | |
| scene_task = _merge_scene_task(request, tasks, asset_lock=asset_lock) | |
| report = { | |
| "schema_version": "1.0", | |
| "status": "valid", | |
| "suite_id": request.suite_id, | |
| "backend": request.scene.backend, | |
| "episode_count": len(variants), | |
| "task_template_count": len(referenced_templates), | |
| "entity_count": len(entity_ids), | |
| "domain_operation_count": operation_count, | |
| "asset_override_count": len(overrides), | |
| "procedural_asset_count": len(asset_lock.get("procedural_assets", {})), | |
| "metadata_only_factors": metadata_only_factors, | |
| "data_only_extension_points": [ | |
| "scene", | |
| "task_library", | |
| "episode_groups", | |
| "asset_lock", | |
| "domain_randomization_policy", | |
| "robot_profile", | |
| "evaluation", | |
| ], | |
| } | |
| return ValidatedSuiteInputs( | |
| request=request, | |
| library_source=library_source, | |
| asset_source=asset_source, | |
| policy_source=policy_source, | |
| variants=variants, | |
| tasks=tasks, | |
| asset_lock=asset_lock, | |
| randomization_compiler=randomization_compiler, | |
| scene_task=scene_task, | |
| report=report, | |
| ) | |
| def _contains_template_token(value: object, name: str) -> bool: | |
| token = "${" + name + "}" | |
| if isinstance(value, dict): | |
| return any(_contains_template_token(item, name) for item in value.values()) | |
| if isinstance(value, list): | |
| return any(_contains_template_token(item, name) for item in value) | |
| return isinstance(value, str) and token in value | |
| def _resolve_input(suite_path: Path, declared: str) -> Path: | |
| path = Path(declared) | |
| candidates = [path] if path.is_absolute() else [suite_path.parent / path, Path.cwd() / path] | |
| for candidate in candidates: | |
| if candidate.is_file(): | |
| return candidate.resolve() | |
| raise FileNotFoundError(f"suite input does not exist: {declared}") | |
| def _merge_scene_task( | |
| request: BenchmarkSuiteBuildRequest, | |
| tasks: list[TaskSpec], | |
| *, | |
| asset_lock: dict[str, object], | |
| ) -> TaskSpec: | |
| if not tasks: | |
| raise ValueError("suite must contain at least one task") | |
| entities: dict[str, TaskEntity] = {} | |
| for task in tasks: | |
| for entity in task.entities: | |
| previous = entities.get(entity.entity_id) | |
| if previous is not None and previous.role != entity.role: | |
| raise ValueError(f"shared entity {entity.entity_id!r} has conflicting roles") | |
| entities.setdefault(entity.entity_id, entity) | |
| procedural = asset_lock.get("procedural_assets", {}) | |
| if not isinstance(procedural, dict): | |
| raise ValueError("asset lock procedural_assets must be an object") | |
| unknown_procedural = set(procedural) - set(entities) | |
| if unknown_procedural: | |
| raise ValueError( | |
| f"procedural assets reference unknown entities: {sorted(unknown_procedural)}" | |
| ) | |
| for entity_id, geometry in procedural.items(): | |
| entity = entities[entity_id] | |
| entities[entity_id] = entity.model_copy( | |
| update={"attributes": {**entity.attributes, "procedural_geometry": geometry}} | |
| ) | |
| base = tasks[0] | |
| base_placements = [PredicateSpec.model_validate(item) for item in request.scene.base_placements] | |
| scene_description = request.scene.prompt | |
| if room_size := request.scene.room_size_m: | |
| scene_description += f" Exact room dimensions in meters: {room_size}." | |
| return base.model_copy( | |
| update={ | |
| "task_id": f"scene-{request.suite_id}", | |
| "natural_language": scene_description, | |
| "task_type": request.scene.task_type, | |
| "entities": list(entities.values()), | |
| "initial_predicates": base_placements, | |
| "random_seed": request.seed, | |
| "parameters": {}, | |
| "metadata": { | |
| "scene": request.scene.model_dump(mode="json", exclude_none=True), | |
| "suite_id": request.suite_id, | |
| "asset_lock": asset_lock, | |
| }, | |
| } | |
| ) | |
| def _write_episode_composition( | |
| episode_dir: Path, | |
| factor_values: dict[str, str | int | float | bool], | |
| scene_overrides: list[object], | |
| initial_predicates: list[object], | |
| entity_prim_paths: dict[str, str], | |
| robot_prim_path: str, | |
| compiler: DomainRandomizationCompiler, | |
| ) -> None: | |
| layers = episode_dir / "layers" | |
| layers.mkdir(parents=True, exist_ok=True) | |
| override_layer = layers / "episode_overrides.usda" | |
| atomic_write_text(override_layer, '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n') | |
| atomic_write_text( | |
| episode_dir / "root.usda", | |
| '#usda 1.0\n(\n defaultPrim = "World"\n metersPerUnit = 1\n' | |
| " subLayers = [@layers/episode_overrides.usda@, @../../shared_scene/root.usda@]\n" | |
| ' upAxis = "Z"\n)\n', | |
| ) | |
| compiled = compiler.compile( | |
| episode_root=episode_dir / "root.usda", | |
| override_layer=override_layer, | |
| operations=scene_overrides, | |
| entity_prim_paths=entity_prim_paths, | |
| robot_prim_path=robot_prim_path, | |
| ) | |
| manifests = episode_dir / "manifests" | |
| manifests.mkdir(parents=True, exist_ok=True) | |
| atomic_write_text( | |
| manifests / "scene_overrides.json", | |
| json.dumps( | |
| { | |
| "schema_version": "1.1", | |
| "factor_values": factor_values, | |
| "operations": scene_overrides, | |
| "applied_operations": compiled.applied, | |
| "deferred_operations": compiled.deferred, | |
| "policy_uri": "../../inputs/domain_randomization_policy.yaml", | |
| "initial_predicates": initial_predicates, | |
| "application_phase": "before_episode_timer_start", | |
| }, | |
| indent=2, | |
| sort_keys=True, | |
| ) | |
| + "\n", | |
| ) | |