File size: 26,481 Bytes
d011890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
"""Variable-body relationship model with a shared geometric function space.

The learned node MLP never receives absolute position or quaternion. Directed
relations use source-local relative SE(3), velocities and measured geometry.
The physical core is gated graph integration, not an embodiment classifier.
Goal trajectories and numerical actuator controls share this relational space.
"""
from __future__ import annotations

from dataclasses import asdict, dataclass
import math

import torch
from torch import nn
import torch.nn.functional as F


NODE_DIM = 27
ACTUATOR_DIM = 40
RELATION_DIM = 24
SCHEMA = "rigby.variable_relationship_graph.v2"


@dataclass
class ModelConfig:
    width: int = 384
    state_blocks: int = 4
    effect_blocks: int = 2
    text_blocks: int = 2
    goal_atoms: int = 8
    inverse_modes: int = 5
    text_vocabulary: int = 257
    dropout: float = 0.


def mlp(n_in, width, n_out, expansion=2):
    return nn.Sequential(nn.Linear(n_in, expansion * width), nn.GELU(), nn.Linear(expansion * width, n_out))


def gather_nodes(value, index):
    return value.gather(1, index[..., None].expand(*index.shape, value.shape[-1]))


def quat_matrix(quaternion):
    q = quaternion / quaternion.norm(dim=-1, keepdim=True).clamp_min(1e-8)
    w, x, y, z = q.unbind(-1)
    return torch.stack((1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w),
                        2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w),
                        2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y)), -1).reshape(*q.shape[:-1], 3, 3)


def dense_edges(batch_size, nodes, device):
    row, column = torch.meshgrid(torch.arange(nodes, device=device), torch.arange(nodes, device=device), indexing="ij")
    valid = row != column
    return torch.stack((row[valid], column[valid]), -1)[None].expand(batch_size, -1, -1)


def edge_indices(batch):
    state = batch["node_state"]
    b, n = state.shape[:2]
    if n < 2:
        raise ValueError("A relational state needs at least two measured entities")
    edges = batch.get("edge_index")
    if edges is None:
        if n > 96:
            raise ValueError("Provide sparse topology/neighbour/object edges for graphs above 96 nodes")
        edges = dense_edges(b, n, state.device)
    edges = edges.long()
    if edges.ndim != 3 or edges.shape[0] != b or edges.shape[-1] != 2:
        raise ValueError("edge_index must be [B,E,2]")
    edge_mask = batch.get("edge_mask", torch.ones(edges.shape[:2], device=state.device, dtype=torch.bool)).bool()
    if bool(((edges < 0) | (edges >= n))[edge_mask].any()):
        raise ValueError("Relationship edge references a nonexistent node")
    edges = edges.clamp(0, n - 1)
    node_mask = batch["node_mask"].bool()
    edge_mask = edge_mask & node_mask.gather(1, edges[..., 0]) & node_mask.gather(1, edges[..., 1])
    return edges, edge_mask


