Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/supermimic/representations.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,12 +487,15 @@ def __init__(self, num_joints: int, default_joint_pos: torch.Tensor):
self.full_state_dim = 13 + 2 * num_joints
self.rep_state_dim = rep_state_dim_from_num_joints(num_joints)
self.prediction_dim = 6 + num_joints # [Δv_b(3), Δw_b(3), Δvj(N)]
self._default_joint_pos = default_joint_pos
self.register_buffer("_default_joint_pos", default_joint_pos, persistent=False)
self.fk: ForwardKinematics # set by bind
self._encoder_bias: tuple[slice, SimContext] | None = None

def bind(self, env: ManagerBasedRlEnv, sim_context: SimContext) -> None:
super().bind(env, sim_context)
self.fk = env.command_manager.get_term("motion").motion.fk
columns = sim_context.find("encoder_bias")
self._encoder_bias = None if columns is None else (columns, sim_context)

def represent(self, full_state: torch.Tensor) -> torch.Tensor:
flat = full_state.reshape(-1, self.full_state_dim)
Expand Down Expand Up @@ -603,10 +606,14 @@ def compute_wm_obs(
joint_state: torch.Tensor,
sim_ctx: torch.Tensor,
) -> torch.Tensor:
del aux_state, sim_ctx
del aux_state
_, g_b, _, w_b, _, _ = decompose_rep_state(rep_state)
qj, vj = joint_state.chunk(2, dim=-1)
return torch.cat([g_b, w_b, qj - self._default_joint_pos, vj], dim=-1)
joint_pos_rel = qj - self._default_joint_pos
if self._encoder_bias is not None:
columns, sim_context = self._encoder_bias
joint_pos_rel = joint_pos_rel + sim_context.denormalize(sim_ctx, columns)
return torch.cat([g_b, w_b, joint_pos_rel, vj], dim=-1)


class MaxCoordRepresentation(StateRepresentation):
Expand Down
75 changes: 75 additions & 0 deletions tests/standalone/test_gencoord_encoder_bias.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import ast
from abc import ABC, abstractmethod
from pathlib import Path
from types import SimpleNamespace as NS

import torch
import torch.nn as nn

from supermimic.sim_context import EncoderBiasSpec, SimContext


def load_production(path, names, namespace):
source = Path(__file__).resolve().parents[2] / "src/supermimic" / path
tree = ast.parse(source.read_text())
nodes = [
n
for n in tree.body
if isinstance(n, (ast.ClassDef, ast.FunctionDef)) and n.name in names
]
future = ast.ImportFrom(
module="__future__", names=[ast.alias(name="annotations")], level=0
)
module = ast.fix_missing_locations(ast.Module(body=[future, *nodes], type_ignores=[]))
exec(compile(module, str(source), "exec"), namespace)
return namespace


def representation():
namespace = {"torch": torch, "nn": nn, "ABC": ABC, "abstractmethod": abstractmethod}
load_production(
"utils/gencoord_helpers.py",
{"rep_state_dim_from_num_joints", "rep_state_offsets", "decompose_rep_state"},
namespace,
)
load_production(
"representations.py", {"StateRepresentation", "GenCoordRepresentation"}, namespace
)
return namespace["GenCoordRepresentation"](2, torch.tensor([1.0, 2.0]))


def test_gencoord_sensor_includes_the_real_encoder_bias_and_keeps_gradients():
rep = representation()
spec = EncoderBiasSpec()
spec.dim = 2
ctx = SimContext([spec], [(-0.1, 0.1), (-0.1, 0.1)])
env = NS(
scene={"robot": NS(data=NS(soft_joint_pos_limits=torch.zeros(1, 2, 2)))},
command_manager=NS(get_term=lambda name: NS(motion=NS(fk=None))),
)
rep.bind(env, ctx)
joints = torch.tensor([[3.0, 5.0, 7.0, 9.0]], requires_grad=True)
obs = rep.compute_wm_obs(
torch.zeros(1, 14), torch.zeros(1, 7), joints, torch.tensor([[0.5, -0.5]])
)
torch.testing.assert_close(obs[:, 6:8], torch.tensor([[2.05, 2.95]]))
torch.testing.assert_close(obs[:, 8:10], joints[:, 2:])
obs.sum().backward()
torch.testing.assert_close(joints.grad, torch.ones_like(joints))


def test_no_bias_context_preserves_the_unbiased_sensor():
rep = representation()
obs = rep.compute_wm_obs(
torch.zeros(1, 14),
torch.zeros(1, 7),
torch.tensor([[3.0, 5.0, 7.0, 9.0]]),
torch.zeros(1, 0),
)
torch.testing.assert_close(obs[:, 6:], torch.tensor([[2.0, 3.0, 7.0, 9.0]]))


def test_default_joint_positions_follow_model_conversion_without_changing_checkpoint_keys():
rep = representation().double()
assert rep._default_joint_pos.dtype == torch.float64
assert "_default_joint_pos" not in rep.state_dict()