diffvid 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,301 @@
1
+ # Copyright 2024 DeepMind Technologies Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Pytorch model utilities."""
17
+ import math
18
+ from typing import Any, Sequence, Union, Tuple
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn.functional as F
22
+
23
+
24
+ def bilinear(x: torch.Tensor, resolution: Tuple[int, int]) -> torch.Tensor:
25
+ """Resizes a 5D tensor using bilinear interpolation.
26
+
27
+ Args:
28
+ x: A 5D tensor of shape (B, T, W, H, C) where B is batch size, T is
29
+ time, W is width, H is height, and C is the number of channels.
30
+ resolution: The target resolution as a tuple (new_width, new_height).
31
+
32
+ Returns:
33
+ The resized tensor.
34
+ """
35
+ b, t, h, w, c = x.size()
36
+ x = x.permute(0, 1, 4, 2, 3).reshape(b, t * c, h, w)
37
+ x = F.interpolate(x, size=resolution, mode='bilinear', align_corners=False)
38
+ b, _, h, w = x.size()
39
+ x = x.reshape(b, t, c, h, w).permute(0, 1, 3, 4, 2)
40
+ return x
41
+
42
+
43
+ def map_coordinates_3d(
44
+ feats: torch.Tensor, coordinates: torch.Tensor
45
+ ) -> torch.Tensor:
46
+ """Maps 3D coordinates to corresponding features using bilinear interpolation.
47
+
48
+ Args:
49
+ feats: A 5D tensor of features with shape (B, W, H, D, C), where B is batch
50
+ size, W is width, H is height, D is depth, and C is the number of
51
+ channels.
52
+ coordinates: A 3D tensor of coordinates with shape (B, N, 3), where N is the
53
+ number of coordinates and the last dimension represents (W, H, D)
54
+ coordinates.
55
+
56
+ Returns:
57
+ The mapped features tensor.
58
+ """
59
+ x = feats.permute(0, 4, 1, 2, 3)
60
+ y = coordinates[:, :, None, None, :].float().clone()
61
+ y[..., 0] = y[..., 0] + 0.5
62
+ y = 2 * (y / torch.tensor(x.shape[2:], device=y.device)) - 1
63
+ y = torch.flip(y, dims=(-1,))
64
+ out = (
65
+ F.grid_sample(
66
+ x, y, mode='bilinear', align_corners=False, padding_mode='border'
67
+ )
68
+ .squeeze(dim=(3, 4))
69
+ .permute(0, 2, 1)
70
+ )
71
+ return out
72
+
73
+
74
+ def map_coordinates_2d(
75
+ feats: torch.Tensor, coordinates: torch.Tensor
76
+ ) -> torch.Tensor:
77
+ """Maps 2D coordinates to feature maps using bilinear interpolation.
78
+
79
+ The function performs bilinear interpolation on the feature maps (`feats`)
80
+ at the specified `coordinates`. The coordinates are normalized between
81
+ -1 and 1 The result is a tensor of sampled features corresponding
82
+ to these coordinates.
83
+
84
+ Args:
85
+ feats (Tensor): A 5D tensor of shape (N, T, H, W, C) representing feature
86
+ maps, where N is the batch size, T is the number of frames, H and W are
87
+ height and width, and C is the number of channels.
88
+ coordinates (Tensor): A 5D tensor of shape (N, P, T, S, XY) representing
89
+ coordinates, where N is the batch size, P is the number of points, T is
90
+ the number of frames, S is the number of samples, and XY represents the 2D
91
+ coordinates.
92
+
93
+ Returns:
94
+ Tensor: A 5D tensor of the sampled features corresponding to the
95
+ given coordinates, of shape (N, P, T, S, C).
96
+ """
97
+ n, t, h, w, c = feats.shape
98
+ x = feats.permute(0, 1, 4, 2, 3).view(n * t, c, h, w)
99
+
100
+ n, p, t, s, xy = coordinates.shape
101
+ y = coordinates.permute(0, 2, 1, 3, 4).reshape(n * t, p, s, xy)
102
+ y = 2 * (y / torch.tensor([h, w], device=feats.device)) - 1
103
+ y = torch.flip(y, dims=(-1,)).float()
104
+
105
+ out = F.grid_sample(
106
+ x, y, mode='bilinear', align_corners=False, padding_mode='zeros'
107
+ )
108
+ _, c, _, _ = out.shape
109
+ out = out.permute(0, 2, 3, 1).view(n, t, p, s, c).permute(0, 2, 1, 3, 4)
110
+
111
+ return out
112
+
113
+
114
+ def soft_argmax_heatmap_batched(softmax_val, threshold=5):
115
+ """Test if two image resolutions are the same."""
116
+ b, h, w, d1, d2 = softmax_val.shape
117
+ y, x = torch.meshgrid(
118
+ torch.arange(d1, device=softmax_val.device),
119
+ torch.arange(d2, device=softmax_val.device),
120
+ indexing='ij',
121
+ )
122
+ coords = torch.stack([x + 0.5, y + 0.5], dim=-1).to(softmax_val.device)
123
+ softmax_val_flat = softmax_val.reshape(b, h, w, -1)
124
+ argmax_pos = torch.argmax(softmax_val_flat, dim=-1)
125
+
126
+ pos = coords.reshape(-1, 2)[argmax_pos]
127
+ valid = (
128
+ torch.sum(
129
+ torch.square(
130
+ coords[None, None, None, :, :, :] - pos[:, :, :, None, None, :]
131
+ ),
132
+ dim=-1,
133
+ keepdims=True,
134
+ )
135
+ < threshold**2
136
+ )
137
+
138
+ weighted_sum = torch.sum(
139
+ coords[None, None, None, :, :, :]
140
+ * valid
141
+ * softmax_val[:, :, :, :, :, None],
142
+ dim=(3, 4),
143
+ )
144
+ sum_of_weights = torch.maximum(
145
+ torch.sum(valid * softmax_val[:, :, :, :, :, None], dim=(3, 4)),
146
+ torch.tensor(1e-12, device=softmax_val.device),
147
+ )
148
+ return weighted_sum / sum_of_weights
149
+
150
+
151
+ def heatmaps_to_points(
152
+ all_pairs_softmax,
153
+ image_shape,
154
+ threshold=5,
155
+ query_points=None,
156
+ ):
157
+ """Convert heatmaps to points using soft argmax."""
158
+
159
+ out_points = soft_argmax_heatmap_batched(all_pairs_softmax, threshold)
160
+ feature_grid_shape = all_pairs_softmax.shape[1:]
161
+ # Note: out_points is now [x, y]; we need to divide by [width, height].
162
+ # image_shape[3] is width and image_shape[2] is height.
163
+ out_points = convert_grid_coordinates(
164
+ out_points,
165
+ feature_grid_shape[3:1:-1],
166
+ image_shape[3:1:-1],
167
+ )
168
+ assert feature_grid_shape[1] == image_shape[1]
169
+ if query_points is not None:
170
+ # The [..., 0:1] is because we only care about the frame index.
171
+ query_frame = convert_grid_coordinates(
172
+ query_points.detach(),
173
+ image_shape[1:4],
174
+ feature_grid_shape[1:4],
175
+ coordinate_format='tyx',
176
+ )[..., 0:1]
177
+
178
+ query_frame = torch.round(query_frame)
179
+ frame_indices = torch.arange(image_shape[1], device=query_frame.device)[
180
+ None, None, :
181
+ ]
182
+ is_query_point = query_frame == frame_indices
183
+
184
+ is_query_point = is_query_point[:, :, :, None]
185
+ out_points = (
186
+ out_points * ~is_query_point
187
+ + torch.flip(query_points[:, :, None], dims=(-1,))[..., 0:2]
188
+ * is_query_point
189
+ )
190
+
191
+ return out_points
192
+
193
+
194
+ def is_same_res(r1, r2):
195
+ """Test if two image resolutions are the same."""
196
+ return all([x == y for x, y in zip(r1, r2)])
197
+
198
+
199
+ def convert_grid_coordinates(
200
+ coords: torch.Tensor,
201
+ input_grid_size: Sequence[int],
202
+ output_grid_size: Sequence[int],
203
+ coordinate_format: str = 'xy',
204
+ ) -> torch.Tensor:
205
+ """Convert grid coordinates to correct format."""
206
+ if isinstance(input_grid_size, tuple):
207
+ input_grid_size = torch.tensor(input_grid_size, device=coords.device)
208
+ if isinstance(output_grid_size, tuple):
209
+ output_grid_size = torch.tensor(output_grid_size, device=coords.device)
210
+
211
+ if coordinate_format == 'xy':
212
+ if input_grid_size.shape[0] != 2 or output_grid_size.shape[0] != 2:
213
+ raise ValueError(
214
+ 'If coordinate_format is xy, the shapes must be length 2.'
215
+ )
216
+ elif coordinate_format == 'tyx':
217
+ if input_grid_size.shape[0] != 3 or output_grid_size.shape[0] != 3:
218
+ raise ValueError(
219
+ 'If coordinate_format is tyx, the shapes must be length 3.'
220
+ )
221
+ if input_grid_size[0] != output_grid_size[0]:
222
+ raise ValueError('converting frame count is not supported.')
223
+ else:
224
+ raise ValueError('Recognized coordinate formats are xy and tyx.')
225
+
226
+ position_in_grid = coords
227
+ position_in_grid = position_in_grid * output_grid_size / input_grid_size
228
+
229
+ return position_in_grid
230
+
231
+
232
+ def generate_default_resolutions(full_size, train_size, num_levels=None):
233
+ """Generate a list of logarithmically-spaced resolutions.
234
+
235
+ Generated resolutions are between train_size and full_size, inclusive, with
236
+ num_levels different resolutions total. Useful for generating the input to
237
+ refinement_resolutions in PIPs.
238
+
239
+ Args:
240
+ full_size: 2-tuple of ints. The full image size desired.
241
+ train_size: 2-tuple of ints. The smallest refinement level. Should
242
+ typically match the training resolution, which is (256, 256) for TAPIR.
243
+ num_levels: number of levels. Typically each resolution should be less than
244
+ twice the size of prior resolutions.
245
+
246
+ Returns:
247
+ A list of resolutions.
248
+ """
249
+ if all([x == y for x, y in zip(train_size, full_size)]):
250
+ return [train_size]
251
+
252
+ if num_levels is None:
253
+ size_ratio = np.array(full_size) / np.array(train_size)
254
+ num_levels = int(np.ceil(np.max(np.log2(size_ratio))) + 1)
255
+
256
+ if num_levels <= 1:
257
+ return [train_size]
258
+
259
+ h, w = full_size[0:2]
260
+ if h % 8 != 0 or w % 8 != 0:
261
+ print(
262
+ 'Warning: output size is not a multiple of 8. Final layer '
263
+ + 'will round size down.'
264
+ )
265
+ ll_h, ll_w = train_size[0:2]
266
+
267
+ sizes = []
268
+ for i in range(num_levels):
269
+ size = (
270
+ int(round((ll_h * (h / ll_h) ** (i / (num_levels - 1))) // 8)) * 8,
271
+ int(round((ll_w * (w / ll_w) ** (i / (num_levels - 1))) // 8)) * 8,
272
+ )
273
+ sizes.append(size)
274
+ return sizes
275
+
276
+
277
+ class Conv2dSamePadding(torch.nn.Conv2d):
278
+
279
+ def calc_same_pad(self, i: int, k: int, s: int, d: int) -> int:
280
+ return max((math.ceil(i / s) - 1) * s + (k - 1) * d + 1 - i, 0)
281
+
282
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
283
+ ih, iw = x.size()[-2:]
284
+
285
+ pad_h = self.calc_same_pad(i=ih, k=self.kernel_size[0], s=self.stride[0], d=self.dilation[0])
286
+ pad_w = self.calc_same_pad(i=iw, k=self.kernel_size[1], s=self.stride[1], d=self.dilation[1])
287
+
288
+ if pad_h > 0 or pad_w > 0:
289
+ x = F.pad(
290
+ x, [pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2]
291
+ )
292
+ return F.conv2d(
293
+ x,
294
+ self.weight,
295
+ self.bias,
296
+ self.stride,
297
+ # self.padding,
298
+ 0,
299
+ self.dilation,
300
+ self.groups,
301
+ )
@@ -0,0 +1,324 @@
1
+ """Arm channel: compare where the robot arm went and when.
2
+
3
+ Uses LeRobot joint states (`observation.state`) when both recordings provide them; otherwise compares
4
+ the DTW-aligned arm region (`ra`, `rb` from `robot_cover`) using DINOv2 + CIE Lab appearance (`pa`, `pb`,
5
+ `la`, `lb`) gated by a clean, reference-only physical check:
6
+
7
+ 1. Measure `self_world_change(A)`: how much the robot-free scene changed from start to end of A.
8
+ 2. When A leaves no lasting change on the world (`self_world_change(A) < ARM_STATIC_WORLD_THR`, e.g.
9
+ button pressing / probing / inspection), the arm trajectory IS the task — compare the arm along the
10
+ DTW path (`ARM_MID_THR` for >= 0.3 s, or `ARM_END_THR` at the end) to catch wrong button presses and
11
+ wrong end poses with zero false items on normal runs.
12
+ 3. On world-changing tasks (`self_world_change(A) >= ARM_STATIC_WORLD_THR`), mid-run arm paths naturally
13
+ vary when grasping objects; only report an `ARM DIFF` when the arm is stuck far out of A's end pose
14
+ (`ARM_STUCK_END_THR` + footprint divergence).
15
+ """
16
+ from pathlib import Path
17
+
18
+ import cv2
19
+ import numpy as np
20
+
21
+ from .core import _combined_patch_diff, _hot_region, _medfilt1d, _robot_cells
22
+
23
+ ARM_STATIC_WORLD_THR = 0.22 # self_world_change(A) below this -> arm-only task (e.g. buttons)
24
+ ARM_MASK_THR = 0.25 # cell belongs to arm above this occupancy
25
+ ARM_MIN_CELLS = 6 # both runs must clearly show the arm (>= 6 cells on 16x16)
26
+ ARM_MID_THR = 0.68 # arm-only task: sustained mid-run arm divergence threshold
27
+ ARM_END_THR = 0.45 # arm-only task: end arm-pose divergence threshold
28
+ ARM_STUCK_END_THR = 0.78 # world-changing task: stuck-arm end divergence threshold
29
+ ARM_STUCK_OUT_THR = 0.35 # world-changing task: arm cells outside A's dilated end arm
30
+ ARM_MREF_PAIR_THR = 0.20 # multi-ref (--also): max end-pose disagreement among good runs to trust home-park check
31
+ ARM_MREF_HOME_THR = 0.40 # multi-ref (--also): good runs must return near their own start pose
32
+ ARM_MREF_STUCK_THR = 0.38 # multi-ref (--also): B end-arm divergence vs all good runs -> stuck arm
33
+ ARM_JOINT_THR = 0.45 # normalized joint-space L2 divergence threshold (LeRobot parquet)
34
+ ARM_TIME_TOL_STEPS = 4 # local temporal tolerance for joint-state comparison
35
+
36
+
37
+ def _load_lerobot_joints(spec, fps=10):
38
+ """If `spec` is a LeRobot v3 folder#ep with a data parquet containing `observation.state`, return
39
+ (N, D) float32 resampled to `fps`; otherwise None."""
40
+ if not spec or "#" not in str(spec):
41
+ return None
42
+ root_s, ep_s = str(spec).rsplit("#", 1)
43
+ root = Path(root_s)
44
+ meta = root / "meta/episodes/chunk-000/file-000.parquet"
45
+ data = root / "data/chunk-000/file-000.parquet"
46
+ if not meta.exists() or not data.exists():
47
+ return None
48
+ try:
49
+ import json
50
+ import pandas as pd
51
+ info = json.loads((root / "meta/info.json").read_text(encoding="utf-8"))
52
+ src_fps = info.get("fps", 30)
53
+ ep = int(ep_s)
54
+ df = pd.read_parquet(data, columns=["episode_index", "observation.state"])
55
+ sub = df[df["episode_index"] == ep]["observation.state"].tolist()
56
+ if not sub:
57
+ return None
58
+ arr = np.asarray(sub, dtype=np.float32)
59
+ step = max(1, round(src_fps / fps))
60
+ return arr[::step]
61
+ except Exception:
62
+ return None
63
+
64
+
65
+ def _spans_from_curve(hot, min_len, gap_merge=3):
66
+ spans = []
67
+ for idx in np.flatnonzero(hot):
68
+ idx = int(idx)
69
+ if spans and idx - spans[-1][1] <= gap_merge:
70
+ spans[-1][1] = idx
71
+ else:
72
+ spans.append([idx, idx])
73
+ return [(s0, s1) for s0, s1 in spans if s1 - s0 + 1 >= min_len]
74
+
75
+
76
+ def _self_world_change(pa_g, la, ra):
77
+ """How much the robot-free scene changed from start to end of reference run A (top-4 cells mean)."""
78
+ k = min(3, len(pa_g))
79
+ if k < 1:
80
+ return 1.0
81
+ la0 = la[:k] if la is not None else None
82
+ la1 = la[-k:] if la is not None else None
83
+ M_se = _combined_patch_diff(pa_g[:k], pa_g[-k:], la0, la1, rad=1)
84
+ skip = _robot_cells(np.maximum(ra[:k], ra[-k:]))
85
+ M_se[skip] = 0.0
86
+ m_med = np.median(M_se, axis=0)
87
+ return float(np.sort(m_med.ravel())[-min(4, m_med.size):].mean())
88
+
89
+
90
+ def _end_out_frac(ma, mb):
91
+ """Bidirectional fraction of arm cells falling outside the other arm (+1-cell dilation)."""
92
+ na, nb = int(ma.sum()), int(mb.sum())
93
+ if na < ARM_MIN_CELLS or nb < ARM_MIN_CELLS:
94
+ return 0.0
95
+ kern = np.ones((3, 3), np.uint8)
96
+ da = cv2.dilate(ma.astype(np.uint8), kern) > 0
97
+ db = cv2.dilate(mb.astype(np.uint8), kern) > 0
98
+ return max(float((mb & ~da).sum()) / nb, float((ma & ~db).sum()) / na)
99
+
100
+
101
+ def _multiref_stuck_end(ra, rb, extra_ra, path, sa, sb, fps):
102
+ """Safe multi-ref (--also) stuck final arm pose detector.
103
+
104
+ Only fires when ALL good runs (A + --also) consistently park at the same home pose at the end
105
+ (max pairwise end divergence <= ARM_MREF_PAIR_THR and each returns near its own start pose),
106
+ while B finishes with its arm far outside every good run's end pose (>= ARM_MREF_STUCK_THR).
107
+ Automatically skips tasks where good runs end in varying poses (0/49 quiet FPs across 8 tasks).
108
+ """
109
+ if ra is None or rb is None or not extra_ra:
110
+ return []
111
+ ra_list = [r for r in [ra] + list(extra_ra) if r is not None and len(r) >= 4]
112
+ if len(ra_list) < 2 or len(rb) < 4:
113
+ return []
114
+ end_masks = [np.median(r[-min(5, len(r)):], axis=0) >= ARM_MASK_THR for r in ra_list]
115
+ if any(int(m.sum()) < ARM_MIN_CELLS for m in end_masks):
116
+ return []
117
+ home_outs = [
118
+ _end_out_frac(np.median(r[:min(5, len(r))], axis=0) >= ARM_MASK_THR, m1)
119
+ for r, m1 in zip(ra_list, end_masks)
120
+ ]
121
+ if max(home_outs) > ARM_MREF_HOME_THR:
122
+ return []
123
+ pair_end = max(
124
+ _end_out_frac(end_masks[i], end_masks[j])
125
+ for i in range(len(end_masks)) for j in range(i + 1, len(end_masks))
126
+ )
127
+ if pair_end > ARM_MREF_PAIR_THR:
128
+ return []
129
+ mb1 = np.median(rb[-min(5, len(rb)):], axis=0) >= ARM_MASK_THR
130
+ if int(mb1.sum()) < ARM_MIN_CELLS:
131
+ return []
132
+ min_vs_g = min(_end_out_frac(mg, mb1) for mg in end_masks)
133
+ if min_vs_g < ARM_MREF_STUCK_THR:
134
+ return []
135
+
136
+ S = len(path)
137
+ ia = np.array([i + sa for i, _ in path], dtype=int)
138
+ jb = np.array([j + sb for _, j in path], dtype=int)
139
+ tail = max(2, min(S, fps // 2))
140
+ # Find when B's arm stopped matching the good end pose near the end (walk back while still out of home)
141
+ ref_end = end_masks[0]
142
+ s0 = max(0, S - tail)
143
+ while s0 > 0 and jb[s0 - 1] < len(rb) and _end_out_frac(ref_end, rb[jb[s0 - 1]] >= ARM_MASK_THR) >= ARM_MREF_STUCK_THR * 0.85:
144
+ # Stop walking back once A itself wasn't yet parked at home (only count time after A returned home)
145
+ if ia[s0 - 1] < len(ra) and _end_out_frac(ref_end, ra[ia[s0 - 1]] >= ARM_MASK_THR) > 0.25:
146
+ break
147
+ s0 -= 1
148
+ kern = np.ones((3, 3), np.uint8)
149
+ extra_cells = mb1 & ~(cv2.dilate(ref_end.astype(np.uint8), kern) > 0)
150
+ use_m = extra_cells if int(extra_cells.sum()) >= 3 else mb1
151
+ ys, xs = np.nonzero(use_m)
152
+ G = float(mb1.shape[0])
153
+ box = [round(float(xs.min()) / G, 4), round(float(ys.min()) / G, 4),
154
+ round(float(xs.max() + 1) / G, 4), round(float(ys.max() + 1) / G, 4)]
155
+ return [dict(
156
+ kind="ARM DIFF",
157
+ a=[int(ia[s0] - sa), int(ia[-1] - sa)],
158
+ b=[int(jb[s0] - sb), int(jb[-1] - sb)],
159
+ step=int(s0), end_step=S - 1, peak_step=S - 1,
160
+ score=round(float(min_vs_g), 2), thr=ARM_MREF_STUCK_THR,
161
+ box=box, frames=int(S - s0), info=False, stuck_end=True,
162
+ detail=(f"arm ended stuck out of home pose (from B {jb[s0] / fps:.1f} s to end; "
163
+ f"divergence {min_vs_g:.2f} vs {len(ra_list)} good runs)"),
164
+ )]
165
+
166
+
167
+ def compare_arms(fa, fb, res, ra=None, rb=None, pa=None, pb=None, la=None, lb=None,
168
+ spec_a=None, spec_b=None, has_end_diff=False, joints_only=False, extra_ra=None):
169
+ """Compare robot arm trajectories along DTW path `res['path']`.
170
+
171
+ Uses LeRobot joint states if both runs provide them; otherwise checks multi-ref (--also) end-arm
172
+ home consensus when `extra_ra` is given, and (when `joints_only=False`) DINOv2+Lab appearance
173
+ inside the robot arm mask (`ra`, `rb`), gated on `self_world_change(A)`.
174
+ """
175
+ fps = res.get("fps", 10)
176
+ path = res.get("path") or []
177
+ if not path:
178
+ return []
179
+ sa, sb = res["trim_a"][0], res["trim_b"][0]
180
+ ia = np.array([i + sa for i, _ in path], dtype=int)
181
+ jb = np.array([j + sb for _, j in path], dtype=int)
182
+ S = len(path)
183
+
184
+ # 1) Joint-state path when both LeRobot parquets exist
185
+ qa = _load_lerobot_joints(spec_a, fps=fps)
186
+ qb = _load_lerobot_joints(spec_b, fps=fps)
187
+ if qa is not None and qb is not None and len(qa) > ia.max() and len(qb) > jb.max():
188
+ scale = np.maximum(np.std(np.concatenate([qa, qb], axis=0), axis=0), 0.15)
189
+ d_joint = np.empty(S, np.float32)
190
+ for s in range(S):
191
+ t_lo, t_hi = max(0, s - ARM_TIME_TOL_STEPS), min(S, s + ARM_TIME_TOL_STEPS + 1)
192
+ diffs = np.linalg.norm((qb[jb[s]] - qa[ia[t_lo:t_hi]]) / scale, axis=-1) / np.sqrt(qa.shape[1])
193
+ d_joint[s] = float(diffs.min())
194
+ sm = _medfilt1d(d_joint, k=min(5, S if S % 2 == 1 else max(1, S - 1)))
195
+ min_len = max(3, int(round(1.0 * fps)))
196
+ items = []
197
+ for s0, s1 in _spans_from_curve(sm >= ARM_JOINT_THR, min_len=min_len):
198
+ pk = int(s0 + np.argmax(sm[s0:s1 + 1]))
199
+ box = None
200
+ if rb is not None and jb[pk] < len(rb):
201
+ m = rb[jb[pk]] >= ARM_MASK_THR
202
+ if m.any():
203
+ ys, xs = np.nonzero(m)
204
+ G = float(m.shape[0])
205
+ box = [round(float(xs.min()) / G, 4), round(float(ys.min()) / G, 4),
206
+ round(float(xs.max() + 1) / G, 4), round(float(ys.max() + 1) / G, 4)]
207
+ items.append(dict(
208
+ kind="ARM DIFF",
209
+ a=[int(ia[s0] - sa), int(ia[s1] - sa)],
210
+ b=[int(jb[s0] - sb), int(jb[s1] - sb)],
211
+ step=s0, end_step=s1, peak_step=pk,
212
+ score=round(float(sm[pk]), 2), thr=ARM_JOINT_THR,
213
+ box=box, frames=int(s1 - s0 + 1), info=False,
214
+ detail=f"arm joint path diverges at B {jb[s0]/fps:.1f}-{jb[s1]/fps:.1f} s (z={sm[pk]:.2f})",
215
+ ))
216
+ return items
217
+
218
+ # 2) Multi-ref (--also) stuck final arm pose check (safe when all good runs consistently park at home)
219
+ mref_items = _multiref_stuck_end(ra, rb, extra_ra, path, sa, sb, fps)
220
+
221
+ # 3) Visual arm-mask path (opt-in; requires ra, rb and DINOv2 patch tokens pa, pb)
222
+ if joints_only or ra is None or rb is None or pa is None or pb is None:
223
+ return mref_items
224
+ G = int(round(pa.shape[1] ** 0.5))
225
+ pa_g = pa.reshape(len(pa), G, G, -1).astype(np.float32)
226
+ pb_g = pb.reshape(len(pb), G, G, -1).astype(np.float32)
227
+
228
+ arm_only_task = _self_world_change(pa_g, la, ra) < ARM_STATIC_WORLD_THR
229
+ tail = max(1, min(S, max(2, fps // 2)))
230
+ k_top = min(4, G * G)
231
+ k0 = min(3, len(pa_g), len(pb_g))
232
+ La0 = la[:k0] if la is not None else None
233
+ Lb0 = lb[:k0] if lb is not None else None
234
+
235
+ # Fast path for world-changing tasks: only check the last `tail` frames (0.01s vs 2.5s!)
236
+ if not arm_only_task:
237
+ if mref_items:
238
+ return mref_items
239
+ if has_end_diff:
240
+ return []
241
+ arm_a_t = ra[ia[-tail:]] >= ARM_MASK_THR
242
+ arm_b_t = rb[jb[-tail:]] >= ARM_MASK_THR
243
+ both_t = (arm_a_t.reshape(tail, -1).sum(1) >= ARM_MIN_CELLS) & (arm_b_t.reshape(tail, -1).sum(1) >= ARM_MIN_CELLS)
244
+ if not both_t.any():
245
+ return []
246
+ end_out = _end_out_frac(arm_a_t[-1], arm_b_t[-1])
247
+ if end_out < ARM_STUCK_OUT_THR:
248
+ return []
249
+ M0 = np.median(_combined_patch_diff(pa_g[:k0], pb_g[:k0], La0, Lb0, rad=1), axis=0, keepdims=True)
250
+ La_t = la[ia[-tail:]] if la is not None else None
251
+ Lb_t = lb[jb[-tail:]] if lb is not None else None
252
+ Mt = np.clip(_combined_patch_diff(pa_g[ia[-tail:]], pb_g[jb[-tail:]], La_t, Lb_t, rad=1) - M0, 0.0, None)
253
+ ac_t = _robot_cells(np.maximum(ra[ia[-tail:]], rb[jb[-tail:]]))
254
+ Mt = np.where(ac_t & both_t[:, None, None], Mt, 0.0)
255
+ end_map = np.median(Mt, axis=0)
256
+ end_score = float(np.sort(end_map.ravel())[-k_top:].mean())
257
+ if end_score < ARM_STUCK_END_THR:
258
+ return []
259
+ box, _ = _hot_region(end_map, rel=0.55, floor=0.30)
260
+ s0 = max(0, S - tail)
261
+ return [dict(
262
+ kind="ARM DIFF",
263
+ a=[int(ia[s0] - sa), int(ia[-1] - sa)],
264
+ b=[int(jb[s0] - sb), int(jb[-1] - sb)],
265
+ step=s0, end_step=S - 1, peak_step=S - 1,
266
+ score=round(end_score, 2), thr=ARM_STUCK_END_THR,
267
+ box=box, frames=int(S - s0), info=False,
268
+ detail=f"arm stuck in a different end pose (score {end_score:.2f})",
269
+ )]
270
+
271
+ # Arm-only task (e.g. buttons): full-path arm trajectory comparison
272
+ M0 = np.median(_combined_patch_diff(pa_g[:k0], pb_g[:k0], La0, Lb0, rad=1), axis=0, keepdims=True)
273
+ La = la[ia] if la is not None else None
274
+ Lb = lb[jb] if lb is not None else None
275
+ M = _combined_patch_diff(pa_g[ia], pb_g[jb], La, Lb, rad=1)
276
+ M_new = np.clip(M - M0, 0.0, None)
277
+
278
+ arm_cells = _robot_cells(np.maximum(ra[ia], rb[jb]))
279
+ arm_a_bin = ra[ia] >= ARM_MASK_THR
280
+ arm_b_bin = rb[jb] >= ARM_MASK_THR
281
+ both_arm = (arm_a_bin.reshape(S, -1).sum(1) >= ARM_MIN_CELLS) & (arm_b_bin.reshape(S, -1).sum(1) >= ARM_MIN_CELLS)
282
+ M_arm = np.where(arm_cells & both_arm[:, None, None], M_new, 0.0)
283
+
284
+ curve = np.sort(M_arm.reshape(S, -1), axis=1)[:, -k_top:].mean(1).astype(np.float32)
285
+ end_map = np.median(M_arm[-tail:], axis=0)
286
+ end_score = float(np.sort(end_map.ravel())[-k_top:].mean())
287
+ items = []
288
+ end_s0 = S
289
+ if end_score >= ARM_END_THR:
290
+ box, comp = _hot_region(end_map, rel=0.55, floor=0.30)
291
+ vals = M_arm[:, comp]
292
+ reg_c = np.sort(vals, axis=1)[:, -min(4, vals.shape[1]):].mean(1)
293
+ reg_sm = _medfilt1d(reg_c, k=min(5, S if S % 2 == 1 else max(1, S - 1)))
294
+ below = np.flatnonzero(reg_sm < 0.70 * ARM_END_THR)
295
+ s0 = min(int(below[-1] + 1) if len(below) else 0, S - 1)
296
+ end_s0 = s0
297
+ items.append(dict(
298
+ kind="ARM DIFF",
299
+ a=[int(ia[s0] - sa), int(ia[-1] - sa)],
300
+ b=[int(jb[s0] - sb), int(jb[-1] - sb)],
301
+ step=s0, end_step=S - 1, peak_step=S - 1,
302
+ score=round(end_score, 2), thr=ARM_END_THR,
303
+ box=box, frames=int(S - s0), info=False,
304
+ detail=f"arm ends in a different pose from B {jb[s0]/fps:.1f} s to end (score {end_score:.2f})",
305
+ ))
306
+
307
+ if end_s0 > 2:
308
+ c_sm = _medfilt1d(curve[:end_s0], k=min(3, end_s0 if end_s0 % 2 == 1 else max(1, end_s0 - 1)))
309
+ min_len = max(3, int(round(0.3 * fps)))
310
+ for s0, s1 in _spans_from_curve(c_sm >= ARM_MID_THR, min_len=min_len, gap_merge=max(3, fps // 2)):
311
+ pk = int(s0 + np.argmax(curve[s0:s1 + 1]))
312
+ span_map = np.median(M_arm[s0:s1 + 1], axis=0)
313
+ box, _ = _hot_region(span_map if span_map.max() >= 0.30 else M_arm[pk], rel=0.55, floor=0.30)
314
+ items.append(dict(
315
+ kind="ARM DIFF",
316
+ a=[int(ia[s0] - sa), int(ia[s1] - sa)],
317
+ b=[int(jb[s0] - sb), int(jb[s1] - sb)],
318
+ step=s0, end_step=s1, peak_step=pk,
319
+ score=round(float(curve[pk]), 2), thr=ARM_MID_THR,
320
+ box=box, frames=int(s1 - s0 + 1), info=False,
321
+ detail=f"arm trajectory diverges at B {jb[s0]/fps:.1f}-{jb[s1]/fps:.1f} s (peak {curve[pk]:.2f})",
322
+ ))
323
+
324
+ return items