def node_features(batch):
    raw = batch["node_state"]
    known = batch["feature_mask"].bool()
    if raw.shape[-1] != NODE_DIM or known.shape != raw.shape:
        raise ValueError("node_state and feature_mask require the measured 27-field ABI")
    rotation = quat_matrix(raw[..., 3:7])
    local = rotation.transpose(-1, -2)
    local_linear = (local @ raw[..., 7:10, None]).squeeze(-1)
    local_angular = (local @ raw[..., 10:13, None]).squeeze(-1)
    gravity = batch.get("gravity")
    if gravity is None:
        raise ValueError("Supply the physical world's measured/configured gravity vector")
    gravity_local = (local @ gravity[:, None, :, None]).squeeze(-1) / 9.81
    com = batch.get("node_com_offset", batch.get("body_com_offset", torch.zeros_like(raw[..., :3])))
    com_default = torch.ones_like(raw[..., :3], dtype=torch.bool) if "node_com_offset" in batch or "body_com_offset" in batch else torch.zeros_like(raw[..., :3], dtype=torch.bool)
    com_known = batch.get("node_com_mask", com_default)
    controlled = batch["node_controlled"].to(raw.dtype)[..., None]
    values = torch.cat((local_linear / .1, local_angular, raw[..., 13:16] / .1,
                        raw[..., 16:17], raw[..., 17:20], raw[..., 20:26], raw[..., 26:27],
                        controlled, gravity_local, com / .1), -1)
    rotation_known = known[..., 3:7].all(-1, keepdim=True)
    masks = torch.cat(((known[..., 7:10].all(-1, keepdim=True) & rotation_known).expand(-1, -1, 3),
                       (known[..., 10:13].all(-1, keepdim=True) & rotation_known).expand(-1, -1, 3),
                       known[..., 13:27], torch.ones_like(controlled, dtype=torch.bool),
                       (rotation_known & batch.get("gravity_mask", torch.ones_like(gravity, dtype=torch.bool))[:, None].all(-1, keepdim=True)).expand(-1, -1, 3), com_known.bool()), -1)
    if values.shape[-1] != 27:
        raise RuntimeError("Invariant node feature ABI drift")
    # Infinite plane tangent extents are undefined, rather than a finite box.
    plane = batch.get("node_geomtype", torch.full(raw.shape[:2], -1, device=raw.device)) == 0
    masks[..., 6:8] &= ~plane[..., None]
    return torch.asinh(values) * masks.to(raw.dtype), masks


def relation_features(batch, edges, edge_mask):
    raw, known = batch["node_state"], batch["feature_mask"].bool()
    b, n = raw.shape[:2]
    source, target = edges.unbind(-1)
    x, y = gather_nodes(raw, source), gather_nodes(raw, target)
    kx, ky = gather_nodes(known, source), gather_nodes(known, target)
    rx, ry = quat_matrix(x[..., 3:7]), quat_matrix(y[..., 3:7])
    displacement = y[..., :3] - x[..., :3]
    geomtype = batch.get("node_geomtype", torch.full((b, n), -1, device=raw.device))
    plane_source, plane_target = geomtype.gather(1, source) == 0, geomtype.gather(1, target) == 0
    # A plane's arbitrary tangent origin must not become a learned distance.
    normal = torch.where(plane_target[..., None], ry[..., :, 2], rx[..., :, 2])
    plane_displacement = (displacement * normal).sum(-1, keepdim=True) * normal
    displacement = torch.where((plane_source | plane_target)[..., None], plane_displacement, displacement)
    local = rx.transpose(-1, -2)
    relative_position = (local @ displacement[..., None]).squeeze(-1) / .1
    relative_rotation = local @ ry
    rotation6 = relative_rotation[..., :, :2].transpose(-1, -2).reshape(b, -1, 6)
    linear = (local @ (y[..., 7:10] - x[..., 7:10])[..., None]).squeeze(-1) / .1
    angular = (local @ (y[..., 10:13] - x[..., 10:13])[..., None]).squeeze(-1)
    distance = displacement.norm(dim=-1, keepdim=True) / .1
    topology = raw.new_zeros((b, n, n))
    parent_edges = batch.get("parent_edges")
    if parent_edges is not None:
        valid_parent = batch.get("parent_edge_mask", torch.ones(parent_edges.shape[:2], device=raw.device, dtype=torch.bool)).bool()
        if bool(((parent_edges < 0) | (parent_edges >= n))[valid_parent].any()):
            raise ValueError("Parent edge references a nonexistent node")
        pe = parent_edges.clamp(0, n - 1).long()
        bi = torch.arange(b, device=raw.device)[:, None].expand_as(pe[..., 0])
        topology[bi[valid_parent], pe[..., 0][valid_parent], pe[..., 1][valid_parent]] = 1
        topology[bi[valid_parent], pe[..., 1][valid_parent], pe[..., 0][valid_parent]] = 1
    linked = topology[torch.arange(b, device=raw.device)[:, None], source, target][..., None]
    values = torch.cat((relative_position, rotation6, linear, angular, distance,
                        x[..., 13:16] / .1, y[..., 13:16] / .1, linked, torch.ones_like(linked)), -1)
    source_rotation = kx[..., 3:7].all(-1, keepdim=True)
    position_known = kx[..., :3].all(-1, keepdim=True) & ky[..., :3].all(-1, keepdim=True) & source_rotation
    rotation_known = source_rotation & ky[..., 3:7].all(-1, keepdim=True)
    linear_known = kx[..., 7:10].all(-1, keepdim=True) & ky[..., 7:10].all(-1, keepdim=True) & source_rotation
    angular_known = kx[..., 10:13].all(-1, keepdim=True) & ky[..., 10:13].all(-1, keepdim=True) & source_rotation
    masks = torch.cat((position_known.expand(-1, -1, 3), rotation_known.expand(-1, -1, 6),
                       linear_known.expand(-1, -1, 3), angular_known.expand(-1, -1, 3), position_known,
                       kx[..., 13:16], ky[..., 13:16], torch.ones_like(linked, dtype=torch.bool),
                       torch.ones_like(linked, dtype=torch.bool)), -1)
    masks[..., 16:18] &= ~plane_source[..., None]
    masks[..., 19:21] &= ~plane_target[..., None]
    masks &= edge_mask[..., None]
    # Rotation matrix entries and structural flags retain their natural scale.
    transformed = values.clone()
    for section in (slice(0, 3), slice(9, 22)):
        transformed[..., section] = torch.asinh(values[..., section])
    return transformed * masks.to(raw.dtype), masks


