feat: release guided Go2 standing skill with explicit drift waiver
Add loaded-standing physics, PPO training, fixed-candidate acceptance, isolated inference, and fail-closed publication. Preserve the original 120-second drift failure and bind the operator-approved exception to the exact candidate and evidence. Include pending Reach training/release infrastructure and archived packages. Leave pre-existing short-worker visualization changes and large generated training artifacts out of this commit.
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
"""Self-contained SkillBundle-v1 reader. Only Python stdlib and PyTorch required.
|
||||
|
||||
This file is copied verbatim into each immutable release. No project/Kit import.
|
||||
SHA256 detects corruption; it is not a signature or a sandbox for untrusted code.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
class Actor(nn.Module):
|
||||
def __init__(self, hidden=128):
|
||||
super().__init__()
|
||||
self.register_buffer("mean", torch.zeros(15))
|
||||
self.register_buffer("std", torch.ones(15))
|
||||
self.net = nn.Sequential(
|
||||
nn.Linear(15, hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, 3)
|
||||
)
|
||||
|
||||
def forward(self, state):
|
||||
return self.net((state - self.mean) / self.std).tanh()
|
||||
|
||||
|
||||
def file_hash(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
class FrozenPolicy:
|
||||
"""Stateless deterministic leg-token-v1 -> float32 [B,8] normalized PD command.
|
||||
|
||||
Caller owns sensor sampling, last-applied action, goal validity and 100Hz clock.
|
||||
The package binds exact static geometry/controller/units, not just tensor shapes.
|
||||
"""
|
||||
|
||||
def __init__(self, directory, *, part_id, manifest_sha256, device="cpu"):
|
||||
root = Path(directory).resolve()
|
||||
manifest = json.loads((root / "manifest.json").read_text())
|
||||
if manifest["format"] != "skillfactory.skillbundle.v1" or manifest["interface"] != "go2-fl-reach-leg-token-v1":
|
||||
raise ValueError("Unsupported bundle/interface version")
|
||||
if sys.version_info[:2] != (3, 12) or torch.__version__.split("+")[0] != "2.10.0":
|
||||
raise RuntimeError("Validated dependency range: Python 3.12, torch 2.10.0")
|
||||
for name, digest in manifest["files"].items():
|
||||
path = (root / name).resolve()
|
||||
if not path.is_relative_to(root) or not path.is_file() or file_hash(path) != digest:
|
||||
raise ValueError(f"Bundle integrity failure: {name}")
|
||||
required = {"actor.pt", "binding.json", "frozen_policy.py", "config.json", "README.md"}
|
||||
if not required.issubset(manifest["files"]):
|
||||
raise ValueError("Missing required integrity entries")
|
||||
self.binding = json.loads((root / "binding.json").read_text())
|
||||
if part_id != self.binding["part_id"] or manifest_sha256 != self.binding["manifest_sha256"]:
|
||||
raise ValueError("Unsupported hardware binding")
|
||||
self.device = torch.device(device)
|
||||
self._actor = Actor(manifest["hidden"]).to(self.device)
|
||||
self.device = next(self._actor.parameters()).device
|
||||
self._actor.load_state_dict(
|
||||
torch.load(root / "actor.pt", map_location=self.device, weights_only=True), strict=True
|
||||
)
|
||||
self._actor.eval().requires_grad_(False)
|
||||
if any(not torch.isfinite(v).all() for v in self._actor.state_dict().values()) or (self._actor.std <= 0).any():
|
||||
raise ValueError("Invalid weights or normalization state")
|
||||
self._static = {
|
||||
k: torch.tensor(v, device=self.device, dtype=torch.bool if "mask" in k else torch.float32)
|
||||
for k, v in self.binding["static_tokens"].items()
|
||||
}
|
||||
self._context = torch.tensor(self.binding["context"], device=self.device, dtype=torch.float32)
|
||||
self.version = manifest["version"]
|
||||
|
||||
@torch.inference_mode()
|
||||
def act(self, tokens):
|
||||
shapes = {
|
||||
"joint_description": (8, 25),
|
||||
"joint_observation": (8, 3),
|
||||
"joint_mask": (8,),
|
||||
"effector_description": (1, 16),
|
||||
"effector_observation": (1, 11),
|
||||
"effector_mask": (1,),
|
||||
"context": (10,),
|
||||
"goal": (3,),
|
||||
}
|
||||
if set(tokens) != set(shapes):
|
||||
raise ValueError("Require all and only leg-token-v1 fields")
|
||||
first = tokens["goal"]
|
||||
if not isinstance(first, torch.Tensor) or first.ndim != 2 or len(first) < 1:
|
||||
raise ValueError("Require nonempty batched tensors")
|
||||
count = len(first)
|
||||
for key, shape in shapes.items():
|
||||
value = tokens[key]
|
||||
dtype = torch.bool if "mask" in key else torch.float32
|
||||
if (
|
||||
not isinstance(value, torch.Tensor)
|
||||
or value.shape != (count, *shape)
|
||||
or value.dtype != dtype
|
||||
or value.device != self.device
|
||||
):
|
||||
raise ValueError(f"Bad shape/dtype/device: {key}")
|
||||
# Padded garbage is deliberately ignored; valid entities must be finite.
|
||||
active = value[:, :3] if key.startswith("joint_") else value
|
||||
if not torch.isfinite(active).all():
|
||||
raise ValueError(f"Non-finite active input: {key}")
|
||||
for key, expected in self._static.items():
|
||||
actual = tokens[key]
|
||||
if key == "joint_description":
|
||||
actual, expected = actual[:, :3], expected[:3]
|
||||
if not torch.equal(actual, expected.expand_as(actual)):
|
||||
raise ValueError(f"Static binding mismatch: {key}")
|
||||
if not torch.allclose(tokens["context"], self._context.expand_as(tokens["context"]), atol=1e-5, rtol=0):
|
||||
raise ValueError("Context mismatch: fixed suspended anchor/control period/physical scales required")
|
||||
x = torch.cat(
|
||||
(tokens["joint_observation"][:, :3].flatten(1), tokens["effector_observation"][:, 0, :3], tokens["goal"]),
|
||||
-1,
|
||||
)
|
||||
result = torch.zeros(count, 8, device=self.device, dtype=torch.float32)
|
||||
result[:, :3] = self._actor(x)
|
||||
if not torch.isfinite(result).all():
|
||||
raise RuntimeError("Non-finite policy output")
|
||||
return result
|
||||
|
||||
@torch.inference_mode()
|
||||
def position_targets(self, tokens):
|
||||
"""Native declared-order rad targets. Actual driver must still enforce torque/velocity limits."""
|
||||
action = self.act(tokens)[:, :3].clamp(-1, 1)
|
||||
controls = self.binding["spec"]["joints"]
|
||||
nominal = action.new_tensor([j["q_default"] for j in controls])
|
||||
scale = action.new_tensor([j["action_scale"] for j in controls])
|
||||
soft = action.new_tensor([j["soft_limits"] for j in self.binding["joints"]])
|
||||
return (nominal + scale * action).clamp(min=soft[:, 0], max=soft[:, 1])
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Package-only guided standing inference. Python stdlib + Torch, no simulator/project imports.
|
||||
|
||||
SHA256 is an integrity check, not a signature. Caller owns the validated 100Hz
|
||||
clock, xyzw sensor frames, last action, driver limits and floating guided rig.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
CONTRACT = "go2-fl-loaded-stand-v0"
|
||||
SHAPES = {
|
||||
"joint_state": (3, 3),
|
||||
"base_state": (13,),
|
||||
"mount_wrench": (6,),
|
||||
"foot_state": (10,),
|
||||
"guide_wrench": (6,),
|
||||
"goal": (1,),
|
||||
}
|
||||
CORE = {
|
||||
"actor.pt",
|
||||
"frozen_standing.py",
|
||||
"binding.json",
|
||||
"task.json",
|
||||
"training.json",
|
||||
"selection.json",
|
||||
"README.md",
|
||||
"requirements.txt",
|
||||
"example.pt",
|
||||
"ASSET_LICENSE",
|
||||
}
|
||||
|
||||
|
||||
def file_hash(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def checked_manifest(root, expected):
|
||||
root = Path(root).resolve()
|
||||
if file_hash(root / "manifest.json") != expected:
|
||||
raise ValueError("Package manifest identity mismatch")
|
||||
m = json.loads((root / "manifest.json").read_text())
|
||||
if m["format"] != "skillfactory.standing-bundle.v1" or m["contract"] != CONTRACT:
|
||||
raise ValueError("Unsupported standing package")
|
||||
if not CORE.issubset(m["files"]):
|
||||
raise ValueError("Missing integrity entries")
|
||||
for name, digest in m["files"].items():
|
||||
path = (root / name).resolve()
|
||||
if not path.is_relative_to(root) or not path.is_file() or file_hash(path) != digest:
|
||||
raise ValueError(f"Bundle integrity failure: {name}")
|
||||
return m
|
||||
|
||||
|
||||
class Actor(nn.Module):
|
||||
def __init__(self, hidden=128):
|
||||
super().__init__()
|
||||
self.register_buffer("offset", torch.zeros(45))
|
||||
self.register_buffer("scale", torch.ones(45))
|
||||
self.actor = nn.Sequential(
|
||||
nn.Linear(45, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(), nn.Linear(hidden, 3)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
return self.actor(((x - self.offset) / self.scale).clamp(-10, 10)).tanh()
|
||||
|
||||
|
||||
class FrozenStanding:
|
||||
def __init__(self, directory, *, manifest_sha256, task_sha256, support_sha256, device="cpu"):
|
||||
root = Path(directory).resolve()
|
||||
m = checked_manifest(root, manifest_sha256)
|
||||
if sys.version_info[:2] != (3, 12) or torch.__version__.split("+")[0] != "2.10.0":
|
||||
raise RuntimeError("Validated dependencies: Python3.12 / Torch2.10.0")
|
||||
self.binding = b = json.loads((root / "binding.json").read_text())
|
||||
if b["task_sha256"] != task_sha256 or b["support_sha256"] != support_sha256:
|
||||
raise ValueError("Unsupported physical binding")
|
||||
if file_hash(root / "task.json") != task_sha256:
|
||||
raise ValueError("Task file/binding mismatch")
|
||||
self._actor = Actor(m["hidden"]).to(device)
|
||||
self.device = next(self._actor.parameters()).device
|
||||
self._actor.load_state_dict(
|
||||
torch.load(root / "actor.pt", map_location=self.device, weights_only=True), strict=True
|
||||
)
|
||||
self._actor.eval().requires_grad_(False)
|
||||
if (
|
||||
any(not torch.isfinite(x).all() for x in self._actor.state_dict().values())
|
||||
or (self._actor.scale <= 0).any()
|
||||
):
|
||||
raise ValueError("Invalid actor/normalization")
|
||||
self.version = m["version"]
|
||||
|
||||
@torch.inference_mode()
|
||||
def act(self, observation):
|
||||
if set(observation) != set(SHAPES):
|
||||
raise ValueError("Require all and only standing observation fields")
|
||||
goal = observation["goal"]
|
||||
if not isinstance(goal, torch.Tensor) or goal.ndim != 2 or len(goal) < 1:
|
||||
raise ValueError("Require nonempty batch")
|
||||
for key, shape in SHAPES.items():
|
||||
x = observation[key]
|
||||
if (
|
||||
not isinstance(x, torch.Tensor)
|
||||
or x.shape != (len(goal), *shape)
|
||||
or x.dtype != torch.float32
|
||||
or x.device != self.device
|
||||
or not torch.isfinite(x).all()
|
||||
):
|
||||
raise ValueError(f"Invalid standing input: {key}")
|
||||
if (goal - self.binding["height_m"]).abs().max() > 1e-5:
|
||||
raise ValueError("Unsupported height goal")
|
||||
if observation["guide_wrench"][:, 2].abs().max() != 0:
|
||||
raise ValueError("Vertical guide not permitted")
|
||||
quat = observation["base_state"][:, 3:7]
|
||||
if (quat.norm(dim=-1) - 1).abs().max() > 0.002:
|
||||
raise ValueError("Require unit xyzw quaternion")
|
||||
x = torch.cat([observation[k].reshape(len(goal), -1) for k in SHAPES], -1)
|
||||
x[:, 11] -= goal[:, 0]
|
||||
action = self._actor(x)
|
||||
if not torch.isfinite(action).all():
|
||||
raise RuntimeError("Non-finite actor output")
|
||||
return action
|
||||
|
||||
@torch.inference_mode()
|
||||
def position_targets(self, observation):
|
||||
action = self.act(observation)
|
||||
soft = action.new_tensor(self.binding["soft_limits"])
|
||||
return (action.new_tensor(self.binding["nominal"]) + self.binding["action_scale_rad"] * action).clamp(
|
||||
min=soft[:, 0], max=soft[:, 1]
|
||||
)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Fixed-dataset IQL for the explicitly bound Go2 reach profile (no simulator imports)."""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from .frozen_policy import Actor
|
||||
|
||||
|
||||
def sha256(path):
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def canonical_hash(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False).encode()).hexdigest()
|
||||
|
||||
|
||||
def atomic_save(value, path):
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(path.suffix + ".tmp")
|
||||
torch.save(value, temporary)
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def features(tokens):
|
||||
"""A named projection of leg FEATURE_SCHEMA v1, NOT a generic morphology policy."""
|
||||
return torch.cat(
|
||||
(tokens["joint_observation"][:, :3].flatten(1), tokens["effector_observation"][:, 0, :3], tokens["goal"]),
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
|
||||
def network(inputs, outputs, hidden):
|
||||
return nn.Sequential(
|
||||
nn.Linear(inputs, hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, outputs)
|
||||
)
|
||||
|
||||
|
||||
class IQL:
|
||||
def __init__(self, config, mean, std, device="cpu"):
|
||||
self.config = config
|
||||
self.actor = Actor(config["hidden"]).to(device)
|
||||
self.actor.mean.copy_(mean)
|
||||
self.actor.std.copy_(std)
|
||||
self.q1, self.q2 = (network(18, 1, config["hidden"]).to(device) for _ in range(2))
|
||||
self.v = network(15, 1, config["hidden"]).to(device)
|
||||
self.t1, self.t2 = copy.deepcopy(self.q1), copy.deepcopy(self.q2)
|
||||
self.t1.requires_grad_(False)
|
||||
self.t2.requires_grad_(False)
|
||||
self.optimizers = [
|
||||
torch.optim.Adam(m.parameters(), lr=config["lr"]) for m in (self.actor, self.q1, self.q2, self.v)
|
||||
]
|
||||
|
||||
def update(self, batch):
|
||||
cfg = self.config
|
||||
s = (batch["state"] - self.actor.mean) / self.actor.std
|
||||
ns = (batch["next_state"] - self.actor.mean) / self.actor.std
|
||||
sa = torch.cat((s, batch["action"]), -1)
|
||||
with torch.no_grad():
|
||||
target_q = torch.minimum(self.t1(sa), self.t2(sa)).squeeze(-1)
|
||||
value = self.v(s).squeeze(-1)
|
||||
delta = target_q - value
|
||||
v_loss = (torch.where(delta > 0, cfg["expectile"], 1 - cfg["expectile"]) * delta.square()).mean()
|
||||
with torch.no_grad():
|
||||
target = batch["reward"] + cfg["discount"] * (~batch["terminated"]) * self.v(ns).squeeze(-1)
|
||||
weight = ((target_q - value) * cfg["temperature"]).exp().clamp(max=cfg["max_weight"])
|
||||
q1_loss = (self.q1(sa).squeeze(-1) - target).square().mean()
|
||||
q2_loss = (self.q2(sa).squeeze(-1) - target).square().mean()
|
||||
actor_loss = (weight * (self.actor(batch["state"]) - batch["action"]).square().mean(-1)).mean()
|
||||
losses = (actor_loss, q1_loss, q2_loss, v_loss)
|
||||
for optimizer, loss in zip(self.optimizers, losses):
|
||||
if not torch.isfinite(loss):
|
||||
raise RuntimeError("Non-finite IQL loss")
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
loss.backward()
|
||||
params = [p for group in optimizer.param_groups for p in group["params"]]
|
||||
nn.utils.clip_grad_norm_(params, 10.0, error_if_nonfinite=True)
|
||||
optimizer.step()
|
||||
with torch.no_grad():
|
||||
for target_net, source in ((self.t1, self.q1), (self.t2, self.q2)):
|
||||
for target_param, param in zip(target_net.parameters(), source.parameters()):
|
||||
target_param.lerp_(param, cfg["target_tau"])
|
||||
return dict(zip(("actor", "q1", "q2", "value"), [v.item() for v in losses]))
|
||||
|
||||
def state_dict(self):
|
||||
return {
|
||||
"models": {name: getattr(self, name).state_dict() for name in ("actor", "q1", "q2", "v", "t1", "t2")},
|
||||
"optimizers": [v.state_dict() for v in self.optimizers],
|
||||
"rng": torch.get_rng_state(),
|
||||
"cuda_rng": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else [],
|
||||
}
|
||||
|
||||
def load_state_dict(self, checkpoint):
|
||||
for name, value in checkpoint["models"].items():
|
||||
getattr(self, name).load_state_dict(value)
|
||||
for optimizer, value in zip(self.optimizers, checkpoint["optimizers"]):
|
||||
optimizer.load_state_dict(value)
|
||||
torch.set_rng_state(checkpoint["rng"].cpu())
|
||||
if checkpoint["cuda_rng"]:
|
||||
torch.cuda.set_rng_state_all([v.cpu() for v in checkpoint["cuda_rng"]])
|
||||
@@ -0,0 +1,340 @@
|
||||
"""Dedicated loaded-standing PPO; pure Torch, no Isaac imports or Reach weights."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.distributions import Normal
|
||||
|
||||
from .policy import compute_gae
|
||||
|
||||
CONTRACT = "go2-fl-loaded-stand-v0"
|
||||
FEATURE_VERSION = "loaded-stand-45-fixed-si-v1"
|
||||
SHAPES = {
|
||||
"joint_state": (3, 3),
|
||||
"base_state": (13,),
|
||||
"mount_wrench": (6,),
|
||||
"foot_state": (10,),
|
||||
"guide_wrench": (6,),
|
||||
"goal": (1,),
|
||||
}
|
||||
|
||||
|
||||
def load_training_config(path):
|
||||
cfg = json.loads(Path(path).read_text())
|
||||
keys = {
|
||||
"format",
|
||||
"task_config",
|
||||
"seed",
|
||||
"validation_seed",
|
||||
"holdout_seed",
|
||||
"num_envs",
|
||||
"horizon",
|
||||
"updates",
|
||||
"hidden",
|
||||
"initial_std",
|
||||
"learning_rate",
|
||||
"gamma",
|
||||
"gae_lambda",
|
||||
"clip_ratio",
|
||||
"epochs",
|
||||
"minibatch_size",
|
||||
"value_coefficient",
|
||||
"max_gradient_norm",
|
||||
"target_kl",
|
||||
"failure_penalty",
|
||||
"checkpoint_interval",
|
||||
"validation_interval",
|
||||
"train_amplitude_scale",
|
||||
"train_time_shift_s",
|
||||
"validation_amplitude_scale",
|
||||
"validation_time_shift_s",
|
||||
"max_wall_seconds",
|
||||
"max_disk_bytes",
|
||||
}
|
||||
if set(cfg) != keys or cfg["format"] != "skillfactory.loaded-stand-ppo.v1":
|
||||
raise ValueError("Invalid standing training config")
|
||||
integer = (
|
||||
"seed",
|
||||
"validation_seed",
|
||||
"holdout_seed",
|
||||
"num_envs",
|
||||
"horizon",
|
||||
"updates",
|
||||
"hidden",
|
||||
"epochs",
|
||||
"minibatch_size",
|
||||
"checkpoint_interval",
|
||||
"validation_interval",
|
||||
"max_disk_bytes",
|
||||
)
|
||||
for key, value in cfg.items():
|
||||
if key in ("format", "task_config"):
|
||||
continue
|
||||
if isinstance(value, list):
|
||||
if (
|
||||
len(value) != 2
|
||||
or any(type(v) not in (int, float) or not math.isfinite(v) for v in value)
|
||||
or value[0] > value[1]
|
||||
):
|
||||
raise ValueError(f"Invalid interval: {key}")
|
||||
if "amplitude" in key and not 0 < value[0] <= value[1] <= 1:
|
||||
raise ValueError("Initial training stays within validated disturbance amplitudes")
|
||||
if "time_shift" in key and max(abs(v) for v in value) > 0.5:
|
||||
raise ValueError("Pulse shift outside initial training scope")
|
||||
elif (
|
||||
type(value) not in (int, float)
|
||||
or not math.isfinite(value)
|
||||
or value <= 0
|
||||
or (key in integer and type(value) is not int)
|
||||
):
|
||||
raise ValueError(f"Invalid positive training value: {key}")
|
||||
if not 0 < cfg["gamma"] <= 1 or not 0 < cfg["gae_lambda"] <= 1 or not 0 < cfg["clip_ratio"] < 1:
|
||||
raise ValueError("Invalid PPO discounts/clip")
|
||||
if not 0.02 <= cfg["initial_std"] <= 0.5 or len({cfg[k] for k in ("seed", "validation_seed", "holdout_seed")}) != 3:
|
||||
raise ValueError("Invalid std or non-independent seeds")
|
||||
if cfg["num_envs"] < 13 or cfg["num_envs"] * cfg["horizon"] % cfg["minibatch_size"]:
|
||||
raise ValueError("Need >=13 environments and exact minibatches")
|
||||
return cfg
|
||||
|
||||
|
||||
def canonical_hash(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
||||
|
||||
|
||||
def features(observation):
|
||||
if set(observation) != set(SHAPES):
|
||||
raise ValueError("Wrong standing observation fields")
|
||||
first = observation["goal"]
|
||||
if not isinstance(first, torch.Tensor) or first.ndim != 2 or first.shape[0] < 1:
|
||||
raise ValueError("Invalid standing observation batch")
|
||||
for key, shape in SHAPES.items():
|
||||
x = observation[key]
|
||||
if (
|
||||
not isinstance(x, torch.Tensor)
|
||||
or x.shape != (len(first), *shape)
|
||||
or x.dtype != torch.float32
|
||||
or x.device != first.device
|
||||
or not torch.isfinite(x).all()
|
||||
):
|
||||
raise ValueError(f"Invalid standing observation: {key}")
|
||||
x = torch.cat([observation[k].reshape(len(first), -1) for k in SHAPES], -1)
|
||||
x[:, 11] -= first[:, 0] # base z error, not a world-origin-dependent absolute height
|
||||
return x
|
||||
|
||||
|
||||
class StandingActorCritic(nn.Module):
|
||||
def __init__(self, hidden=128, initial_std=0.15):
|
||||
super().__init__()
|
||||
self.model_config = {"hidden": hidden, "initial_std": initial_std}
|
||||
offset = torch.zeros(45)
|
||||
offset[[0, 3, 6]] = torch.tensor([0.0, 0.8, -1.5])
|
||||
scale = torch.ones(45)
|
||||
scale[[0, 3, 6]] = 0.5
|
||||
scale[9:12] = 0.1
|
||||
scale[22:28] = torch.tensor([50.0, 50.0, 50.0, 10.0, 10.0, 10.0])
|
||||
scale[28:31], scale[34:37], scale[37] = 0.4, 50.0, 0.05
|
||||
scale[38:44] = torch.tensor([50.0, 50.0, 50.0, 10.0, 10.0, 10.0])
|
||||
scale[44] = 0.4
|
||||
self.register_buffer("offset", offset)
|
||||
self.register_buffer("scale", scale)
|
||||
self.actor = nn.Sequential(
|
||||
nn.Linear(45, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(), nn.Linear(hidden, 3)
|
||||
)
|
||||
self.critic = nn.Sequential(
|
||||
nn.Linear(45, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(), nn.Linear(hidden, 1)
|
||||
)
|
||||
for module in self.modules():
|
||||
if isinstance(module, nn.Linear):
|
||||
nn.init.orthogonal_(module.weight, math.sqrt(2))
|
||||
nn.init.zeros_(module.bias)
|
||||
nn.init.orthogonal_(self.actor[-1].weight, 0.01)
|
||||
nn.init.orthogonal_(self.critic[-1].weight, 1.0)
|
||||
self.log_std = nn.Parameter(torch.full((3,), math.log(initial_std)))
|
||||
self.float()
|
||||
|
||||
def distribution_value(self, x):
|
||||
x = ((x - self.offset) / self.scale).clamp(-10, 10)
|
||||
return Normal(
|
||||
self.actor(x), self.log_std.clamp(math.log(0.02), math.log(0.5)).exp(), validate_args=False
|
||||
), self.critic(x).squeeze(-1)
|
||||
|
||||
def act(self, x, deterministic=False):
|
||||
dist, value = self.distribution_value(x)
|
||||
latent = dist.mean if deterministic else dist.sample()
|
||||
# For PPO ratios evaluated at fixed latent, tanh's Jacobian cancels exactly.
|
||||
return latent.tanh(), latent, dist.log_prob(latent).sum(-1), value
|
||||
|
||||
def evaluate(self, x, latent):
|
||||
dist, value = self.distribution_value(x)
|
||||
return dist.log_prob(latent).sum(-1), value
|
||||
|
||||
def value(self, x):
|
||||
return self.distribution_value(x)[1]
|
||||
|
||||
|
||||
def selection_height_error(error, failed):
|
||||
"""A failed first episode has fixed 0.10m cost; later autoresets cannot affect selection."""
|
||||
return torch.where(failed, torch.full_like(error, 0.10), error)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def bootstrap_values(model, next_features, terminated, truncated, info):
|
||||
value = model.value(next_features)
|
||||
needs_terminal = truncated & ~terminated
|
||||
if needs_terminal.any():
|
||||
ids = info["terminal_ids"]
|
||||
if (
|
||||
ids is None
|
||||
or info["terminal_observation"] is None
|
||||
or not torch.isin(needs_terminal.nonzero().flatten(), ids).all()
|
||||
):
|
||||
raise RuntimeError("Missing pre-reset timeout observations")
|
||||
mask = needs_terminal[ids.long()]
|
||||
terminal = {k: v[mask] for k, v in info["terminal_observation"].items()}
|
||||
value[ids.long()[mask]] = model.value(features(terminal))
|
||||
value[terminated] = 0
|
||||
return value
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def collect_rollout(env, model, x, cfg):
|
||||
data = {
|
||||
k: torch.empty(cfg["horizon"], env.num_envs, *shape, device=env.device, dtype=dtype)
|
||||
for k, shape, dtype in (
|
||||
("features", (45,), torch.float32),
|
||||
("latent", (3,), torch.float32),
|
||||
("log_prob", (), torch.float32),
|
||||
("value", (), torch.float32),
|
||||
("reward", (), torch.float32),
|
||||
("next_value", (), torch.float32),
|
||||
("done", (), torch.bool),
|
||||
)
|
||||
}
|
||||
failures, timeouts = 0, 0
|
||||
for step in range(cfg["horizon"]):
|
||||
action, latent, logp, value = model.act(x)
|
||||
obs, reward, terminated, truncated, info = env.step(action)
|
||||
nx = features(obs["policy"])
|
||||
nv = bootstrap_values(model, nx, terminated, truncated, info)
|
||||
for key, item in (
|
||||
("features", x),
|
||||
("latent", latent),
|
||||
("log_prob", logp),
|
||||
("value", value),
|
||||
("reward", reward / env.step_dt - cfg["failure_penalty"] * terminated.float()),
|
||||
("next_value", nv),
|
||||
("done", terminated | truncated),
|
||||
):
|
||||
data[key][step].copy_(item)
|
||||
failures += int(terminated.sum())
|
||||
timeouts += int(truncated.sum())
|
||||
x = nx
|
||||
return data, x, failures, timeouts
|
||||
|
||||
|
||||
def ppo_step(model, optimizer, data, cfg):
|
||||
advantages, returns = compute_gae(
|
||||
data["reward"], data["value"], data["next_value"], data["done"], cfg["gamma"], cfg["gae_lambda"]
|
||||
)
|
||||
x, latent, old_log = [data[k].flatten(0, 1).detach() for k in ("features", "latent", "log_prob")]
|
||||
with torch.no_grad():
|
||||
mismatch = (model.evaluate(x, latent)[0] - old_log).abs().max().item()
|
||||
if not math.isfinite(mismatch) or mismatch > 2e-4:
|
||||
raise RuntimeError(f"Sampling/learner probability mismatch: {mismatch}")
|
||||
adv = advantages.flatten()
|
||||
adv = (adv - adv.mean()) / (adv.std(unbiased=False) + 1e-8)
|
||||
target = returns.flatten()
|
||||
rows, stopped = [], False
|
||||
for _ in range(cfg["epochs"]):
|
||||
order = torch.randperm(len(x), device=x.device)
|
||||
for ids in order.split(cfg["minibatch_size"]):
|
||||
logp, value = model.evaluate(x[ids], latent[ids])
|
||||
log_ratio = logp - old_log[ids]
|
||||
ratio = log_ratio.exp()
|
||||
kl = ((ratio - 1) - log_ratio).mean()
|
||||
if not torch.isfinite(kl):
|
||||
raise RuntimeError("Non-finite PPO KL")
|
||||
if kl.item() > cfg["target_kl"]:
|
||||
stopped = True
|
||||
break
|
||||
actor = -torch.minimum(
|
||||
ratio * adv[ids], ratio.clamp(1 - cfg["clip_ratio"], 1 + cfg["clip_ratio"]) * adv[ids]
|
||||
).mean()
|
||||
critic = (value - target[ids]).square().mean()
|
||||
loss = actor + cfg["value_coefficient"] * critic
|
||||
if not torch.isfinite(loss):
|
||||
raise RuntimeError("Non-finite PPO objective")
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
loss.backward()
|
||||
norm = nn.utils.clip_grad_norm_(model.parameters(), cfg["max_gradient_norm"], error_if_nonfinite=True)
|
||||
optimizer.step()
|
||||
rows.append(torch.stack((actor.detach(), critic.detach(), kl.detach(), norm.detach())))
|
||||
if stopped:
|
||||
break
|
||||
if not rows or any(not torch.isfinite(p).all() for p in model.parameters()):
|
||||
raise RuntimeError("No finite PPO update")
|
||||
metrics = dict(zip(("actor_loss", "value_loss", "kl", "gradient_norm"), torch.stack(rows).mean(0).cpu().tolist()))
|
||||
return {**metrics, "minibatches": len(rows), "kl_early_stop": stopped, "sampling_log_prob_error": mismatch}
|
||||
|
||||
|
||||
def rng_state():
|
||||
return {"cpu": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []}
|
||||
|
||||
|
||||
def restore_rng(state):
|
||||
torch.set_rng_state(state["cpu"].cpu())
|
||||
if state["cuda"]:
|
||||
torch.cuda.set_rng_state_all([x.cpu() for x in state["cuda"]])
|
||||
|
||||
|
||||
def save_checkpoint(path, model, optimizer, identity, update, elapsed_s, best):
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = {
|
||||
"format": "skillfactory.standing-ppo-checkpoint.v1",
|
||||
"contract": CONTRACT,
|
||||
"features": FEATURE_VERSION,
|
||||
"model_config": model.model_config,
|
||||
"model": model.state_dict(),
|
||||
"optimizer": optimizer.state_dict(),
|
||||
"identity": identity,
|
||||
"update": update,
|
||||
"elapsed_s": elapsed_s,
|
||||
"best": best,
|
||||
"rng": rng_state(),
|
||||
"resume_semantics": "learner-state restored; physics episodes reset, not bitwise simulation resume",
|
||||
"accepted_skill": False,
|
||||
}
|
||||
tmp = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
||||
tmp = Path(stream.name)
|
||||
torch.save(data, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
if tmp is not None:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def restore_checkpoint(path, model, optimizer, identity):
|
||||
data = torch.load(path, map_location=next(model.parameters()).device, weights_only=True)
|
||||
if (
|
||||
data["format"] != "skillfactory.standing-ppo-checkpoint.v1"
|
||||
or data["contract"] != CONTRACT
|
||||
or data["features"] != FEATURE_VERSION
|
||||
or data["identity"] != identity
|
||||
or data["model_config"] != model.model_config
|
||||
):
|
||||
raise ValueError("Standing checkpoint/config/source identity mismatch")
|
||||
model.load_state_dict(data["model"])
|
||||
optimizer.load_state_dict(data["optimizer"])
|
||||
restore_rng(data["rng"])
|
||||
return data
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Loaded-standing contract/math. No simulator import; deliberately not leg-token-v1."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
CONTRACT = "go2-fl-loaded-stand-v0"
|
||||
PAYLOAD = "virtual_payload"
|
||||
MOUNT_JOINT = "mount_ft_joint"
|
||||
|
||||
|
||||
def sha256(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def load_config(path):
|
||||
cfg = json.loads(Path(path).read_text())
|
||||
expected = {
|
||||
"schema_version",
|
||||
"task",
|
||||
"source_bundle",
|
||||
"support_asset",
|
||||
"payload_mass_kg",
|
||||
"payload_size_m",
|
||||
"payload_com_m",
|
||||
"sensor_carrier_mass_kg",
|
||||
"guide_stiffness",
|
||||
"guide_damping",
|
||||
"guide_wrench_limit",
|
||||
"disturbance_amplitude",
|
||||
"action_scale_rad",
|
||||
"initial_foot_clearance_m",
|
||||
"episode_seconds",
|
||||
"warmup_seconds",
|
||||
"height_error_limit_m",
|
||||
"tilt_limit_rad",
|
||||
"foot_drift_limit_m",
|
||||
"contact_fraction_min",
|
||||
"vertical_balance_relative_tolerance",
|
||||
"sensor_static_force_tolerance_N",
|
||||
"sensor_static_torque_tolerance_Nm",
|
||||
"normalized_effort_velocity_limit",
|
||||
"joint_limit_excess_rad",
|
||||
"seed",
|
||||
}
|
||||
if (
|
||||
set(cfg) != expected
|
||||
or type(cfg["schema_version"]) is not int
|
||||
or cfg["schema_version"] != 1
|
||||
or cfg["task"] != "go2_fl_loaded_stand_v0"
|
||||
):
|
||||
raise ValueError("Unsupported loaded-standing config")
|
||||
for key, value in cfg.items():
|
||||
if isinstance(value, list):
|
||||
length = 3 if key in ("payload_size_m", "payload_com_m") else 6
|
||||
if len(value) != length or any(type(v) not in (int, float) or not math.isfinite(v) for v in value):
|
||||
raise ValueError(f"Invalid finite vector: {key}")
|
||||
if key != "payload_com_m" and any(v < 0 for v in value):
|
||||
raise ValueError(f"Negative coefficient: {key}")
|
||||
elif key not in ("task", "source_bundle", "support_asset"):
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
|
||||
raise ValueError(f"Invalid positive scalar: {key}")
|
||||
if any(cfg[k][2] != 0 for k in ("guide_stiffness", "guide_damping", "guide_wrench_limit")):
|
||||
raise ValueError("Standing guide must provide no vertical support")
|
||||
if min(cfg["disturbance_amplitude"]) <= 0:
|
||||
raise ValueError("All six disturbance axes require positive amplitudes")
|
||||
if min(cfg["payload_size_m"]) <= 0 or not 0 < cfg["contact_fraction_min"] <= 1:
|
||||
raise ValueError("Invalid dimensions/contact fraction")
|
||||
if cfg["episode_seconds"] < 14 or cfg["warmup_seconds"] >= 3 or type(cfg["seed"]) is not int:
|
||||
raise ValueError("Protocol needs duration>=14s, warmup<3s and integer seed")
|
||||
return cfg
|
||||
|
||||
|
||||
def payload_urdf(source, cfg):
|
||||
"""Derive a new floating tree; never mutate the original fixed-leg URDF."""
|
||||
root = ET.fromstring(Path(source).read_bytes())
|
||||
if root.find(f"link[@name='{PAYLOAD}']") is not None:
|
||||
raise ValueError("Already contains payload")
|
||||
root.set("name", "go2_fl_loaded_stand")
|
||||
anchor = root.find("link[@name='anchor_base']/inertial")
|
||||
if anchor is None:
|
||||
raise ValueError("Missing sensor carrier")
|
||||
anchor.find("mass").set("value", str(cfg["sensor_carrier_mass_kg"]))
|
||||
anchor.find("inertia").attrib.update(ixx="0.00001", iyy="0.00001", izz="0.00001")
|
||||
payload = ET.Element("link", name=PAYLOAD)
|
||||
mass, (x, y, z) = cfg["payload_mass_kg"], cfg["payload_size_m"]
|
||||
xyz = " ".join(map(str, cfg["payload_com_m"]))
|
||||
inertial = ET.SubElement(payload, "inertial")
|
||||
ET.SubElement(inertial, "origin", xyz=xyz, rpy="0 0 0")
|
||||
ET.SubElement(inertial, "mass", value=str(mass))
|
||||
ET.SubElement(
|
||||
inertial,
|
||||
"inertia",
|
||||
ixx=str(mass * (y * y + z * z) / 12),
|
||||
iyy=str(mass * (x * x + z * z) / 12),
|
||||
izz=str(mass * (x * x + y * y) / 12),
|
||||
ixy="0",
|
||||
ixz="0",
|
||||
iyz="0",
|
||||
)
|
||||
for tag in ("visual", "collision"):
|
||||
item = ET.SubElement(payload, tag)
|
||||
ET.SubElement(item, "origin", xyz=xyz, rpy="0 0 0")
|
||||
ET.SubElement(ET.SubElement(item, "geometry"), "box", size=" ".join(map(str, (x, y, z))))
|
||||
if tag == "visual":
|
||||
ET.SubElement(ET.SubElement(item, "material", name="payload_blue"), "color", rgba="0.1 0.35 0.8 1")
|
||||
root.insert(0, payload)
|
||||
joint = ET.SubElement(root, "joint", name=MOUNT_JOINT, type="fixed", dont_collapse="true")
|
||||
ET.SubElement(joint, "parent", link=PAYLOAD)
|
||||
ET.SubElement(joint, "child", link="anchor_base")
|
||||
ET.SubElement(joint, "origin", xyz="0 0 0", rpy="0 0 0")
|
||||
ET.indent(root)
|
||||
return ET.tostring(root, encoding="utf-8", xml_declaration=True)
|
||||
|
||||
|
||||
def load_support_asset(directory, cfg):
|
||||
root = Path(directory).resolve()
|
||||
manifest = json.loads((root / "support.json").read_text())
|
||||
if (
|
||||
manifest["contract"] != CONTRACT
|
||||
or manifest["fixed_to_world"] is not False
|
||||
or manifest["source_manifest_sha256"] != sha256(Path(cfg["source_bundle"]) / "manifest.json")
|
||||
):
|
||||
raise ValueError("Support/source identity mismatch")
|
||||
for name in ("payload_mass_kg", "payload_size_m", "payload_com_m", "sensor_carrier_mass_kg"):
|
||||
if manifest[name] != cfg[name]:
|
||||
raise ValueError(f"Support asset config mismatch: {name}")
|
||||
for relative, digest in manifest["files"].items():
|
||||
path = (root / relative).resolve()
|
||||
if not path.is_relative_to(root) or not path.is_file() or sha256(path) != digest:
|
||||
raise ValueError(f"Support asset integrity failure: {relative}")
|
||||
if manifest["usd_path"] not in manifest["files"] or manifest["mount_joint"] != MOUNT_JOINT:
|
||||
raise ValueError("Missing support USD/mount identity")
|
||||
return manifest
|
||||
|
||||
|
||||
def passive_wrench(displacement, velocity, stiffness, damping, limit):
|
||||
"""World-frame passive component (F, T), no gravity compensation or z support."""
|
||||
return (-stiffness * displacement - damping * velocity).clamp(min=-limit, max=limit)
|
||||
|
||||
|
||||
def disturbance_wrench(time, scenario_ids, amplitudes):
|
||||
"""13 deterministic cases: no load, ±six axes; trapezoids at [3,6] and [8,11]s."""
|
||||
import torch
|
||||
|
||||
envelope = torch.zeros_like(time)
|
||||
for start in (3.0, 8.0):
|
||||
envelope += torch.minimum((time - start) / 0.5, (start + 3.0 - time) / 0.5).clamp(0, 1)
|
||||
result = time.new_zeros(len(time), 6)
|
||||
axis = ((scenario_ids - 1).clamp(min=0) // 2).long()
|
||||
sign = torch.where(scenario_ids % 2 == 1, 1.0, -1.0)
|
||||
result[torch.arange(len(time), device=time.device), axis] = amplitudes[axis] * sign * envelope * (scenario_ids != 0)
|
||||
return result
|
||||
|
||||
|
||||
def relative_point_velocity(v_point, v_root, omega_root, displacement):
|
||||
"""World components of velocity relative to a rotating root (before rotation)."""
|
||||
import torch
|
||||
|
||||
return v_point - v_root - torch.cross(omega_root, displacement, dim=-1)
|
||||
|
||||
|
||||
def negative_control_collapsed(rows, drop_threshold_m=0.10):
|
||||
"""All tested environments must actually drop downward with zero actuation."""
|
||||
return bool(rows) and all(
|
||||
row["max_base_drop_m"] >= drop_threshold_m and row["max_normalized_torque"] == 0 for row in rows
|
||||
)
|
||||
|
||||
|
||||
def shift_wrench(force, torque, old_origin_minus_new_origin):
|
||||
import torch
|
||||
|
||||
return force, torque + torch.cross(old_origin_minus_new_origin, force, dim=-1)
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Floating payload, ground support and measured mounting wrench; not Reach v1."""
|
||||
import gymnasium as gym
|
||||
|
||||
gym.register(
|
||||
id="SkillFactory-LoadedLegStand-v0",
|
||||
entry_point=f"{__name__}.env:LoadedLegEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={"env_cfg_entry_point": f"{__name__}.cfg:LoadedLegEnvCfg"},
|
||||
)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Experimental load-bearing stand task; reuses leg mechanics, not Reach observations/rewards."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from isaaclab.envs import mdp as base_mdp
|
||||
from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, RewardTermCfg, TerminationTermCfg
|
||||
from isaaclab.sensors import JointWrenchSensorCfg
|
||||
from isaaclab.utils.configclass import configclass
|
||||
|
||||
from SkillFactory.legs.support import load_config, load_support_asset
|
||||
from SkillFactory.legs.urdf import forward, multiply, pose
|
||||
from SkillFactory.tasks.manager_based.leg_skill.leg_env_cfg import LegEnvCfg, LegSceneCfg
|
||||
from SkillFactory.tasks.manager_based.single_leg_anchor.mdp.actions import BoundedJointPositionActionCfg
|
||||
|
||||
from . import mdp
|
||||
|
||||
|
||||
@configclass
|
||||
class LoadedSceneCfg(LegSceneCfg):
|
||||
mount_wrench = JointWrenchSensorCfg(
|
||||
prim_path="{ENV_REGEX_NS}/Robot", update_period=0.0, convention="incoming_joint_frame"
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class NoCommandsCfg:
|
||||
pass
|
||||
|
||||
|
||||
@configclass
|
||||
class ObservationsCfg:
|
||||
@configclass
|
||||
class PolicyCfg(ObservationGroupCfg):
|
||||
joint_state = ObservationTermCfg(func=mdp.observation, params={"name": "joint_state"})
|
||||
base_state = ObservationTermCfg(func=mdp.observation, params={"name": "base_state"})
|
||||
mount_wrench = ObservationTermCfg(func=mdp.observation, params={"name": "mount_wrench"})
|
||||
foot_state = ObservationTermCfg(func=mdp.observation, params={"name": "foot_state"})
|
||||
guide_wrench = ObservationTermCfg(func=mdp.observation, params={"name": "guide_wrench"})
|
||||
goal = ObservationTermCfg(func=mdp.observation, params={"name": "goal"})
|
||||
|
||||
def __post_init__(self):
|
||||
self.enable_corruption = False
|
||||
self.concatenate_terms = False
|
||||
|
||||
policy = PolicyCfg()
|
||||
|
||||
|
||||
@configclass
|
||||
class RewardsCfg:
|
||||
standing = RewardTermCfg(func=mdp.standing_reward, weight=1.0)
|
||||
effort = RewardTermCfg(func=mdp.effort_cost, weight=-0.01)
|
||||
action_rate = RewardTermCfg(func=mdp.action_rate_cost, weight=-0.005)
|
||||
|
||||
|
||||
@configclass
|
||||
class TerminationsCfg:
|
||||
time_out = TerminationTermCfg(func=base_mdp.time_out, time_out=True)
|
||||
invalid = TerminationTermCfg(func=mdp.invalid_state)
|
||||
fallen = TerminationTermCfg(func=mdp.fallen)
|
||||
|
||||
|
||||
@configclass
|
||||
class LoadedLegEnvCfg(LegEnvCfg):
|
||||
support_config: str = "configs/standing/go2_fl_support_v0.json"
|
||||
support_parameters: dict | None = None
|
||||
support_manifest: dict | None = None
|
||||
guide_enabled: bool = True
|
||||
scenario_offset: int = 0
|
||||
load_randomization: dict | None = None # Training-only, disabled for original physical protocol.
|
||||
scene = LoadedSceneCfg(
|
||||
num_envs=13, env_spacing=2.0, replicate_physics=True, filter_collisions=True, lazy_sensor_update=False
|
||||
)
|
||||
commands = NoCommandsCfg()
|
||||
observations = ObservationsCfg()
|
||||
rewards = RewardsCfg()
|
||||
terminations = TerminationsCfg()
|
||||
|
||||
def __post_init__(self):
|
||||
self.support_parameters = cfg = load_config(self.support_config)
|
||||
self.bundle_dir = cfg["source_bundle"]
|
||||
super().__post_init__()
|
||||
if self.leg_bundle["spec"]["part_id"] != "go2_fl" or self.leg_bundle["foot"]["type"] != "sphere":
|
||||
raise ValueError("Loaded stand v0 is only validated for Go2 FL spherical foot")
|
||||
self.support_manifest = support = load_support_asset(cfg["support_asset"], cfg)
|
||||
self.scene.robot.spawn.usd_path = str(Path(cfg["support_asset"]).resolve() / support["usd_path"])
|
||||
self.scene.foot_contact.prim_path = (
|
||||
"{ENV_REGEX_NS}/Robot" + support["body_paths"][self.leg_bundle["foot"]["body"]]
|
||||
)
|
||||
q = {j["name"]: j["q_default"] for j in self.leg_bundle["spec"]["joints"]}
|
||||
poses, _ = forward(self.leg_bundle["tree"], q)
|
||||
foot = self.leg_bundle["foot"]
|
||||
center = multiply(poses[foot["body"]], pose(foot["xyz"], foot["rpy"]))
|
||||
self.anchor_height = foot["radius"] - center[2][3]
|
||||
self.scene.robot.init_state.pos = (0.0, 0.0, self.anchor_height + cfg["initial_foot_clearance_m"])
|
||||
self.actions.joint_position = BoundedJointPositionActionCfg(
|
||||
class_type=mdp.LoadedPositionAction,
|
||||
asset_name="robot",
|
||||
joint_names=self.leg_bundle["joint_order"],
|
||||
scale=cfg["action_scale_rad"],
|
||||
preserve_order=True,
|
||||
use_default_offset=True,
|
||||
)
|
||||
# Separate task backend: verify mount reactions with PGS, not Reach's TGS settings.
|
||||
self.sim.physics.solver_type = 0
|
||||
self.sim.physics.enable_external_forces_every_iteration = False # TGS-only flag is invalid for PGS.
|
||||
self.episode_length_s = cfg["episode_seconds"]
|
||||
self.seed = cfg["seed"]
|
||||
self.viewer.lookat = (0.0, 0.0, self.anchor_height / 2)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Separate standing observation contract and pre-reset terminal samples."""
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
|
||||
from .mdp import state
|
||||
|
||||
|
||||
class LoadedLegEnv(ManagerBasedRLEnv):
|
||||
def reset(self, seed=None, env_ids=None, options=None):
|
||||
if env_ids is not None:
|
||||
ids = torch.as_tensor(env_ids, device=self.device)
|
||||
if ids.ndim != 1:
|
||||
raise ValueError("env_ids must be one-dimensional")
|
||||
if ids.numel() == 0:
|
||||
if seed is not None:
|
||||
raise ValueError("An empty reset cannot reseed")
|
||||
return self.observation_manager.compute(update_history=False), {}
|
||||
if (
|
||||
ids.dtype not in (torch.int32, torch.int64)
|
||||
or (ids < 0).any()
|
||||
or (ids >= self.num_envs).any()
|
||||
or len(ids.unique()) != len(ids)
|
||||
):
|
||||
raise ValueError("Invalid/duplicate reset indices")
|
||||
env_ids = ids
|
||||
return super().reset(seed=seed, env_ids=env_ids, options=options)
|
||||
|
||||
def step(self, action):
|
||||
if (
|
||||
not isinstance(action, torch.Tensor)
|
||||
or action.shape != (self.num_envs, 3)
|
||||
or action.dtype != torch.float32
|
||||
or action.device != torch.device(self.device)
|
||||
or not torch.isfinite(action).all()
|
||||
):
|
||||
raise ValueError("Require finite float32 [B,3] actions on the simulation device")
|
||||
self.extras["terminal_observation"] = None
|
||||
self.extras["terminal_ids"] = None
|
||||
self._standing_step = True
|
||||
try:
|
||||
return super().step(action)
|
||||
finally:
|
||||
self._standing_step = False
|
||||
|
||||
def _reset_idx(self, env_ids):
|
||||
if getattr(self, "_standing_step", False):
|
||||
self.extras["terminal_ids"] = env_ids.clone()
|
||||
self.extras["terminal_observation"] = {k: v[env_ids].clone() for k, v in state(self).snapshot().items()}
|
||||
super()._reset_idx(env_ids)
|
||||
if hasattr(self, "_loaded_state"):
|
||||
self._loaded_state.last_guide[env_ids] = 0
|
||||
self._loaded_state.last_disturbance[env_ids] = 0
|
||||
self._loaded_state.reset_loads(env_ids)
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Measured six-axis mount reaction, passive guidance and load-bearing stand objective."""
|
||||
|
||||
import math
|
||||
import re
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.utils.math import axis_angle_from_quat, quat_apply, quat_apply_inverse
|
||||
|
||||
from SkillFactory.legs.support import PAYLOAD, disturbance_wrench, passive_wrench, relative_point_velocity
|
||||
from SkillFactory.tasks.manager_based.single_leg_anchor.mdp.actions import BoundedJointPositionAction
|
||||
|
||||
|
||||
class LoadedState:
|
||||
def __init__(self, env):
|
||||
self.env, self.cfg = env, env.cfg.support_parameters
|
||||
self.robot = env.scene["robot"]
|
||||
self.sensor = env.scene["mount_wrench"]
|
||||
self.bundle = env.cfg.leg_bundle
|
||||
self.joints, _ = self.robot.find_joints([re.escape(n) for n in self.bundle["joint_order"]], preserve_order=True)
|
||||
self.payload = self.robot.body_names.index(PAYLOAD)
|
||||
self.anchor = self.robot.body_names.index(self.bundle["anchor_body"])
|
||||
self.foot = self.robot.body_names.index(self.bundle["foot"]["body"])
|
||||
self.sensor_index = self.sensor.body_names.index(self.bundle["anchor_body"])
|
||||
self.payload_ids = torch.tensor([self.payload], device=env.device)
|
||||
self.nominal = torch.tensor([j["q_default"] for j in self.bundle["spec"]["joints"]], device=env.device)
|
||||
self.effort = torch.tensor([j["limits"]["effort"] for j in self.bundle["joints"]], device=env.device)
|
||||
self.offset = torch.tensor(self.bundle["foot"]["xyz"], device=env.device).expand(env.num_envs, -1)
|
||||
self.stiffness, self.damping, self.wrench_limit, self.amplitude = [
|
||||
torch.tensor(self.cfg[k], device=env.device)
|
||||
for k in ("guide_stiffness", "guide_damping", "guide_wrench_limit", "disturbance_amplitude")
|
||||
]
|
||||
self.scenarios = (torch.arange(env.num_envs, device=env.device) + env.cfg.scenario_offset) % 13
|
||||
self.last_guide = torch.zeros(env.num_envs, 6, device=env.device)
|
||||
self.last_disturbance = torch.zeros_like(self.last_guide)
|
||||
self.load_scale = torch.ones(env.num_envs, device=env.device)
|
||||
self.time_shift = torch.zeros(env.num_envs, device=env.device)
|
||||
|
||||
def reset_loads(self, ids):
|
||||
distribution = self.env.cfg.load_randomization
|
||||
if distribution is None:
|
||||
self.scenarios[ids] = ((ids + self.env.cfg.scenario_offset) % 13).long()
|
||||
self.load_scale[ids], self.time_shift[ids] = 1.0, 0.0
|
||||
else:
|
||||
self.scenarios[ids] = torch.randint(0, 13, (len(ids),), device=self.env.device)
|
||||
for target, key in ((self.load_scale, "amplitude_scale"), (self.time_shift, "time_shift_s")):
|
||||
low, high = distribution[key]
|
||||
target[ids] = low + (high - low) * torch.rand(len(ids), device=self.env.device)
|
||||
|
||||
def q(self):
|
||||
return self.robot.data.joint_pos.torch[:, self.joints]
|
||||
|
||||
def root(self):
|
||||
d = self.robot.data
|
||||
return (
|
||||
d.body_link_pos_w.torch[:, self.payload],
|
||||
d.body_link_quat_w.torch[:, self.payload],
|
||||
d.body_link_lin_vel_w.torch[:, self.payload],
|
||||
d.body_link_ang_vel_w.torch[:, self.payload],
|
||||
)
|
||||
|
||||
def foot_center(self):
|
||||
d = self.robot.data
|
||||
return d.body_link_pos_w.torch[:, self.foot] + quat_apply(d.body_link_quat_w.torch[:, self.foot], self.offset)
|
||||
|
||||
def contact(self):
|
||||
# Foot-to-ground normal force, not a full contact wrench or friction sensor.
|
||||
return self.env.scene["foot_contact"].data.force_matrix_w.torch[:, 0].sum(dim=1)
|
||||
|
||||
def mount_wrench(self):
|
||||
d = self.sensor.data
|
||||
return torch.cat((d.force.torch[:, self.sensor_index], d.torque.torch[:, self.sensor_index]), dim=-1)
|
||||
|
||||
def mount_world(self):
|
||||
w = self.mount_wrench()
|
||||
quat = self.robot.data.body_link_quat_w.torch[:, self.anchor]
|
||||
# Built asset has identity child localPos1/localRot1; rotation only at SAME mount origin.
|
||||
return torch.cat((quat_apply(quat, w[:, :3]), quat_apply(quat, w[:, 3:])), -1)
|
||||
|
||||
def guidance(self):
|
||||
pos, quat, vel, omega = self.root()
|
||||
displacement = torch.cat((pos - self.env.scene.env_origins, axis_angle_from_quat(quat)), -1)
|
||||
wrench = passive_wrench(
|
||||
displacement, torch.cat((vel, omega), -1), self.stiffness, self.damping, self.wrench_limit
|
||||
)
|
||||
return wrench if self.env.cfg.guide_enabled else torch.zeros_like(wrench)
|
||||
|
||||
def apply_loads(self):
|
||||
self.last_guide[:] = self.guidance()
|
||||
# Disturbance is held for each control period; passive guidance is recomputed every physics step.
|
||||
time = self.env.episode_length_buf.float() * self.env.step_dt
|
||||
self.last_disturbance[:] = (
|
||||
disturbance_wrench(time - self.time_shift, self.scenarios, self.amplitude) * self.load_scale[:, None]
|
||||
)
|
||||
total = self.last_guide + self.last_disturbance
|
||||
self.robot.permanent_wrench_composer.set_forces_and_torques_index(
|
||||
forces=total[:, None, :3],
|
||||
torques=total[:, None, 3:],
|
||||
positions=self.root()[0][:, None, :],
|
||||
body_ids=self.payload_ids,
|
||||
is_global=True,
|
||||
)
|
||||
|
||||
def tilt(self):
|
||||
quat = self.root()[1]
|
||||
up = torch.zeros(self.env.num_envs, 3, device=self.env.device)
|
||||
up[:, 2] = 1
|
||||
return torch.acos(quat_apply(quat, up)[:, 2].clamp(-1, 1))
|
||||
|
||||
def token(self, name):
|
||||
d = self.robot.data
|
||||
pos, quat, vel, omega = self.root()
|
||||
if name == "joint_state":
|
||||
return torch.stack((self.q(), d.joint_vel.torch[:, self.joints], self.env.action_manager.action), -1)
|
||||
if name == "base_state":
|
||||
return torch.cat((pos - self.env.scene.env_origins, quat, vel, omega), -1)
|
||||
if name == "mount_wrench":
|
||||
return self.mount_wrench()
|
||||
if name == "guide_wrench":
|
||||
return self.last_guide
|
||||
if name == "goal":
|
||||
return torch.full((self.env.num_envs, 1), self.env.cfg.anchor_height, device=self.env.device)
|
||||
if name == "foot_state":
|
||||
center = self.foot_center()
|
||||
point_velocity = d.body_link_lin_vel_w.torch[:, self.foot] + torch.cross(
|
||||
d.body_link_ang_vel_w.torch[:, self.foot],
|
||||
quat_apply(d.body_link_quat_w.torch[:, self.foot], self.offset),
|
||||
dim=-1,
|
||||
)
|
||||
relative = relative_point_velocity(point_velocity, vel, omega, center - pos)
|
||||
return torch.cat(
|
||||
(
|
||||
quat_apply_inverse(quat, center - pos),
|
||||
quat_apply_inverse(quat, relative),
|
||||
self.contact(),
|
||||
(center[:, 2] - self.bundle["foot"]["radius"])[:, None],
|
||||
),
|
||||
-1,
|
||||
)
|
||||
raise KeyError(name)
|
||||
|
||||
def snapshot(self):
|
||||
return {
|
||||
k: self.token(k)
|
||||
for k in ("joint_state", "base_state", "mount_wrench", "foot_state", "guide_wrench", "goal")
|
||||
}
|
||||
|
||||
|
||||
def state(env):
|
||||
if not hasattr(env, "_loaded_state"):
|
||||
env._loaded_state = LoadedState(env)
|
||||
return env._loaded_state
|
||||
|
||||
|
||||
def observation(env, name):
|
||||
return state(env).token(name)
|
||||
|
||||
|
||||
class LoadedPositionAction(BoundedJointPositionAction):
|
||||
def apply_actions(self):
|
||||
state(self._env).apply_loads() # every physics step, before scene.write_data_to_sim
|
||||
super().apply_actions()
|
||||
|
||||
|
||||
def standing_reward(env):
|
||||
s = state(env)
|
||||
height_error = s.root()[0][:, 2] - env.cfg.anchor_height
|
||||
contact = (s.contact()[:, 2] > 1.0).float()
|
||||
return contact * torch.exp(-((height_error / 0.04) ** 2) - (s.tilt() / 0.2) ** 2)
|
||||
|
||||
|
||||
def effort_cost(env):
|
||||
s = state(env)
|
||||
return (s.robot.data.applied_torque.torch[:, s.joints] / s.effort).square().mean(-1)
|
||||
|
||||
|
||||
def action_rate_cost(env):
|
||||
return (env.action_manager.action - env.action_manager.prev_action).square().mean(-1)
|
||||
|
||||
|
||||
def invalid_state(env):
|
||||
s = state(env)
|
||||
return ~(
|
||||
torch.isfinite(s.robot.data.root_state_w.torch).all(-1)
|
||||
& torch.isfinite(s.robot.data.joint_pos.torch).all(-1)
|
||||
& torch.isfinite(s.robot.data.joint_vel.torch).all(-1)
|
||||
& torch.isfinite(s.mount_wrench()).all(-1)
|
||||
)
|
||||
|
||||
|
||||
def fallen(env):
|
||||
s = state(env)
|
||||
return (s.root()[0][:, 2] < env.cfg.anchor_height - 0.10) | (s.tilt() > math.radians(35))
|
||||
Reference in New Issue
Block a user