AngeloWhey's picture
Upload Task-Potential v2 model and inference source
d011890 verified
Raw History Blame Contribute Delete
26.5 kB
"""Whole-episode registry and padded variable-graph transition batches."""
from __future__ import annotations
from collections import OrderedDict
import hashlib
import json
from pathlib import Path
import numpy as np
import torch
from model import encode_text
STATIC = dict(actuator_features=("actuator", 40), actuator_feature_mask=("actuator", 40),
actuator_node=("actuator",), actuator_mask=("actuator",),
node_mask=("node",), node_controlled=("node",), node_geomtype=("node",),
body_com_offset=("node", 3), actuator_joint_anchor_local=("actuator", 3),
actuator_joint_anchor_mask=("actuator", 3), gravity=(3,))
def sha256(path):
value = hashlib.sha256()
with Path(path).open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
value.update(block)
return value.hexdigest()
def partition(group):
number = int(hashlib.sha256(group.encode()).hexdigest()[:8], 16) % 10
return "validation" if number == 0 else "test" if number == 1 else "train"
def instruction_roles(arrays, metadata, nodes):
"""Resolve supplied task grounding without inventing robot-part semantics."""
roles = np.zeros((nodes, 2), np.float32)
if "task_object_mask" in arrays or "task_target_mask" in arrays:
roles[:, 0] = arrays.get("task_object_mask", np.zeros(nodes))
roles[:, 1] = arrays.get("task_target_mask", np.zeros(nodes))
return roles
entities = metadata.get("original_entity_keys")
if entities is not None and len(entities) == nodes:
# These are archive-provided WORLD entity tags used for grounding the
# instruction. No body name, joint name or semantic part label enters
# the learned state encoder.
for index, (category, label) in enumerate(entities):
if category != "actors":
continue
label = str(label).lower()
if label.startswith("goal") or label.startswith("target"):
roles[index, 1] = 1
elif label in ("cube", "block", "ball", "object"):
roles[index, 0] = 1
return roles
candidates = np.asarray(arrays.get("target_node_mask", np.zeros(nodes)), dtype=bool)
if int(candidates.sum()) == 1:
roles[:, 0] = candidates
# Multiple free objects without an instruction-to-entity association are
# ambiguous, not a collection of falsely asserted task objects.
return roles
def task_family(text):
"""Small, source-audited semantic groups for paired outcome supervision.
These groups are task families, never robot/body-part classes. Unknown
instructions remain ungrouped rather than being force-matched.
"""
value = " ".join(str(text).lower().replace("-", " ").split())
if "walk" in value or "locomotion" in value or "velocity" in value:
return "locomotion"
if ("pick up" in value or "pick-up" in value or "pickup" in value or
("grasp" in value and ("lift" in value or "hold" in value))):
return "pickup_object"
if "push" in value and ("target" in value or "marked" in value):
return "push_object_to_target"
if "lift" in value and ("object" in value or "block" in value):
return "pickup_object"
if "move the robot" in value and "target" in value:
return "reach_target"
if "move to the target position" in value:
return "reach_target"
if ("place" in value or "inside the container" in value or "inside its target bin" in value):
return "place_object_in_target"
return None
def outcome_label(source, metadata):
"""Return explicit episode outcome; absence is unknown, never failure."""
if bool(metadata.get("curated_episode_success", False)):
return True, True
if "success" in source:
success = source["success"]
mask = source.get("success_mask", np.zeros_like(success, dtype=bool))
if len(success) and len(mask) and bool(mask[-1]):
return True, bool(success[-1])
if "terminal_success" in source:
return True, bool(source["terminal_success"].item())
return False, False
class EpisodeDataset:
def __init__(self, roots, goal_steps=3, cache_episodes=96):
self.goal_steps = goal_steps
self.cache_limit = cache_episodes
self.cache = OrderedDict()
self.episodes = []
self.split_policy = json.loads(Path(__file__).with_name("DATA_SPLITS.json").read_text(encoding="utf-8"))
seen = set()
for root in map(Path, roots):
paths = [root] if root.is_file() else sorted(root.rglob("*.npz"))
for path in paths:
if path.resolve() in seen:
continue
seen.add(path.resolve())
with np.load(path, allow_pickle=False) as source:
if "node_state" not in source or "feature_mask" not in source:
continue
shape = source["node_state"].shape
if len(shape) != 3 or shape[0] < 2 or shape[-1] != 27:
raise ValueError("Invalid measured graph episode: " + str(path))
metadata = json.loads(str(source["metadata"].item())) if "metadata" in source else {}
outcome_known, outcome = outcome_label(source, metadata)
outcome_pair_id = str(metadata.get("outcome_pair_id", ""))
schema = str(source["schema"].item()) if "schema" in source else metadata.get("schema", "")
text = str(source["task_text"].item()) if "task_text" in source else metadata.get("task_text", "")
if not text:
raise ValueError("Task text is required: " + str(path))
# Source generator uses a fresh numerical body per episode.
group = str(source["embodiment_group"].item()) if "embodiment_group" in source else metadata.get("group_id", "procedural-body/" + path.stem)
split = metadata.get("split", partition(group))
if group.startswith(self.split_policy["h1_seen_embodiment_pretraining"]["embodiment_group_prefix"]):
episode_number = int(path.stem.split("-")[1])
rule = self.split_policy["h1_seen_embodiment_pretraining"]
if episode_number in rule["train_episode_indices"]:
split = "train"
elif episode_number in rule["validation_episode_indices"]:
split = "validation"
else:
raise ValueError("H1 episode outside the explicit seen-body pretraining split")
group += "/recorded-episode-" + str(episode_number)
if schema == self.split_policy["serial_source"]["schema"]:
arm = int(source["source_arm_registry_id"].item())
if arm in self.split_policy["serial_source"]["train_arm_registry_ids"]:
split, expected_split = "train", 0
elif arm in self.split_policy["serial_source"]["validation_arm_registry_ids"]:
split, expected_split = "validation", 1
else:
raise ValueError("Protected or native arm leaked into serial-source fit data")
if int(source["split"].item()) != expected_split:
raise ValueError("Serial source arm/split declaration mismatch")
group = "serial-source/arm-" + str(arm)
split = {"val": "validation", "valid": "validation", 0: "train", 1: "validation", 2: "test"}.get(split, split)
if split not in ("train", "validation", "test"):
raise ValueError("Unknown split: " + str(split))
controls = source["control"].shape[1] if "control" in source else 0
exact = schema in ("rigby.procedural_multitask_physics.v1", "rigby.h1_policy_rollout.v1") or bool(metadata.get("motor_control_recovered", False))
if "dynamics_label_mask" in source:
exact = exact or bool(source["dynamics_label_mask"].any())
domain = "serial" if schema == self.split_policy["serial_source"]["schema"] else "h1" if group.startswith("unitree_h1_") else "procedural" if schema == "rigby.procedural_multitask_physics.v1" else "public"
self.episodes.append(dict(path=path.resolve(), group=str(group), split=split, schema=schema, domain=domain,
task=text, frames=shape[0], nodes=shape[1], actuators=controls, exact_controls=exact,
outcome_known=outcome_known, outcome=outcome, task_family=task_family(text),
outcome_pair_id=outcome_pair_id,
sha256=sha256(path), source_dataset=metadata.get("source_dataset", schema), metadata=metadata))
if not self.episodes:
raise ValueError("No graph episodes")
groups = {}
for episode in self.episodes:
previous = groups.setdefault(episode["group"], episode["split"])
if previous != episode["split"]:
raise ValueError("A source episode/controller group leaks across splits")
self.splits = {name: [i for i, row in enumerate(self.episodes) if row["split"] == name] for name in ("train", "validation", "test")}
self.controlled = {name: [i for i in indices if self.episodes[i]["exact_controls"] and self.episodes[i]["actuators"]] for name, indices in self.splits.items()}
self.observational = {name: [i for i in indices if i not in self.controlled[name]] for name, indices in self.splits.items()}
self.domains = {name: {domain: [i for i in indices if self.episodes[i]["domain"] == domain] for domain in ("serial", "procedural", "h1", "public")} for name, indices in self.splits.items()}
self.outcome_groups = {}
self.matched_outcome_pairs = {}
for split, indices in self.splits.items():
families = {}
matched = {}
for index in indices:
row = self.episodes[index]
if row["task_family"] is not None and row["outcome_known"]:
group = families.setdefault(row["task_family"], {True: [], False: []})
group[row["outcome"]].append(index)
if row["outcome_pair_id"] and row["metadata"].get("counterfactual_pair_verified") is True:
key = (row["task_family"], row["outcome_pair_id"])
pair = matched.setdefault(key, {True: [], False: []})
pair[row["outcome"]].append(index)
self.outcome_groups[split] = {name: group for name, group in families.items()
if group[True] and group[False]}
self.matched_outcome_pairs[split] = [pair for pair in matched.values() if pair[True] and pair[False]]
if not self.splits["train"] or not self.splits["validation"] or not self.controlled["train"]:
raise ValueError("Require train/validation episodes and exact primitive controls on optimization data")
manifest = [{key: str(value) if isinstance(value, Path) else value for key, value in episode.items() if key != "metadata"} for episode in self.episodes]
self.manifest = manifest
# Dataset identity does not depend on workstation-local absolute paths.
portable = [{key: value for key, value in row.items() if key != "path"} for row in manifest]
self.identity = hashlib.sha256(json.dumps(dict(episodes=portable, split_policy=self.split_policy), sort_keys=True).encode()).hexdigest()
def load(self, index):
if index not in self.cache:
with np.load(self.episodes[index]["path"], allow_pickle=False) as source:
self.cache[index] = {key: source[key].copy() for key in source.files if source[key].dtype.kind in "biuf"}
while len(self.cache) > self.cache_limit:
self.cache.popitem(last=False)
self.cache.move_to_end(index)
return self.cache[index]
def sample(self, split, count, rng):
# Frozen strata keep all three exact-control families represented.
result = []
for row in range(count):
domain = ("serial", "procedural", "h1", "public")[row % 4]
candidates = self.domains[split][domain]
candidates = candidates or (self.controlled[split] if row % 4 < 3 else self.observational[split]) or self.splits[split]
episode = int(rng.choice(candidates))
time = int(rng.integers(0, self.episodes[episode]["frames"] - 1))
result.append((episode, time))
return result
def sample_outcome_pairs(self, split, count, rng):
"""Return same-task, same-initial-scene positive/negative examples."""
count = max(0, int(count))
groups = self.matched_outcome_pairs[split]
if count < 2 or not groups:
return []
result = []
while len(result) + 1 < count:
group = groups[int(rng.integers(0, len(groups)))]
positive = int(rng.choice(group[True]))
negative = int(rng.choice(group[False]))
# Counterfactual ranking is valid only at the exactly matched
# initial state. Later states diverge because the policies differ;
# equal frame indices would create a false same-state comparison.
frame = 0
result.extend(((positive, frame), (negative, frame)))
return result
def observation(self, episode_index, frame, delta_t):
row, arrays = self.episodes[episode_index], self.load(episode_index)
n, a = row["nodes"], row["actuators"]
known = arrays["feature_mask"][frame].astype(bool)
state = arrays["node_state"][frame].astype(np.float32)
if state.shape != (n, 27) or not np.isfinite(state).all():
raise ValueError("Non-finite or malformed graph state")
result = dict(node_state=state, feature_mask=known,
node_mask=arrays.get("node_mask", np.ones(n, bool)).astype(bool),
node_controlled=arrays.get("node_controlled", np.zeros(n, bool)).astype(bool),
node_geomtype=arrays.get("node_geomtype", np.full(n, -1, np.int32)),
body_com_offset=arrays.get("body_com_offset", np.zeros((n, 3), np.float32)),
node_com_mask=arrays.get("body_com_offset_mask", arrays.get("node_com_mask", np.full((n, 3), "body_com_offset" in arrays, bool))),
actuator_features=arrays.get("actuator_features", np.zeros((a, 40), np.float32)),
actuator_feature_mask=arrays.get("actuator_feature_mask", np.zeros((a, 40), bool)),
actuator_node=arrays.get("actuator_node", np.full(a, -1, np.int32)),
actuator_mask=arrays.get("actuator_mask", arrays.get("actuator_node", np.full(a, -1)) >= 0).astype(bool),
actuator_state=arrays.get("actuator_state", np.zeros((row["frames"], a, 4), np.float32))[frame],
actuator_state_mask=arrays.get("actuator_state_mask", np.zeros((row["frames"], a, 4), bool))[frame],
actuator_joint_anchor_local=arrays.get("actuator_joint_anchor_local", np.zeros((a, 3), np.float32)),
actuator_joint_anchor_mask=arrays.get("actuator_joint_anchor_mask", np.zeros((a, 3), bool)),
parent_edges=arrays.get("parent_edges", np.empty((0, 2), np.int32)),
gravity=arrays.get("gravity", np.zeros(3, np.float32)),
gravity_mask=arrays.get("gravity_mask", np.full(3, "gravity" in arrays, bool)), delta_t=np.float32(delta_t))
result["instruction_node_roles"] = instruction_roles(arrays, row["metadata"], n)
return result
def batch(self, samples, device):
current, following, goals, control, control_mask, dynamic, cost, cost_mask, text, task_ids, family_ids, pair_ids, continuation_success, outcome_mask, verified_goals, policy_rows = [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []
times = np.linspace(1 / self.goal_steps, 1, self.goal_steps, dtype=np.float32)
task_labels, family_labels = {}, {}
for episode_index, frame in samples:
row, arrays = self.episodes[episode_index], self.load(episode_index)
t = row["frames"] - 1
dt = arrays.get("delta_t", arrays.get("dt", np.zeros(t, np.float32)))
dt_known = arrays.get("dt_mask", np.asarray(dt) > 0).astype(bool)
duration = float(dt[frame])
current.append(self.observation(episode_index, frame, duration))
following.append(self.observation(episode_index, frame + 1, duration))
future_frames = np.maximum(frame + 1, np.rint(frame + times * (t - frame)).astype(int)).clip(0, t)
goals.extend(self.observation(episode_index, int(future), duration) for future in future_frames)
command = arrays.get("control", np.zeros((t, row["actuators"]), np.float32))[frame]
if "dynamics_label_mask" in arrays:
actual = bool(arrays["dynamics_label_mask"][frame])
else:
actual = row["exact_controls"]
dynamics_valid = actual and duration > 0 and bool(dt_known[frame])
known_control = arrays.get("control_mask", np.full((t, row["actuators"]), row["exact_controls"], bool))[frame]
control.append(command)
control_mask.append(known_control.astype(bool))
dynamic.append(dynamics_valid)
terminal_known = "terminal_success" in arrays
terminal_success = bool(arrays["terminal_success"].item()) if terminal_known else False
success = arrays.get("success", np.zeros(t, bool))
success_known = arrays.get("success_mask", np.full(t, terminal_known, bool))
verified_goals.append(terminal_success or (bool(success[-1]) and bool(success_known[-1])) or bool(row["metadata"].get("curated_episode_success", False)))
if bool(row["metadata"].get("curated_episode_success", False)):
continuation_success.append(True)
outcome_mask.append(True)
elif "success" in arrays and len(success) and len(success_known) and bool(success_known[-1]):
continuation_success.append(bool(success[-1]))
outcome_mask.append(True)
else:
continuation_success.append(bool(terminal_success))
outcome_mask.append(bool(terminal_known or row["outcome_known"]))
explicit_policy = arrays.get("policy_label_mask", arrays.get("qualified_recovery_policy_mask"))
policy_rows.append(bool(explicit_policy[frame]) if explicit_policy is not None else verified_goals[-1])
qualified = np.flatnonzero(success[frame:t].astype(bool) & success_known[frame:t].astype(bool))
if len(qualified):
end = min(t, frame + int(qualified[0]) + 1)
measured_cost = float(np.sum(dt[frame:end]))
measured_cost_known = True
elif terminal_known and terminal_success:
measured_cost, measured_cost_known = float(np.sum(dt[frame:t])), True
else:
measured_cost, measured_cost_known = 0., False
end = frame
if measured_cost_known:
end = end if len(qualified) else t
measured_cost_known = bool(np.all(dt_known[frame:end])) and bool(np.all(np.asarray(dt)[frame:end] > 0))
cost.append(measured_cost)
cost_mask.append(measured_cost_known)
text.append(row["task"])
task_ids.append(task_labels.setdefault(row["task"], len(task_labels)))
family_ids.append(family_labels.setdefault(row["task_family"], len(family_labels)) if row["task_family"] is not None else -1)
verified_pair = row["metadata"].get("counterfactual_pair_verified") is True
pair_ids.append(int(hashlib.sha256(row["outcome_pair_id"].encode()).hexdigest()[:15], 16)
if row["outcome_pair_id"] and verified_pair else -1)
n = max(row["node_state"].shape[0] for row in current)
a = max(row["actuator_features"].shape[0] for row in current)
p = max(row["parent_edges"].shape[0] for row in current)
batch = collate_observations(current, n, a, p, device)
batch["next_state"] = collate_observations(following, n, a, p, device)
batch["goal_state"] = collate_observations(goals, n, a, p, device)
batch["control"] = torch.as_tensor(np.stack([np.pad(row, (0, a-len(row))) for row in control]), dtype=torch.float32, device=device)
batch["control_mask"] = torch.as_tensor(np.stack([np.pad(row, (0, a-len(row))) for row in control_mask]), dtype=torch.bool, device=device)
batch["dynamics_label_mask"] = torch.tensor(dynamic, dtype=torch.bool, device=device)
batch["value_cost"] = torch.tensor(cost, dtype=torch.float32, device=device)
batch["value_mask"] = torch.tensor(cost_mask, dtype=torch.bool, device=device)
batch["text_tokens"], batch["text_mask"] = encode_text(text, device=device)
batch["task_group"] = torch.tensor(task_ids, dtype=torch.long, device=device)
batch["task_family"] = torch.tensor(family_ids, dtype=torch.long, device=device)
batch["outcome_pair_group"] = torch.tensor(pair_ids, dtype=torch.long, device=device)
batch["continuation_success"] = torch.tensor(continuation_success, dtype=torch.float32, device=device)
batch["outcome_mask"] = torch.tensor(outcome_mask, dtype=torch.bool, device=device)
batch["goal_times"] = torch.tensor(np.repeat(times[None], len(samples), axis=0), device=device)
batch["goal_target_mask"] = torch.tensor(np.repeat(np.asarray(verified_goals)[:, None], self.goal_steps, axis=1), device=device, dtype=torch.bool)
batch["policy_label_mask"] = torch.tensor(policy_rows, device=device, dtype=torch.bool)
audit = dict(domain={}, task={}, body={}, exact_control_rows=int(sum(dynamic)),
known_control_scalars=int(batch["control_mask"].sum()), verified_goal_frames=int(batch["goal_target_mask"].sum()),
qualified_policy_rows=int((batch["policy_label_mask"] & batch["dynamics_label_mask"]).sum()),
qualified_policy_control_scalars=int((batch["control_mask"] & batch["policy_label_mask"][:, None] & batch["dynamics_label_mask"][:, None]).sum()),
known_outcome_rows=int(batch["outcome_mask"].sum()),
successful_outcome_rows=int((batch["outcome_mask"] & batch["continuation_success"].bool()).sum()),
failed_outcome_rows=int((batch["outcome_mask"] & ~batch["continuation_success"].bool()).sum()),
measured_value_rows=int(batch["value_mask"].sum()))
for episode_index, _ in samples:
row = self.episodes[episode_index]
for name, key in (("domain", row["domain"]), ("task", row["task"]), ("body", row["group"])):
audit[name][key] = audit[name].get(key, 0) + 1
batch["_audit"] = audit
return batch
def summary(self):
return dict(schema="rigby.variable_relationship_graph.v2", dataset_sha256=self.identity,
episodes=len(self.episodes), transitions=sum(row["frames"]-1 for row in self.episodes),
splits={name: dict(episodes=len(indices), exact_control_episodes=len(self.controlled[name]),
observed_trajectory_episodes=len(self.observational[name])) for name, indices in self.splits.items()},
nodes=sorted(set(row["nodes"] for row in self.episodes)), actuators=sorted(set(row["actuators"] for row in self.episodes)),
task_texts=sorted(set(row["task"] for row in self.episodes)),
grounding="supplied instruction object/target bindings; not learned text grounding",
split_policy=self.split_policy,
domain_counts={name: {domain: len(indices) for domain, indices in groups.items()} for name, groups in self.domains.items()},
goals="only verified successful trajectory futures supervise text goals; unknown/failed futures are reconstruction/dynamics targets only",
outcomes={split: {family: {"success": len(group[True]), "failure": len(group[False])}
for family, group in self.outcome_groups[split].items()} for split in self.splits},
matched_counterfactual_pairs={split: len(groups) for split, groups in self.matched_outcome_pairs.items()},
controls="original public task-space actions are never treated as motor controls",
split_limit="public demonstrations hold out episodes/controller groups, not their shared robot embodiment")
def collate_observations(rows, n, a, p, device):
node_keys = {"node_state", "feature_mask", "node_mask", "node_controlled", "node_geomtype", "body_com_offset", "node_com_mask", "instruction_node_roles"}
actuator_keys = {"actuator_features", "actuator_feature_mask", "actuator_node", "actuator_mask", "actuator_state", "actuator_state_mask", "actuator_joint_anchor_local", "actuator_joint_anchor_mask"}
result = {}
for name in rows[0]:
padded = []
for row in rows:
value = np.asarray(row[name])
size = n if name in node_keys else a if name in actuator_keys else p if name == "parent_edges" else None
if size is not None:
pad = [(0, size - len(value))] + [(0, 0)] * (value.ndim - 1)
value = np.pad(value, pad, constant_values=-1 if name in ("actuator_node", "node_geomtype") else 0)
padded.append(value)
values = np.stack(padded)
dtype = torch.bool if values.dtype.kind == "b" else torch.long if name in ("actuator_node", "node_geomtype", "parent_edges") else torch.float32
result[name] = torch.as_tensor(values, dtype=dtype, device=device)
result["parent_edge_mask"] = torch.tensor(np.stack([np.arange(p) < len(row["parent_edges"]) for row in rows]), dtype=torch.bool, device=device)
return result