class GeometricRelationBlock(nn.Module):
    def __init__(self, width):
        super().__init__()
        self.edge_norm = nn.LayerNorm(width)
        self.node_norm = nn.LayerNorm(width)
        self.edge_update = mlp(3 * width, width, width)
        self.gate = nn.Sequential(nn.Linear(width, width), nn.GELU(), nn.Linear(width, 1))
        self.node_update = mlp(2 * width, width, width, expansion=4)

    def forward(self, nodes, relations, edges, node_mask, edge_mask):
        source, target = edges.unbind(-1)
        h = self.node_norm(nodes)
        update = self.edge_update(torch.cat((gather_nodes(h, source), gather_nodes(h, target), self.edge_norm(relations)), -1))
        relations = (relations + update) * edge_mask[..., None]
        weights = self.gate(relations).sigmoid() * edge_mask[..., None]
        pooled = torch.zeros_like(nodes)
        pooled.scatter_add_(1, source[..., None].expand_as(relations), relations * weights)
        normalizer = nodes.new_zeros((*nodes.shape[:2], 1))
        normalizer.scatter_add_(1, source[..., None], weights)
        pooled = pooled / normalizer.clamp_min(1.)
        nodes = (nodes + self.node_update(torch.cat((h, pooled), -1))) * node_mask[..., None]
        return nodes, relations


class ByteTaskEncoder(nn.Module):
    def __init__(self, config):
        super().__init__()
        d = config.width
        self.embedding = nn.Embedding(config.text_vocabulary, d, padding_idx=0)
        self.encoder = nn.TransformerEncoder(nn.TransformerEncoderLayer(d, 8, 4 * d,
            dropout=config.dropout, activation="gelu", batch_first=True), config.text_blocks, enable_nested_tensor=False)

    def forward(self, tokens, mask):
        if not bool(mask.any(-1).all()):
            raise ValueError("Each task needs text bytes, or use explicit demonstrated goal tokens")
        length, width = tokens.shape[1], self.embedding.embedding_dim
        position = torch.arange(length, device=tokens.device, dtype=torch.float32)[:, None]
        frequencies = torch.exp(torch.arange(0, width, 2, device=tokens.device) * (-math.log(10000.) / width))
        pe = torch.stack(((position * frequencies).sin(), (position * frequencies).cos()), -1).flatten(-2)
        x = self.embedding(tokens.long()) + pe[None]
        return self.encoder(x, src_key_padding_mask=~mask.bool()) * mask[..., None]


