File size: 12,277 Bytes
0a3f650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""Dense pose targets with one fixed reference per observation/chunk."""

from typing import Literal

import torch
from mani_skill.utils.geometry.rotation_conversions import quaternion_to_matrix

from lim.action_encoding import controller_to_sixd, matrix_to_sixd, sixd_to_matrix

RELATIVE_POSE_CONTRACT = {
    "version": "chunk_start_pose6d_v1",
    "position": "(world_command_target - observed_chunk_start_tcp) / 0.1",
    "rotation": "scaled6d(R_world_command_target @ R_chunk_start_tcp.T)",
    "gripper": "original continuous command, not a relative offset",
    "target_source": "each saved pre-action TCP composed with its own controller command",
    "padding": "terminal measured TCP pose and last gripper command",
    "normalization_population": "all valid anchor/future-target pairs, no terminal padding",
}

ABSOLUTE_POSE_CONTRACT = {
    "version": "absolute_world_pose6d_v1",
    "position": "world_command_target / 0.1, no anchor subtraction",
    "rotation": "scaled6d(R_world_command_target), no anchor rotation removed",
    "gripper": "original continuous command, not a relative offset",
    "target_source": "each saved pre-action TCP composed with its own controller command",
    "padding": "terminal measured TCP pose and last gripper command",
    "normalization_population": "all valid future targets, no terminal padding",
    "isolation": "identical to chunk_start_pose6d_v1 except the label anchor; the"
    " controller boundary still converts against the real measured TCP",
}

ChunkAnchor = Literal["chunk_start_tcp", "identity"]
ChunkPoseSupervision = Literal[
    "dense", "future_endpoint", "current_endpoint", "phase_segments", "future_waypoint",
    "bspline",
]
ChunkGripperSupervision = Literal["future", "current"]
ChunkPadding = Literal["terminal", "current_target"]


def pose_target_contract(
    anchor: ChunkAnchor,
    supervision: ChunkPoseSupervision,
    gripper: ChunkGripperSupervision = "future",
    padding: ChunkPadding = "terminal",
    normalization_population: Literal["dense", "supervised"] = "dense",
    label_offset: int = 0,
    waypoint_threshold_m: float | None = None,
    bspline_knots: int | None = None,
):
    """Persist target semantics for the audited StackCube world-frame dataset.

    An identity anchor keeps coordinates in the stored TCP/keyframe frame; that
    frame is world in this simulator, not a universal property of absolute poses.
    Existing dense-population recipes retain their checkpoint contract exactly.
    """
    if anchor not in ("chunk_start_tcp", "identity"):
        raise ValueError(f"Unknown chunk anchor mode: {anchor}")
    if (supervision == "future_waypoint") != (waypoint_threshold_m is not None):
        raise ValueError("Exactly the waypoint supervision carries a waypoint threshold")
    if (supervision == "bspline") != (bspline_knots is not None):
        raise ValueError("Exactly the B-spline supervision carries a knot count")
    if supervision == "bspline":
        from lim.bspline_chunk import DEGREE, FIT_TOLERANCE

        if (anchor, gripper, padding, normalization_population, label_offset) != (
            "chunk_start_tcp", "future", "terminal", "dense", 0
        ):
            raise ValueError("B-spline labels use the TCP anchor and default label fields")
        return {
            **RELATIVE_POSE_CONTRACT,
            "version": f"chunk_start_pose6d_bspline_k{bspline_knots}_tol{FIT_TOLERANCE:g}_v1",
            "pose_supervision": supervision,
            "bspline_knots": bspline_knots,
            "target_source": "each demonstration's dense targets and terminal TCP fitted once"
            f" by a degree-{DEGREE} B-spline (FITPACK knot insertion, max abs sample error"
            f" < {FIT_TOLERANCE:g} in xyz m / rotation-matrix entries / gripper); the"
            " observation's segment starts at the knot interval containing it",
            "layout": f"{bspline_knots + 2 * DEGREE} rows of [knot steps relative to the"
            " observation, control point target10 in the observation's TCP frame]",
            "gripper": "fitted with the pose in the same spline, not a relative offset",
            "padding": "past the fitted end, knots and control points repeat the last",
            "normalization_population": "every row of every observation's segment",
        }
    if supervision == "future_waypoint":
        if (anchor, gripper, padding, normalization_population, label_offset) != (
            "chunk_start_tcp", "future", "terminal", "dense", 0
        ):
            raise ValueError("Waypoint labels use the TCP anchor and default label fields")
        return {
            **RELATIVE_POSE_CONTRACT,
            "version": f"chunk_start_pose6d_future_waypoint_eta{waypoint_threshold_m:g}_v1",
            "pose_supervision": supervision,
            "waypoint_threshold_m": waypoint_threshold_m,
            "target_source": "dense controller target at the first AWE waypoint strictly after each future action time; waypoints by dynamic programming on target positions with gripper changes forced, the last action maps to itself",
            "gripper": "original future dense gripper command at each slot, unchanged",
            "normalization_population": "original dense valid anchor/future-target pairs, no terminal padding",
        }
    if supervision == "phase_segments":
        if (anchor, gripper, padding, normalization_population, label_offset) != (
            "chunk_start_tcp", "future", "terminal", "dense", 0
        ):
            raise ValueError("Phase segments use the TCP anchor and default label fields")
        return {
            **RELATIVE_POSE_CONTRACT,
            "version": "chunk_start_pose6d_phase_segments_v1",
            "pose_supervision": supervision,
            "target_source": "slot0 current primitive endpoint, slot1 next primitive endpoint (last primitive repeats)",
            "gripper": "each slot carries its own primitive gripper command",
            "padding": "none; both slots always exist",
            "switch": "remaining steps in the current primitive, min(steps,30)/30, from decoder query zero",
            "normalization_population": "frozen statistics from a completed training; never refit",
        }
    if label_offset:
        if label_offset < 0 or supervision != "future_endpoint" or anchor != "chunk_start_tcp":
            raise ValueError("Lookahead offsets apply to TCP-anchored future endpoints")
        original = pose_target_contract(
            anchor, supervision, gripper, padding, normalization_population
        )
        return {
            **original,
            "version": original["version"] + f"_lookahead{label_offset}_v1",
            "label_offset": label_offset,
            "target_source": f"primitive endpoint and gripper at time t+{label_offset}+i",
            "normalization_population": "frozen statistics from a completed training; never refit",
        }
    if normalization_population == "supervised":
        if (
            supervision != "current_endpoint"
            or gripper != "current"
            or padding != "current_target"
        ):
            raise ValueError(
                "Supervised normalization requires repeated complete current-target endpoint labels"
            )
        original = pose_target_contract(anchor, supervision, gripper, padding)
        return {
            **original,
            "version": original["version"] + "_supervised_population_v1",
            "anchor": anchor,
            "normalization_population": "query-zero complete current endpoint once per original observation; no future-pair or padding reweighting",
        }
    if normalization_population != "dense":
        raise ValueError("Unknown chunk normalization population")
    if padding == "current_target":
        if supervision != "current_endpoint" or gripper != "current":
            raise ValueError(
                "Current-target padding requires current endpoint and gripper"
            )
        original = pose_target_contract(anchor, supervision, gripper)
        return {
            **original,
            "version": original["version"] + "_current_padding_v1",
            "padding": "repeat current observation complete endpoint target in all out-of-range slots",
            "gripper": "current observation command repeated in every slot including padding",
        }
    if padding != "terminal":
        raise ValueError("Unknown chunk padding")
    if gripper == "current":
        original = pose_target_contract(anchor, supervision)
        return {
            **original,
            "version": original["version"] + "_current_gripper_v1",
            "gripper": "current observation command repeated in valid slots; terminal padding unchanged",
            "gripper_supervision": "current",
        }
    if gripper != "future":
        raise ValueError("Unknown chunk gripper supervision")
    base = (
        RELATIVE_POSE_CONTRACT
        if anchor == "chunk_start_tcp"
        else ABSOLUTE_POSE_CONTRACT
    )
    if supervision == "dense":
        return base
    if supervision not in ("future_endpoint", "current_endpoint"):
        raise ValueError("Unknown endpoint supervision")
    return {
        **base,
        "version": (
            f"chunk_start_pose6d_{supervision}_v1"
            if anchor == "chunk_start_tcp"
            else f"absolute_world_pose6d_{supervision}_v1"
        ),
        "pose_supervision": supervision,
        "target_source": (
            "primitive endpoint at each future action time"
            if supervision == "future_endpoint"
            else "current observation primitive endpoint repeated in valid future slots"
        ),
        "gripper": "original future dense gripper command at each slot, unchanged",
        "normalization_population": "original dense valid anchor/future-target pairs, no terminal padding",
        **(
            {
                "anchor": "identity",
                "coordinate_frame": "stored TCP/keyframe frame, world in this audited StackCube dataset",
            }
            if anchor == "identity"
            else {}
        ),
    }


def resolve_anchor(anchor, mode: ChunkAnchor):
    """Pick the label origin; identity preserves the stored pose coordinate frame.

    Only the label/restore frame changes. Converting an absolute goal into a physical
    controller delta always uses the real measured TCP, so this stays a pure
    representation switch rather than a change of what is commanded.
    """
    if mode == "chunk_start_tcp":
        return anchor
    if mode != "identity":
        raise ValueError(f"Unknown chunk anchor mode: {mode}")
    shape = (*anchor.shape[:-1], 7)
    fixed = torch.zeros(shape, dtype=anchor.dtype, device=anchor.device)
    fixed[..., 3] = 1.0  # identity quaternion, zero translation
    return fixed


def controller_pose_targets(actions, tcp):
    """Reconstruct actual CPU controller goals in audited world-aligned root axes."""
    if actions.shape[-1] != 7 or tcp.shape[-1] != 7:
        raise ValueError("Expected controller7 and world TCP7")
    delta = controller_to_sixd(actions)
    rotation = sixd_to_matrix(delta[..., 3:9]) @ quaternion_to_matrix(tcp[..., 3:])
    return torch.cat(
        [
            tcp[..., :3] + actions[..., :3].clamp(-1, 1) * 0.1,
            matrix_to_sixd(rotation),
            actions[..., -1:],
        ],
        -1,
    )


def world_to_chunk_relative(target, anchor):
    """World target10 -> fixed-origin translation and root-aligned relative rotation."""
    rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(
        anchor[..., 3:]
    ).transpose(-1, -2)
    return torch.cat(
        [
            (target[..., :3] - anchor[..., :3]) / 0.1,
            matrix_to_sixd(rotation),
            target[..., -1:],
        ],
        -1,
    )


def chunk_relative_to_world(target, anchor):
    """Restore every goal using the SAME anchor; never integrate or clip offsets."""
    rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix(anchor[..., 3:])
    return torch.cat(
        [
            anchor[..., :3] + target[..., :3] * 0.1,
            matrix_to_sixd(rotation),
            target[..., -1:],
        ],
        -1,
    )