Skip to content

Commit 2f7f434

Browse files
bbutin-nvidiaclaude
andcommitted
Build retarget subtasks on the core Subtask
Address PR #78 review: drop the retarget-only Subtask dataclass that overlapped with autodata_interfaces.tasks.subtask_spec.Subtask. Descriptor subtasks are now parsed into the core Subtask: object_ref/description fill the core fields and the retarget-only fields (name, frame_ref, subtask_end, object_tracking, offset) go into a new RetargetSubtaskAlgoParams (a SubtaskAlgoParams subclass) via algo_params, the same extension point MimicGen/SkillGen use. The descriptor YAML layout is unchanged; core fields that only matter to generation are rejected rather than silently ignored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3f173c0 commit 2f7f434

6 files changed

Lines changed: 188 additions & 54 deletions

File tree

‎autodata_retargeting/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,11 @@ Bundles everything task/pair-specific into one file. Required references plus th
133133
`interpolation_start`/`interpolation_end`);
134134
- `name` — optional stable id (required only if referenced in `synchronization`).
135135

136+
Each segment is parsed into a core AutoData `Subtask` (`autodata_interfaces/tasks/subtask_spec.py`):
137+
`object_ref` and `description` fill the core fields, and the retarget-only keys above go into its
138+
`algo_params` (`RetargetSubtaskAlgoParams`). The other core `Subtask` fields (selection strategy, noise,
139+
term-offset ranges, ...) only matter for generation, so a retarget descriptor rejects them.
140+
136141
Minimal example (right arm picks, then places, then returns):
137142