def encode_text(texts, maximum_bytes=256, device="cpu"):
    encoded = [list(text.encode("utf-8")[:maximum_bytes]) for text in texts]
    if not encoded or min(map(len, encoded)) < 1:
        raise ValueError("Task descriptions cannot be empty")
    result = torch.zeros((len(encoded), max(map(len, encoded))), dtype=torch.long, device=device)
    for row, values in enumerate(encoded):
        result[row, :len(values)] = torch.tensor(values, dtype=torch.long, device=device) + 1
    return result, result != 0


class VariableRelationshipModel(nn.Module):
    def __init__(self, config=None):
        super().__init__()
        self.config = config or ModelConfig()
        d = self.config.width
        if d % 8:
            raise ValueError("Width must be divisible by eight")
        self.node_encoder = mlp(54, d, d)
        self.edge_encoder = mlp(2 * RELATION_DIM, d, d)
        self.actuator_encoder = mlp(97, d, d)
        self.state_blocks = nn.ModuleList(GeometricRelationBlock(d) for _ in range(self.config.state_blocks))
        self.effect_blocks = nn.ModuleList(GeometricRelationBlock(d) for _ in range(self.config.effect_blocks))
        self.action_difference = nn.Linear(d, d)
        self.effect_time = mlp(1, d, d)
        self.future_delta = mlp(d, d, d)
        self.relation_decoder = mlp(d, d, RELATION_DIM)
        self.relation_delta = mlp(d, d, RELATION_DIM)
        self.node_decoder = mlp(d, d, 27)
        self.task_encoder = ByteTaskEncoder(self.config)
        self.goal_queries = nn.Parameter(torch.randn(self.config.goal_atoms, d) / math.sqrt(d))
        self.time_encoder = mlp(9, d, d)
        self.goal_graph_attention = nn.MultiheadAttention(d, 8, dropout=0., batch_first=True)
        self.goal_text_attention = nn.MultiheadAttention(d, 8, dropout=0., batch_first=True)
        self.goal_context_attention = nn.MultiheadAttention(d, 8, dropout=0., batch_first=True)
        self.goal_refine = nn.TransformerEncoder(nn.TransformerEncoderLayer(d, 8, 4*d,
            dropout=0., activation="gelu", batch_first=True), 2, enable_nested_tensor=False)
        self.goal_alignment = nn.MultiheadAttention(d, 8, dropout=0., batch_first=True)
        self.energy = mlp(4 * d, d, 1)
        # Task-goal tokens query the current and candidate relation sets. Their
        # change is a task-conditioned potential in relationship space, rather
        # than a body-class or actuator-name score.
        self.task_relation_attention = nn.MultiheadAttention(d, 8, dropout=0., batch_first=True)
        self.task_completion_head = mlp(4 * d, d, 1)
        self.inverse_goal_attention = nn.MultiheadAttention(d, 8, dropout=0., batch_first=True)
        self.inverse_control = mlp(3 * d, d, 2 * self.config.inverse_modes)
        self.inverse_mode_logits = mlp(2 * d, d, self.config.inverse_modes)
        self.instruction_grounding = nn.Linear(2, d, bias=False)

    def actuator_tokens(self, batch, control=None):
        values = batch["actuator_features"]
        known = batch["actuator_feature_mask"].bool()
        if values.shape[-1] != ACTUATOR_DIM or known.shape != values.shape:
            raise ValueError("Actuator features require the numerical 40-field ABI")
        state = batch.get("actuator_state", values.new_zeros((*values.shape[:2], 4)))
        state_mask = batch.get("actuator_state_mask", torch.zeros_like(state, dtype=torch.bool)).bool()
        anchor = batch.get("joint_anchor_local", batch.get("actuator_joint_anchor_local", values.new_zeros((*values.shape[:2], 3))))
        anchor_mask = batch.get("joint_anchor_mask", batch.get("actuator_joint_anchor_mask", torch.zeros_like(anchor, dtype=torch.bool))).bool()
        u = values.new_zeros((*values.shape[:2], 1)) if control is None else control[..., None]
        u_mask = torch.zeros_like(u, dtype=torch.bool) if control is None else batch["actuator_mask"][..., None].bool()
        range_known = known[..., :2].all(-1, keepdim=True) & ((values[..., 1:2] - values[..., :1]).abs() > 1e-6)
        center = torch.where(range_known, values[..., :2].mean(-1, keepdim=True), torch.zeros_like(u))
        scale = torch.where(range_known, (values[..., 1:2] - values[..., :1]).abs().mul(.5), torch.ones_like(u))
        u = torch.where(u_mask, (u - center) / scale, torch.zeros_like(u))
        delta_t = batch["delta_t"][:, None, None].expand(-1, values.shape[1], 1) if control is not None else torch.zeros_like(u)
        tokens = torch.cat((torch.asinh(values) * known, known.to(values.dtype),
                            torch.asinh(state) * state_mask, state_mask.to(values.dtype),
                            torch.asinh(u), u_mask.to(values.dtype), delta_t,
                            torch.asinh(anchor / .1) * anchor_mask, anchor_mask.to(values.dtype)), -1)
        if tokens.shape[-1] != 97:
            raise RuntimeError("Actuator ABI drift")
        return self.actuator_encoder(tokens) * batch["actuator_mask"][..., None]

    @staticmethod
    def attach_actuators(batch, tokens):
        n = batch["node_state"].shape[1]
        indices = batch["actuator_node"].long()
        valid = batch["actuator_mask"].bool()
        if bool(((indices < 0) | (indices >= n))[valid].any()):
            raise ValueError("Actuator references a nonexistent body")
        indices = indices.clamp(0, n-1)
        pooled = tokens.new_zeros((len(tokens), n, tokens.shape[-1]))
        pooled.scatter_add_(1, indices[..., None].expand_as(tokens), tokens)
        counts = tokens.new_zeros((len(tokens), n, 1))
        counts.scatter_add_(1, indices[..., None], valid[..., None].to(tokens.dtype))
        return pooled / counts.clamp_min(1.)

    def encode_state(self, batch):
        edges, edge_mask = edge_indices(batch)
        nodes, node_known = node_features(batch)
        relationships, relation_known = relation_features(batch, edges, edge_mask)
        h = self.node_encoder(torch.cat((nodes, node_known.to(nodes.dtype)), -1))
        binding = batch.get("instruction_node_roles")
        if binding is not None:
            if binding.shape != (*h.shape[:2], 2):
                raise ValueError("Instruction grounding is [B,N,2]: supplied object and target bindings")
            h = h + self.instruction_grounding(binding.to(h.dtype))
        e = self.edge_encoder(torch.cat((relationships, relation_known.to(nodes.dtype)), -1))
        h = (h + self.attach_actuators(batch, self.actuator_tokens(batch))) * batch["node_mask"][..., None]
        e = e * edge_mask[..., None]
        for block in self.state_blocks:
            h, e = block(h, e, edges, batch["node_mask"], edge_mask)
        return dict(nodes=h, relation=e, edge_index=edges, edge_mask=edge_mask,
                    physical_relation=relationships, relation_feature_mask=relation_known,
                    physical_node=nodes, node_feature_mask=node_known)

    def predict_effect(self, batch, control, state=None):
        state = state or self.encode_state(batch)
        passive = self.actuator_tokens(batch)
        action = self.actuator_tokens(batch, control)
        h = state["nodes"] + self.action_difference(self.attach_actuators(batch, action - passive))
        h = h + self.effect_time(batch["delta_t"][:, None])[:, None]
        e = state["relation"]
        for block in self.effect_blocks:
            h, e = block(h, e, state["edge_index"], batch["node_mask"], state["edge_mask"])
        future = (state["relation"] + self.future_delta(e)) * state["edge_mask"][..., None]
        return dict(state=state, future_relation=future, future_nodes=h,
                    reconstructed_relation=self.relation_decoder(state["relation"]),
                    reconstructed_node=self.node_decoder(state["nodes"]),
                    predicted_relation_delta=self.relation_delta(e))

    def encode_goal_state(self, batch):
        """Desired physical relationships do not include future servo intent."""
        observed = dict(batch)
        if "actuator_state" in observed:
            observed["actuator_state"] = observed["actuator_state"].clone()
            observed["actuator_state"][..., 3] = 0
        if "actuator_state_mask" in observed:
            observed["actuator_state_mask"] = observed["actuator_state_mask"].clone()
            observed["actuator_state_mask"][..., 3] = False
        return self.encode_state(observed)

    def time_features(self, times):
        phase = times[..., None] * times.new_tensor([1., 2., 4., 8.]) * math.pi
        return self.time_encoder(torch.cat((times[..., None], phase.sin(), phase.cos()), -1))

    def compress_goal_graph(self, encoded, times):
        """Encode demonstrated future graphs; these are targets, never live inputs."""
        query = self.goal_queries[None].expand(len(encoded["relation"]), -1, -1)
        tokens, _ = self.goal_graph_attention(query, encoded["relation"], encoded["relation"],
                    key_padding_mask=~encoded["edge_mask"], need_weights=False)
        return tokens + self.time_features(times)[:, None]

    def predict_goal_trajectory(self, state, text_tokens, text_mask, times):
        """Predict generic desired relationship tokens from task and current state."""
        b, steps = times.shape
        text = self.task_encoder(text_tokens, text_mask)
        query = (self.goal_queries[None, None] + self.time_features(times)[:, :, None]).expand(-1, -1, -1, -1)
        query = query.reshape(b, steps * self.config.goal_atoms, -1)
        language, _ = self.goal_text_attention(query, text, text, key_padding_mask=~text_mask, need_weights=False)
        context, _ = self.goal_context_attention(query, state["relation"], state["relation"],
                    key_padding_mask=~state["edge_mask"], need_weights=False)
        goal = self.goal_refine(query + language + context)
        return goal.reshape(b, steps, self.config.goal_atoms, -1)

    def score_effect(self, effect, goal_trajectory, goal_mask=None):
        features = self.effect_goal_features(effect, goal_trajectory, goal_mask)
        return F.softplus(self.energy(features).squeeze(-1))

    def effect_goal_features(self, effect, goal_trajectory, goal_mask=None):
        goal = goal_trajectory.flatten(1, 2)
        if goal_mask is not None and goal_mask.ndim == 2:
            goal_mask = goal_mask[:, :, None].expand(-1, -1, self.config.goal_atoms).flatten(1)
        current = effect["state"]["relation"]
        future = effect["future_relation"]
        edge_padding = ~effect["state"]["edge_mask"].bool()
        current_match, _ = self.task_relation_attention(goal, current, current,
                            key_padding_mask=edge_padding, need_weights=False)
        future_match, _ = self.task_relation_attention(goal, future, future,
                            key_padding_mask=edge_padding, need_weights=False)
        relation_change = future_match - current_match
        if goal_mask is None:
            query_weight = torch.ones((*goal.shape[:2], 1), dtype=goal.dtype, device=goal.device)
        else:
            query_weight = goal_mask[..., None].to(goal.dtype)
        denominator = query_weight.sum(1).clamp_min(1.)
        def pool(value):
            return (value * query_weight).sum(1) / denominator
        return torch.cat((pool(current_match), pool(future_match),
                          pool(relation_change), pool(relation_change.square())), -1)

    def score_task_completion(self, effect, goal_trajectory, goal_mask=None):
        """Logit for whether this task-conditioned continuation will finish.

        Positive is higher. This is a learned outcome potential; it is not a
        physical guarantee and must be calibrated on held-out rollouts.
        """
        return self.task_completion_head(self.effect_goal_features(effect, goal_trajectory, goal_mask)).squeeze(-1)

    def score_completion_state(self, state, future_relation, goal_trajectory, goal_mask=None):
        """Same potential head on a measured future graph (training target)."""
        effect = dict(state=state, future_relation=future_relation)
        return self.score_task_completion(effect, goal_trajectory, goal_mask)

    def inverse_primitives(self, batch, state, goal_trajectory):
        """Shared per-actuator mixture; no gripper or embodiment-specific outputs."""
        b, a = batch["actuator_node"].shape
        indices = batch["actuator_node"].long().clamp(0, batch["node_state"].shape[1] - 1)
        local = gather_nodes(state["nodes"], indices)
        descriptors = self.actuator_tokens(batch) + self.effect_time(batch["delta_t"][:, None])[:, None]
        goal = goal_trajectory.flatten(1, 2)
        desired, _ = self.inverse_goal_attention(local, goal, goal, need_weights=False)
        parameters = self.inverse_control(torch.cat((local, descriptors, desired), -1))
        means, log_scales = parameters.chunk(2, -1)
        edge_mask = state["edge_mask"][..., None].to(local.dtype)
        graph = (state["relation"] * edge_mask).sum(1) / edge_mask.sum(1).clamp_min(1)
        logits = self.inverse_mode_logits(torch.cat((graph, goal.mean(1)), -1))
        valid = batch["actuator_mask"][:, None].to(means.dtype)
        return dict(normalized_mean=means.transpose(1, 2) * valid,
                    log_scale=log_scales.clamp(-5., 1.).transpose(1, 2) * valid,
                    mode_logits=logits, actuator_mask=batch["actuator_mask"].bool())

    def forward(self, batch):
        state = self.encode_state(batch)
        effect = self.predict_effect(batch, batch["control"], state)
        goal = batch.get("goal_trajectory")
        if goal is None:
            goal = self.predict_goal_trajectory(state, batch["text_tokens"], batch["text_mask"], batch["goal_times"])
        return dict(**effect, goal_trajectory=goal, energy=self.score_effect(effect, goal, batch.get("goal_mask")),
                    task_completion_logit=self.score_task_completion(effect, goal, batch.get("goal_mask")),
                    inverse=self.inverse_primitives(batch, state, goal))

    def identity(self):
        return dict(schema=SCHEMA, config=asdict(self.config), parameters=sum(p.numel() for p in self.parameters()),
                    node_abi=27, actuator_abi=40, variable_nodes=True, variable_actuators=True,
                    absolute_pose_enters_node_mlp=False, pickup_specific_heads=False,
                    inverse_control="shared numerical per-actuator joint mixture; exact protocol controls only",
                    inverse_control_transform="asinh(range-normalized raw motor command), unbounded mixture means; sinh decode",
                    goal_encoder_masks_future_motor_intent=True,
                    inverse_observes_primitive_duration=True,
                    instruction_grounding="optional supplied object/target bindings, never finger/body-role labels",
                    task_completion="task-trajectory tokens cross-attend to current and candidate future relationship vectors; a shared potential head scores their task-conditioned change, trained with explicit outcome BCE and matched same-initial-state success/failure ranking",
                    task_completion_limitations="trajectory outcomes are noisy Monte Carlo returns; current dataset has sparse cross-source task families and physical held-out-body/task tests remain required",
                    limitations="A shared representation architecture is not evidence of universal skill transfer; physical held-out-body/task tests remain required.")