138143
```yaml

‎autodata_retargeting/config.py‎

Lines changed: 63 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33

44
"""Task/pair retargeting configuration (the retarget-descriptor YAML schema).
55
6-
The descriptor is now self-contained: it carries its own task structure (a per-EEF list of
7-
:class:`Subtask`) instead of referencing an external task descriptor. Each subtask declares how it ends
8-
(:class:`SubtaskEnd` -- a gripper or signal event, offsettable) and, optionally, which object the EEF
9-
tracks over it (:class:`SubtaskObjectTracking`), so segmentation and object-centric planning come
6+
The descriptor is self-contained: it carries its own task structure (a per-EEF list of core
7+
:class:`~autodata_interfaces.tasks.subtask_spec.Subtask`, with retarget-specific fields in
8+
:class:`RetargetSubtaskAlgoParams`) instead of referencing an external task descriptor. Each subtask declares
9+
how it ends (:class:`SubtaskEnd` -- a gripper or signal event, offsettable) and, optionally, which object the
10+
EEF tracks over it (:class:`SubtaskObjectTracking`), so segmentation and object-centric planning come
1011
straight from this file. Retargeting replays each recorded source trajectory 1:1 onto the target robot.
1112
"""
1213

@@ -15,6 +16,7 @@
1516
from pathlib import Path
1617
from typing import Any
1718

19+
from autodata_interfaces.tasks.subtask_spec import Subtask, SubtaskAlgoParams
1820
from autodata_utils.yaml_utils import UniqueKeySafeLoader
1921

2022

@@ -218,47 +220,58 @@ def parse(cls, value: Any) -> "Offset | None":
218220

219221

220222
@dataclass
221-
class Subtask:
222-
"""One subtask in an EEF's sequence.
223+
class RetargetSubtaskAlgoParams(SubtaskAlgoParams):
224+
"""Retargeting-specific parameters of a core :class:`~autodata_interfaces.tasks.subtask_spec.Subtask`.
225+
226+
A retarget subtask is a core ``Subtask`` (``object_ref``, ``description``) whose ``algo_params`` is an
227+
instance of this class. ``subtask_end`` generalizes the core ``subtask_term_signal``: besides a signal
228+
edge it can end on a source gripper event or a fixed length, with an offset.
223229
224230
``name`` (optional) is a stable identifier for the subtask; when given it must be unique across all
225-
subtasks of all EEFs. ``object_ref`` / ``frame_ref`` name the object or frame the subtask is planned
226-
relative to; they default the reference frame a per-subtask :class:`Offset` acts in. ``subtask_end`` is
227-
required except on the last subtask of an EEF (which runs to the end of the trajectory).
228-
``object_tracking`` (optional) makes the EEF track an object over the whole subtask instead of
229-
following the source EEF path.
231+
subtasks of all EEFs. ``frame_ref`` names the frame the subtask is planned relative to when it has no
232+
``object_ref``; together they default the reference frame a per-subtask :class:`Offset` acts in.
233+
``subtask_end`` is required except on the last subtask of an EEF (which runs to the end of the
234+
trajectory). ``object_tracking`` (optional) makes the EEF track an object over the whole subtask instead
235+
of following the source EEF path. ``offset`` (optional) is a per-subtask SE(3) pose offset applied to
236+
this EEF's commanded trajectory over the subtask's span.
230237
"""
231238

232239
name: str | None = None
233-
object_ref: str | None = None
234240
frame_ref: str | None = None
235-
description: str = ""
236241
subtask_end: SubtaskEnd | None = None
237242
object_tracking: SubtaskObjectTracking | None = None
238-
# Per-subtask SE(3) pose offset applied to this EEF's commanded trajectory over the subtask's span
239-
# (see :class:`Offset`). None = no offset.
240-
offset: "Offset | None" = None
243+
offset: Offset | None = None
241244

242-
@classmethod
243-
def parse(cls, value: dict) -> "Subtask":
244-
"""Parse one subtask and its nested descriptors.
245245

246-
Args:
247-
value: Mapping of subtask field values.
246+
# Core ``Subtask`` fields a retarget descriptor may set; the rest drive generation-time segment selection
247+
# and noise, which retargeting (a 1:1 replay) does not use, so they are rejected rather than ignored.
248+
_CORE_SUBTASK_KEYS = ("object_ref", "description")
248249

249-
Returns:
250-
Parsed subtask descriptor.
251-
"""
252-
assert isinstance(value, dict), f"each subtask must be a section (dict), got {type(value).__name__}."
253-
data = dict(value)
254-
allowed = {f.name for f in fields(cls)}
255-
unknown = set(data) - allowed
256-
assert not unknown, f"unknown subtask keys {sorted(unknown)}; allowed: {sorted(allowed)}."
257-
if data.get("subtask_end") is not None:
258-
data["subtask_end"] = SubtaskEnd.parse(data["subtask_end"])
259-
data["object_tracking"] = SubtaskObjectTracking.parse(data.get("object_tracking"))
260-
data["offset"] = Offset.parse(data.get("offset"))
261-
return cls(**data)
250+
251+
def parse_subtask(value: dict) -> Subtask:
252+
"""Parse one descriptor subtask into a core :class:`Subtask` with :class:`RetargetSubtaskAlgoParams`.
253+
254+
The descriptor keeps a flat layout: ``object_ref`` / ``description`` fill the core fields, and every
255+
other key fills the retarget ``algo_params``.
256+
257+
Args:
258+
value: Mapping of subtask field values.
259+
260+
Returns:
261+
Parsed subtask.
262+
"""
263+
assert isinstance(value, dict), f"each subtask must be a section (dict), got {type(value).__name__}."
264+
algo_keys = {f.name for f in fields(RetargetSubtaskAlgoParams)}
265+
allowed = set(_CORE_SUBTASK_KEYS) | algo_keys
266+
unknown = set(value) - allowed
267+
assert not unknown, f"unknown subtask keys {sorted(unknown)}; allowed: {sorted(allowed)}."
268+
algo = {key: value[key] for key in algo_keys if key in value}
269+
if algo.get("subtask_end") is not None:
270+
algo["subtask_end"] = SubtaskEnd.parse(algo["subtask_end"])
271+
algo["object_tracking"] = SubtaskObjectTracking.parse(algo.get("object_tracking"))
272+
algo["offset"] = Offset.parse(algo.get("offset"))
273+
core = {key: value[key] for key in _CORE_SUBTASK_KEYS if value.get(key) is not None}
274+
return Subtask(**core, algo_params=RetargetSubtaskAlgoParams(**algo))
262275

263276

264277
@dataclass
@@ -336,7 +349,8 @@ class RetargetConfig:
336349
# Default object-tracking interpolation, overridable per subtask (see DefaultObjectTracking).
337350
default_object_tracking: "dict | DefaultObjectTracking" = field(default_factory=DefaultObjectTracking)
338351
# Per-EEF subtask lists (keyed by *source* EEF name; eef_name_map renames onto the target). Each entry
339-
# is parsed into a Subtask. Segmentation and object tracking come from these.
352+
# is parsed into a core Subtask with RetargetSubtaskAlgoParams. Segmentation and object tracking come from
353+
# these.
340354
subtasks: dict[str, list[Subtask]] = field(default_factory=dict)
341355
# Bimanual/multi-arm synchronization: a list of barrier groups, each a list of subtask *names* that must
342356
# conclude together. Every EEF that reaches its named segment holds at that pose until all segments in
@@ -366,18 +380,28 @@ def __post_init__(self) -> None:
366380
"""Parse nested descriptors and validate synchronization barriers."""
367381
self.default_object_tracking = DefaultObjectTracking.parse(self.default_object_tracking)
368382
self.subtasks = {
369-
eef: [st if isinstance(st, Subtask) else Subtask.parse(st) for st in entries]
383+
eef: [st if isinstance(st, Subtask) else parse_subtask(st) for st in entries]
370384
for eef, entries in (self.subtasks or {}).items()
371385
}
372-
names = [st.name for entries in self.subtasks.values() for st in entries if st.name is not None]
386+
for entries in self.subtasks.values():
387+
for st in entries:
388+
assert isinstance(
389+
st.algo_params, RetargetSubtaskAlgoParams
390+
), f"subtask algo_params must be RetargetSubtaskAlgoParams, got {type(st.algo_params).__name__}."
391+
names = [
392+
st.algo_params.name
393+
for entries in self.subtasks.values()
394+
for st in entries
395+
if st.algo_params.name is not None
396+
]
373397
duplicates = sorted({name for name in names if names.count(name) > 1})
374398
assert not duplicates, f"subtask names must be unique across all subtasks; duplicates: {duplicates}"
375399

376400
by_name = {
377-
st.name: (eef, i)
401+
st.algo_params.name: (eef, i)
378402
for eef, entries in self.subtasks.items()
379403
for i, st in enumerate(entries)
380-
if st.name is not None
404+
if st.algo_params.name is not None
381405
}
382406
# Synchronization barriers: names must exist; a group's members belong to different EEFs; each name
383407
# is in at most one group; and the declaration order is a valid schedule -- for each EEF, the groups

‎autodata_retargeting/object_tracking.py‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,17 @@ def iter_subtask_spans(
147147
end, boundary = num_steps - 1, None
148148
else:
149149
assert (
150-
st.subtask_end is not None
150+
st.algo_params.subtask_end is not None
151151
), f"subtask {i} of EEF {eef_key!r} needs a 'subtask_end' (only the last subtask may omit it)."
152152
boundary = _resolve_subtask_end(
153-
st.subtask_end, eef_key, start, num_steps, gripper_closed, signals, name_map, close_fraction
153+
st.algo_params.subtask_end,
154+
eef_key,
155+
start,
156+
num_steps,
157+
gripper_closed,
158+
signals,
159+
name_map,
160+
close_fraction,
154161
)
155162
end = num_steps - 1 if boundary is None else boundary
156163
end = max(end, start)
@@ -178,7 +185,8 @@ def carry_segments_and_boundaries_from_subtasks(
178185
non-final subtask ends are returned as the boundary steps where the replayer holds its settle, each
179186
mapped to its settle-hold cap (``SubtaskEnd.settle_steps`` if set, else ``default_settle_steps``).
180187
181-
``subtasks`` values are :class:`~.config.Subtask` objects (duck-typed). Keyed by *source* EEF name;
188+
``subtasks`` values are core ``Subtask`` objects whose ``algo_params`` is a
189+
:class:`~.config.RetargetSubtaskAlgoParams`. Keyed by *source* EEF name;
182190
``eef_name_map`` renames each onto the target EEF the segment commands. ``gripper_closed`` is keyed by
183191
*target* EEF name (per-step closedness fraction); ``signals`` by signal name.
184192
@@ -196,18 +204,19 @@ def carry_segments_and_boundaries_from_subtasks(
196204
subtasks, gripper_closed, signals, num_steps, eef_name_map, close_fraction
197205
):
198206
eef_boundaries = boundaries.setdefault(target_eef, {})
207+
params = st.algo_params
199208
if boundary is not None:
200-
override = st.subtask_end.settle_steps
209+
override = params.subtask_end.settle_steps
201210
cap = default_settle_steps if override is None else override
202211
eef_boundaries[boundary] = max(eef_boundaries.get(boundary, 0), cap)
203-
if st.name is not None:
204-
name_end_step[st.name] = (target_eef, end)
205-
if st.object_tracking is not None:
206-
iss, isa = st.object_tracking.interpolation_step_start, st.object_tracking.interpolation_step_after
212+
if params.name is not None:
213+
name_end_step[params.name] = (target_eef, end)
214+
if params.object_tracking is not None:
215+
iss, isa = params.object_tracking.interpolation_step_start, params.object_tracking.interpolation_step_after
207216
segments.append(
208217
CarrySegment(
209218
eef=target_eef,
210-
obj=st.object_tracking.object,
219+
obj=params.object_tracking.object,
211220
start=start,
212221
end=end,
213222
interp_start=default_interp_start if iss is None else iss,

‎autodata_retargeting/replay.py‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from isaaclab.utils.datasets import EpisodeData
1313

1414
from autodata_interfaces.embodiments.embodiment_adapter import EmbodimentAdapter
15+
from autodata_interfaces.tasks.subtask_spec import Subtask
1516
from autodata_utils.tensor_utils import as_torch
1617

1718
from .config import DefaultObjectTracking
@@ -553,6 +554,13 @@ def _offset_se3(translation, axis_angle, scale: float, ref: torch.Tensor) -> tor
553554
return mat
554555

555556

557+
def _subtask_offset_frame(subtask: Subtask) -> str:
558+
"""The frame a subtask's offset acts in: ``offset.frame``, else ``object_ref``, else ``frame_ref``, else ``eef``."""
559+
params = subtask.algo_params
560+
off_frame = params.offset.frame if params.offset is not None else None
561+
return off_frame or subtask.object_ref or params.frame_ref or "eef"
562+
563+
556564
def apply_subtask_offsets(
557565
target_eef_poses: dict[str, torch.Tensor],
558566
subtasks: dict,
@@ -577,13 +585,13 @@ def apply_subtask_offsets(
577585
for _eef_key, eef, _index, st, start, end, _boundary in iter_subtask_spans(
578586
subtasks, gripper_closed, signals, num_steps, eef_name_map, close_fraction
579587
):
580-
off = getattr(st, "offset", None)
588+
off = st.algo_params.offset
581589
per_eef.setdefault(eef, []).append({
582590
"start": start,
583591
"end": end,
584592
"trans": list(off.translation) if (off and off.translation) else [0.0, 0.0, 0.0],
585593
"aa": list(off.axis_angle) if (off and off.axis_angle) else [0.0, 0.0, 0.0],
586-
"frame": (off.frame if (off and off.frame) else None) or st.object_ref or st.frame_ref or "eef",
594+
"frame": _subtask_offset_frame(st),
587595
"i_start": off.interpolation_start if off else 0,
588596
"i_end": off.interpolation_end if off else 0,
589597
"has_offset": off is not None,
@@ -627,10 +635,9 @@ def subtasks_need_source_objects(subtasks: dict) -> bool:
627635
"""
628636
for entries in subtasks.values():
629637
for st in entries:
630-
if st.object_tracking is not None:
638+
if st.algo_params.object_tracking is not None:
631639
return True
632-
off = getattr(st, "offset", None)
633-
if off is not None and (off.frame or st.object_ref or st.frame_ref or "eef") not in _RESERVED_OFFSET_FRAMES:
640+
if st.algo_params.offset is not None and _subtask_offset_frame(st) not in _RESERVED_OFFSET_FRAMES:
634641
return True
635642
return False
636643

@@ -698,7 +705,7 @@ def _achieved_eef_poses() -> dict[str, torch.Tensor]:
698705
source_objects = source_object_poses(episode) if need_source_objects else {}
699706
# Signals are read when a subtask ends on a signal event and/or to forward them into the output.
700707
needs_signals = write_datagen_info or any(
701-
st.subtask_end is not None and st.subtask_end.method in ("signal_on", "signal_off")
708+
st.algo_params.subtask_end is not None and st.algo_params.subtask_end.method in ("signal_on", "signal_off")
702709
for entries in subtasks.values()
703710
for st in entries
704711
)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Tests for retarget-descriptor parsing into core subtasks."""
5+
6+
import os
7+
8+
import pytest
9+
10+
from autodata_interfaces.tasks.subtask_spec import Subtask
11+
from autodata_retargeting.config import RetargetConfig, RetargetSubtaskAlgoParams, parse_subtask
12+
13+
_RETARGET_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "autodata_examples", "retarget")
14+
15+
16+
def test_parse_subtask_splits_core_and_retarget_fields():
17+
st = parse_subtask({
18+
"name": "grasp",
19+
"object_ref": "cube",
20+
"description": "Grasp the cube.",
21+
"subtask_end": {"method": "gripper_close", "offset": 5},
22+
"object_tracking": "cube",
23+
"offset": {"translation": [0, 0, 0.01]},
24+
})
25+
assert isinstance(st, Subtask)
26+
assert st.object_ref == "cube"
27+
assert st.description == "Grasp the cube."
28+
params = st.algo_params
29+
assert isinstance(params, RetargetSubtaskAlgoParams)
30+
assert params.name == "grasp"
31+
assert params.subtask_end.method == "gripper_close" and params.subtask_end.offset == 5
32+
assert params.object_tracking.object == "cube"
33+
assert params.offset.translation == [0.0, 0.0, 0.01]
34+
35+
36+
def test_parse_subtask_defaults_to_core_defaults():
37+
st = parse_subtask({"frame_ref": "world"})
38+
assert st.object_ref == ""
39+
assert st.algo_params.frame_ref == "world"
40+
assert st.algo_params.subtask_end is None
41+
assert st.algo_params.object_tracking is None
42+
assert st.algo_params.offset is None
43+
44+
45+
@pytest.mark.parametrize("key", ["selection_strategy", "action_noise", "not_a_key"])
46+
def test_parse_subtask_rejects_unsupported_keys(key):
47+
with pytest.raises(AssertionError, match="unknown subtask keys"):
48+
parse_subtask({key: 0})
49+
50+
51+
def test_synchronization_resolves_names_from_algo_params():
52+
config = RetargetConfig(
53+
source_embodiment="src.yaml",
54+
target_embodiment="tgt.yaml",
55+
target_env_name="env",
56+
subtasks={
57+
"left": [{"name": "l_release", "subtask_end": "gripper_open"}, {}],
58+
"right": [{"name": "r_grasp", "subtask_end": "gripper_close"}, {}],
59+
},
60+
synchronization=[["l_release", "r_grasp"]],
61+
)
62+
assert config.subtasks["left"][0].algo_params.name == "l_release"
63+
64+
65+
def test_duplicate_subtask_names_rejected():
66+
with pytest.raises(AssertionError, match="unique"):
67+
RetargetConfig(
68+
source_embodiment="src.yaml",
69+
target_embodiment="tgt.yaml",
70+
target_env_name="env",
71+
subtasks={"left": [{"name": "a", "subtask_end": "gripper_open"}, {"name": "a"}]},
72+
)
73+
74+
75+
@pytest.mark.parametrize("yaml_name", ["g1_to_gr1_pick_place.yaml", "gr1_to_g1_pick_place.yaml"])
76+
def test_shipped_retarget_descriptors_parse(yaml_name):
77+
config = RetargetConfig.from_yaml(os.path.join(_RETARGET_DIR, yaml_name))
78+
assert config.subtasks
79+
for entries in config.subtasks.values():
80+
assert all(isinstance(st.algo_params, RetargetSubtaskAlgoParams) for st in entries)
81+
82+
83+
def test_from_yaml_rejects_duplicate_keys(tmp_path):
84+
path = tmp_path / "dup.yaml"
85+
path.write_text("source_embodiment: a\nsource_embodiment: b\ntarget_embodiment: c\ntarget_env_name: d\n")
86+
with pytest.raises(AssertionError, match="duplicate key"):
87+
RetargetConfig.from_yaml(str(path))

0 commit comments

Comments
 (0)