File size: 24,349 Bytes
ae1ed83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
#!/usr/bin/env python3
"""Forward/backward and spec-v1.1 validation tests for TRACE-VLA.

Run from the project root:  python tests/test_modules.py
Uses fake tensors for the module tests, the real frozen TIPSv2 for
the ANCHOR integration test, and a synthetic frame-index-encoded
feature cache for the data tests (spec v1.1 section 24: short videos,
invalid frames, overlapping windows, temporal order, intermediate
residual sequences, cyclic motion, demo data leakage, future
observation leakage, ECHO target construction, episode boundaries).
Prints PASS/FAIL per check and exits nonzero on any failure.
"""
import inspect
import sys
from pathlib import Path

import torch

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from trace_vla.anchor import AnchorHeads, TipsAnchor, pool_patches_2x2
from trace_vla.config import TraceConfig
from trace_vla.data import SmokeData, SupportQueryData
from trace_vla.delta import Delta, build_windows, skill_alignment_loss, \
    window_residuals
from trace_vla.echo import Echo, echo_loss
from trace_vla.flux import Flux, flux_loss
from trace_vla.model import TraceVLA
from trace_vla.nexus import Nexus
from trace_vla.pulse import Pulse
from trace_vla.sync import Sync

torch.manual_seed(0)
CFG = TraceConfig()
RESULTS = []


def check(name, fn):
    try:
        fn()
        RESULTS.append((name, "PASS", ""))
        print(f"PASS  {name}")
    except Exception as e:  # noqa: BLE001
        RESULTS.append((name, "FAIL", f"{type(e).__name__}: {e}"))
        print(f"FAIL  {name}: {type(e).__name__}: {e}")


def has_grad(module):
    return any(p.grad is not None and torch.isfinite(p.grad).all()
               for p in module.parameters() if p.requires_grad)


# ---------------------------------------------------------------- ANCHOR
def t_pool():
    x = torch.arange(256, dtype=torch.float32).view(1, 256, 1).expand(1, 256, 768)
    y = pool_patches_2x2(x.clone())
    assert y.shape == (1, 64, 768), y.shape
    # pooled[0,0] = mean of patches (0,1,16,17) = 8.5
    assert abs(y[0, 0, 0].item() - 8.5) < 1e-5
    x2 = torch.rand(2, 256, 768, requires_grad=True)
    pool_patches_2x2(x2).sum().backward()
    assert x2.grad is not None and torch.isfinite(x2.grad).all()


def t_anchor_real():
    anchor = TipsAnchor(CFG.backbone_id)
    imgs = torch.rand(2, 3, 256, 256)
    pooled = anchor.encode_patches(imgs)
    assert pooled.shape == (2, 64, 768), pooled.shape
    emb = anchor.encode_text(["pick up the milk", "open the drawer"])
    assert emb.shape == (2, 768), emb.shape
    assert not any(p.requires_grad for p in anchor.parameters())


def t_heads():
    heads = AnchorHeads(CFG)
    pooled = torch.rand(2, 2, 64, 768)
    live = heads.project_live(pooled)
    assert live.shape == (2, 128, 512)
    txt = heads.project_text(torch.rand(2, 768), 2, "cpu")
    assert txt.shape == (2, 1, 512)
    null = heads.project_text(None, 2, "cpu")
    assert null.shape == (2, 1, 512)
    st = heads.project_state(torch.rand(2, 8))
    assert st.shape == (2, 1, 512)
    hist = heads.build_history(
        torch.rand(2, 3, 2, 64, 768), torch.rand(2, 3, 8),
        torch.rand(2, 3, 7), torch.tensor([[0.4, 0.8, 1.2]] * 2),
        torch.tensor([[True, True, False]] * 2))
    assert hist.shape == (2, 3, 512)
    assert torch.all(hist[:, 2] == 0)
    (live.sum() + txt.sum() + st.sum() + hist.sum()).backward()
    assert has_grad(heads)


# ---------------------------------------------------------------- config
def t_config_v11():
    c = TraceConfig()
    assert c.window_len == 8 and c.window_stride == 4
    assert c.max_windows == 16
    assert tuple(c.residual_offsets) == (1, 4)
    assert c.lambda_flux == 1.0 and c.lambda_echo == 0.1
    assert c.lambda_delta == 0.0 and c.lambda_pulse == 0.0
    assert c.use_echo_loss and not c.use_delta_loss and not c.use_pulse_loss
    assert c.effect_horizon == 4 and c.euler_steps == 4


# ---------------------------------------------------------------- DELTA
def t_windows():
    w = build_windows(64)
    assert len(w) == 15 and w[0] == (0, 8) and w[-1] == (56, 8), w
    assert build_windows(20) == [(0, 8), (4, 8), (8, 8), (12, 8)]
    assert build_windows(9) == [(0, 8), (1, 8)]   # final window ends at 8
    assert build_windows(8) == [(0, 8)]
    assert build_windows(5) == [(0, 5)]           # short video: one window


def _delta_run(t_frames):
    delta = Delta(CFG)
    demo = torch.rand(2, t_frames, 64, 768)
    mask = torch.ones(2, t_frames, dtype=torch.bool)
    times = torch.arange(t_frames, dtype=torch.float32).unsqueeze(0) \
        .expand(2, -1) * 0.35
    memory, wmask, change = delta(demo, mask, times.contiguous())
    s = len(build_windows(t_frames))
    assert memory.shape == (2, s, 4, 512), memory.shape
    assert wmask.shape == (2, s) and wmask.all()
    assert change.shape == (2, s, 512)
    memory.sum().backward()
    assert has_grad(delta)
    return change.detach()


def t_delta64():
    _delta_run(64)


def t_delta_short():
    _delta_run(5)   # single partial window
    _delta_run(3)   # shorter than one window, residuals still defined


def t_delta_invalid_frames():
    delta = Delta(CFG)
    demo = torch.rand(2, 64, 64, 768)
    mask = torch.ones(2, 64, dtype=torch.bool)
    mask[0, 16:24] = False          # window 4 (frames 16-23) fully invalid
    times = (torch.arange(64, dtype=torch.float32).unsqueeze(0)
             .expand(2, -1) * 0.35).contiguous()
    memory, wmask, change = delta(demo, mask, times)
    assert torch.isfinite(memory).all() and torch.isfinite(change).all()
    assert not wmask[0, 4] and wmask[1, 4]
    assert torch.all(memory[0, 4] == 0)         # invalid window -> zeroed
    memory.sum().backward()
    assert has_grad(delta)


def t_residual_math():
    # One window, one patch, one channel: values are frame indices.
    z = torch.arange(8, dtype=torch.float32).view(1, 8, 1, 1)
    z = z.expand(1, 8, 64, 768).contiguous()
    local, medium, endpoint = window_residuals(z)
    assert local.shape == (1, 7, 64, 768) and (local == 1).all()
    assert medium.shape == (1, 4, 64, 768) and (medium == 4).all()
    assert endpoint.shape == (1, 64, 768) and (endpoint == 7).all()


def t_cyclic_motion():
    # Out-and-back motion inside one window: first and last frames are
    # identical, so the endpoint residual is exactly zero, while the
    # signed local residuals are nonzero and change sign (spec 18.1).
    base = torch.randn(1, 64, 768)
    v = torch.randn(1, 64, 768)
    coeffs = [0.0, 1.0, 2.0, 3.0, 3.0, 2.0, 1.0, 0.0]
    z = torch.stack([base + c * v for c in coeffs], dim=1)   # [1,8,64,768]
    local, medium, endpoint = window_residuals(z)
    assert (endpoint == 0).all()
    # atol covers float32 cancellation in (base + c*v) - base; the sign
    # and order structure itself is exact (endpoint and turn point are
    # exactly zero above/below).
    assert torch.allclose(local[0, 0], v[0], rtol=1e-4, atol=1e-5)
    assert torch.allclose(local[0, 2], v[0], rtol=1e-4, atol=1e-5)
    assert torch.allclose(local[0, 4], -v[0], rtol=1e-4, atol=1e-5)
    assert torch.allclose(local[0, 6], -v[0], rtol=1e-4, atol=1e-5)
    assert local[0, 3].abs().max() == 0     # the turn point has no motion
    # Model level: the CHANGE token must see the cyclic motion even
    # though the endpoint difference is zero.
    delta = Delta(CFG)
    times = (torch.arange(8, dtype=torch.float32).unsqueeze(0) * 0.35)
    mask = torch.ones(1, 8, dtype=torch.bool)
    _, _, change_cyclic = delta(z, mask, times)
    static = base.unsqueeze(1).expand(1, 8, 64, 768).contiguous()
    _, _, change_static = delta(static, mask, times)
    dist = (change_cyclic - change_static).norm().item()
    assert dist > 1e-3, f"cyclic motion invisible to CHANGE token ({dist})"


def t_temporal_order():
    # Reversing time negates and reverses the local residuals.
    z = torch.rand(1, 8, 64, 768)
    local_fwd, _, _ = window_residuals(z)
    local_rev, _, _ = window_residuals(z.flip(1))
    assert torch.allclose(local_rev, -local_fwd.flip(1))
    # Model level: a reversed demo gives a different CHANGE token.
    delta = Delta(CFG)
    demo = torch.rand(1, 32, 64, 768)
    times = (torch.arange(32, dtype=torch.float32).unsqueeze(0) * 0.35)
    mask = torch.ones(1, 32, dtype=torch.bool)
    _, _, ch_fwd = delta(demo, mask, times)
    _, _, ch_rev = delta(demo.flip(1), mask, times)
    dist = (ch_fwd - ch_rev).norm().item()
    assert dist > 1e-4, f"temporal order invisible ({dist})"


def t_skill_loss_optional():
    # The function stays available for the optional experiment
    # (spec 16.3) but is off by default (checked in config test).
    change = torch.rand(6, 512, requires_grad=True)
    labels = torch.tensor([0, 0, 0, 1, 1, 1])
    eps = torch.tensor([0, 1, 2, 0, 1, 2])
    loss = skill_alignment_loss(change, labels, eps, 0.07)
    assert torch.isfinite(loss) and loss.item() > 0
    loss.backward()
    assert change.grad is not None
    zero = skill_alignment_loss(change.detach(), labels,
                                torch.zeros(6, dtype=torch.long), 0.07)
    assert zero.item() == 0.0  # same episode everywhere -> no positives


# ---------------------------------------------------------------- SYNC/PULSE
def _sync_inputs(with_demo=True):
    live = torch.rand(2, 128, 512)
    txt = torch.rand(2, 1, 512)
    st = torch.rand(2, 1, 512)
    hist = torch.rand(2, 3, 512)
    hmask = torch.tensor([[True, True, False]] * 2)
    if with_demo:
        demo = torch.rand(2, 15, 4, 512)
        wmask = torch.ones(2, 15, dtype=torch.bool)
        return live, txt, st, hist, hmask, demo, wmask
    return live, txt, st, hist, hmask, None, None


def t_sync_global():
    sync = Sync(CFG)
    # v1.1 SYNC has no pointer input at all (spec 9.3, 10.1).
    assert "pointer" not in inspect.signature(Sync.forward).parameters
    ctx = sync(*_sync_inputs(True))
    assert ctx.shape == (2, 64, 512)
    ctx.sum().backward()
    assert has_grad(sync)
    # Partially invalid demo memory stays finite.
    live, txt, st, hist, hmask, demo, wmask = _sync_inputs(True)
    wmask = wmask.clone()
    wmask[0, :5] = False
    ctx2 = sync(live, txt, st, hist, hmask, demo, wmask)
    assert torch.isfinite(ctx2).all()


def t_sync_null():
    sync = Sync(CFG)
    ctx = sync(*_sync_inputs(False))
    assert ctx.shape == (2, 64, 512)


def t_pulse():
    pulse = Pulse(CFG)
    logits = pulse(torch.rand(2, 64, 512), torch.tensor([0, 16]),
                   torch.tensor([3, 0]))
    assert logits.shape == (2, 3)
    loss = torch.nn.functional.cross_entropy(logits, torch.tensor([1, 2]))
    loss.backward()
    assert has_grad(pulse)


# ---------------------------------------------------------------- NEXUS/FLUX/ECHO
def t_nexus_flux():
    nexus, flux = Nexus(CFG), Flux(CFG)
    ctx = torch.rand(2, 64, 512)
    tau = torch.rand(2)
    noisy = torch.randn(2, 16, 7)
    tokens = flux.action_tokens(noisy, tau)
    assert tokens.shape == (2, 16, 512)
    act, eff = nexus(tokens, ctx)
    assert act.shape == (2, 16, 512) and eff.shape == (2, 16, 512)
    v = flux.velocity(act)
    assert v.shape == (2, 16, 7)
    target = torch.randn(2, 16, 7)
    mask = torch.ones(2, 16, dtype=torch.bool)
    loss = flux_loss(v, target, mask)
    assert torch.isfinite(loss)
    loss.backward()
    assert has_grad(nexus) and has_grad(flux)


def t_echo():
    echo = Echo(CFG)
    eff = torch.rand(2, 16, 512, requires_grad=True)
    pred = echo(eff)
    assert pred.shape == (2, 64, 768)
    target = torch.rand(2, 64, 768)
    valid = torch.ones(2, dtype=torch.bool)
    loss_hi = echo_loss(pred, target, torch.tensor([0.9, 0.75]), valid)
    assert torch.isfinite(loss_hi) and loss_hi.item() > 0
    loss_lo = echo_loss(pred, target, torch.tensor([0.1, 0.2]), valid)
    assert loss_lo.item() == 0.0  # tau gate: no sample qualifies
    loss_hi.backward()
    assert eff.grad is not None


def t_echo_fixed_projection():
    # The 512-dim variant: the target projection is a fixed buffer,
    # never a trainable parameter (spec 13.5).
    cfg = TraceConfig(echo_target_dim=512)
    echo = Echo(cfg)
    assert "fixed_target_proj" not in dict(echo.named_parameters())
    assert not echo.fixed_target_proj.requires_grad
    eff = torch.rand(2, 16, 512, requires_grad=True)
    pred = echo(eff)
    assert pred.shape == (2, 64, 512)
    target768 = torch.rand(2, 64, 768)
    tgt = echo.project_target(target768)
    assert tgt.shape == (2, 64, 512) and not tgt.requires_grad
    valid = torch.ones(2, dtype=torch.bool)
    loss = echo_loss(pred, tgt, torch.tensor([0.9, 0.9]), valid)
    assert torch.isfinite(loss)
    loss.backward()
    assert eff.grad is not None


# ---------------------------------------------------------------- data
def _synthetic_cache(specs):
    """specs: list of (task_index, length). Features encode the global
    frame index in every channel; actions encode it too, so any
    cross-boundary or future-frame read is directly visible."""
    total = sum(L for _, L in specs)
    feats = torch.zeros(total, 2, 64, 768)
    for g in range(total):
        feats[g] = float(g)
    actions = torch.arange(total, dtype=torch.float32)
    actions = actions.unsqueeze(1).expand(total, 7).contiguous()
    episodes, start = [], 0
    for task, L in specs:
        episodes.append({"start": start, "length": L, "task_index": task})
        start += L
    return {
        "features": feats,
        "states": torch.zeros(total, 8),
        "actions": actions,
        "episodes": episodes,
        "text_emb": {task: torch.zeros(768) for task, _ in specs},
        "stats": {"state_mean": torch.zeros(8), "state_std": torch.ones(8),
                  "action_mean": torch.zeros(7), "action_std": torch.ones(7)},
    }


def t_data_echo_target():
    cache = _synthetic_cache([(0, 40)])
    data = SmokeData(cache)
    batch = data.get_batch([0, 5], "cpu")
    # Residual target: (g+4) - g = 4 in every element (spec 13.3).
    assert torch.allclose(batch["echo_target"],
                          torch.full_like(batch["echo_target"], 4.0))
    assert not batch["echo_target"].requires_grad


def t_data_episode_boundaries():
    cache = _synthetic_cache([(0, 40), (1, 35)])
    data = SmokeData(cache)
    eps = cache["episodes"]
    for idx, (ei, t) in enumerate(data.samples):
        ep = eps[ei]
        g = ep["start"] + t
        assert g + 15 < ep["start"] + ep["length"]   # chunk inside episode
    batch = data.get_batch([0], "cpu")               # ep 0, t = 0
    past_pooled, _, _, _, past_mask = batch["history"]
    assert not past_mask.any()                       # no history at t=0
    last0 = max(i for i, (ei, _) in enumerate(data.samples) if ei == 0)
    batch = data.get_batch([last0], "cpu")
    g = eps[0]["start"] + data.samples[last0][1]
    chunk = batch["action_target"][0, :, 0]
    assert torch.allclose(chunk, torch.arange(g, g + 16, dtype=torch.float32))
    assert batch["pooled_live"][0, 0, 0, 0].item() == float(g)


def t_data_support_query():
    cache = _synthetic_cache([(0, 90), (0, 85), (0, 95)])
    data = SupportQueryData(cache)
    gen = torch.Generator().manual_seed(7)
    batch = data.get_batch(list(range(8)), "cpu", generator=gen)
    sup, qry = batch["support_episode"], batch["query_episode"]
    assert (sup != qry).all()                        # different episodes
    eps = cache["episodes"]
    assert batch["text_emb"] is None                 # video-only mode
    assert "demo_actions" not in batch and "demo_states" not in batch
    demo = batch["demo_pooled"]
    assert demo.shape[1] <= 64
    for r in range(8):
        ep = eps[int(sup[r])]
        vals = demo[r][batch["frame_mask"][r]]
        assert vals.numel() > 0
        assert vals.min().item() >= ep["start"]
        assert vals.max().item() < ep["start"] + ep["length"]
        # Padding, if any, comes after the valid frames only.
        m = batch["frame_mask"][r]
        assert m[: int(m.sum())].all() and not m[int(m.sum()):].any()


def t_data_support_query_config_arg():
    # Regression (found 2026-11-21): the validation harness builds
    # SupportQueryData(cache, cfg) with a TraceConfig as the second
    # positional argument (phase_b.py, train_pilot.py), while the
    # package signature expected a float fps there. The config landed
    # in self.fps and _support_demo divided a tensor by it (TypeError,
    # first demo batch). Every older test called SupportQueryData(cache)
    # with no second argument, so nothing caught the mismatch.
    from trace_vla.data import subsample_indices
    cache = _synthetic_cache([(0, 90), (0, 85), (0, 95)])
    eps = cache["episodes"]

    data = SupportQueryData(cache, TraceConfig())
    assert isinstance(data.fps, float) and data.fps == 10.0
    assert data.demo_max_frames == 64
    gen = torch.Generator().manual_seed(11)
    batch = data.get_batch(list(range(4)), "cpu", generator=gen)
    for r in range(4):
        ep = eps[int(batch["support_episode"][r])]
        n = int(batch["frame_mask"][r].sum())
        expected = subsample_indices(ep["length"], 64).float() / 10.0
        assert n == len(expected)
        assert torch.allclose(batch["frame_times"][r, :n], expected)

    data5 = SupportQueryData(cache, TraceConfig(fps=5.0))
    assert isinstance(data5.fps, float) and data5.fps == 5.0
    frames, mask, times, sei = data5._support_demo(
        0, torch.Generator().manual_seed(0))
    expected5 = subsample_indices(eps[sei]["length"], 64).float() / 5.0
    assert torch.allclose(times, expected5)
    assert int(mask.sum()) == frames.shape[0]

    # Backward compatibility: a bare number still works as fps.
    data7 = SupportQueryData(cache, 7.5)
    assert isinstance(data7.fps, float) and data7.fps == 7.5


def t_data_no_future_leakage():
    cache = _synthetic_cache([(0, 90), (0, 85), (0, 95)])
    data = SupportQueryData(cache)
    gen = torch.Generator().manual_seed(3)
    idxs = [0, 30, 60]
    batch = data.get_batch(idxs, "cpu", generator=gen)
    eps = cache["episodes"]
    for r, idx in enumerate(idxs):
        ei, t = data.samples[idx]
        g = eps[ei]["start"] + t
        # The future frame g+4 appears only inside the ECHO target.
        assert batch["pooled_live"][r, 0, 0, 0].item() == float(g)
        past_pooled, _, _, _, past_mask = batch["history"]
        seen = past_pooled[r][past_mask[r]]
        assert seen.numel() == 0 or seen.max().item() < g
        demo_vals = batch["demo_pooled"][r][batch["frame_mask"][r]]
        assert not (demo_vals == float(g + 4)).any()
        assert torch.allclose(batch["echo_target"][r],
                              torch.full_like(batch["echo_target"][r], 4.0))


# ---------------------------------------------------------------- full model
def _fake_batch(with_demo: bool, with_echo: bool):
    b = 2
    batch = {
        "pooled_live": torch.rand(b, 2, 64, 768),
        "text_emb": torch.rand(b, 768),
        "state_norm": torch.rand(b, 8),
        "history": (torch.rand(b, 3, 2, 64, 768), torch.rand(b, 3, 8),
                    torch.rand(b, 3, 7), torch.tensor([[0.4, 0.8, 1.2]] * b),
                    torch.tensor([[True, True, False]] * b)),
        "action_target": torch.randn(b, 16, 7),
        "action_mask": torch.ones(b, 16, dtype=torch.bool),
    }
    if with_demo:
        batch["demo_pooled"] = torch.rand(b, 32, 64, 768)
        batch["frame_mask"] = torch.ones(b, 32, dtype=torch.bool)
        batch["frame_times"] = (torch.arange(32, dtype=torch.float32)
                                 .unsqueeze(0).expand(b, -1) * 0.35).contiguous()
    if with_echo:
        batch["echo_target"] = torch.rand(b, 64, 768)
        batch["echo_valid"] = torch.ones(b, dtype=torch.bool)
    return batch


def t_model_stage1():
    cfg = TraceConfig(use_echo_loss=False)
    model = TraceVLA(cfg, load_anchor=False)
    losses = model.forward_train(_fake_batch(False, False))
    assert set(losses) == {"flux", "total"}
    assert torch.isfinite(losses["total"])
    losses["total"].backward()
    assert has_grad(model.nexus) and has_grad(model.sync)


def t_model_full_v11():
    cfg = TraceConfig()   # v1.1 defaults
    model = TraceVLA(cfg, load_anchor=False)
    losses = model.forward_train(_fake_batch(True, True))
    # Default objective: FLUX + ECHO only. No pulse, no delta loss.
    assert "flux" in losses and "echo" in losses
    assert "pulse" not in losses and "delta" not in losses
    expected = losses["flux"] + 0.1 * losses["echo"]
    assert torch.allclose(losses["total"], expected, atol=1e-6)
    assert torch.isfinite(losses["total"])
    losses["total"].backward()
    assert has_grad(model.delta) and has_grad(model.echo)
    assert has_grad(model.sync) and has_grad(model.nexus)
    # PULSE receives no gradient from the default objective.
    assert all(p.grad is None for p in model.pulse.parameters())
    ctx = model.compute_context(
        torch.rand(2, 2, 64, 768), torch.rand(2, 768), torch.rand(2, 8),
        (torch.rand(2, 3, 2, 64, 768), torch.rand(2, 3, 8),
         torch.rand(2, 3, 7), torch.tensor([[0.4, 0.8, 1.2]] * 2),
         torch.tensor([[True, True, False]] * 2)))
    chunk, echo_pred = model.sample_actions(ctx, 2, "cpu")
    assert chunk.shape == (2, 16, 7) and torch.isfinite(chunk).all()
    assert echo_pred.shape == (2, 64, 768)


def t_static_memory_control():
    """Validation control D00/S00: the static slot memory must be
    invariant to the order of the demo frames, and the full model
    must train through it."""
    torch.manual_seed(0)
    cfg = TraceConfig(demo_mode="static")
    model = TraceVLA(cfg, load_anchor=False)
    demo = torch.rand(1, 64, 64, 768)
    mask = torch.ones(1, 64, dtype=torch.bool)
    times = torch.arange(64, dtype=torch.float32).unsqueeze(0) * 0.1
    mem1, wm1, _ = model.encode_demo(demo, mask, times)
    assert mem1.shape == (1, 4, 4, 512) and bool(wm1.all())
    perm = torch.randperm(64)
    mem2, _, _ = model.encode_demo(demo[:, perm], mask, times)
    assert torch.allclose(mem1, mem2, atol=1e-5), \
        "static memory must not depend on demo frame order"
    losses = model.forward_train(_fake_batch(True, True))
    assert torch.isfinite(losses["total"])
    losses["total"].backward()
    assert has_grad(model.static_encoder)


def t_delta_raw_ablation():
    """Validation arm D01/C02: DELTA with residuals disabled must
    still produce finite memory and train (ordered raw windows)."""
    torch.manual_seed(0)
    cfg = TraceConfig(delta_use_residuals=False)
    model = TraceVLA(cfg, load_anchor=False)
    losses = model.forward_train(_fake_batch(True, True))
    assert torch.isfinite(losses["total"])
    losses["total"].backward()
    assert has_grad(model.delta)


if __name__ == "__main__":
    check("anchor.pool_patches_2x2", t_pool)
    check("anchor.real_tipsv2", t_anchor_real)
    check("anchor.heads", t_heads)
    check("config.v11_defaults", t_config_v11)
    check("delta.window_layout_v11", t_windows)
    check("delta.forward_backward_T64", t_delta64)
    check("delta.forward_short_demo", t_delta_short)
    check("delta.invalid_frames", t_delta_invalid_frames)
    check("delta.residual_math", t_residual_math)
    check("delta.cyclic_motion", t_cyclic_motion)
    check("delta.temporal_order", t_temporal_order)
    check("delta.skill_alignment_optional", t_skill_loss_optional)
    check("sync.global_attention", t_sync_global)
    check("sync.null_demo", t_sync_null)
    check("pulse.head_optional", t_pulse)
    check("nexus+flux", t_nexus_flux)
    check("echo.head+loss", t_echo)
    check("echo.fixed_projection", t_echo_fixed_projection)
    check("data.echo_target_residual", t_data_echo_target)
    check("data.episode_boundaries", t_data_episode_boundaries)
    check("data.support_query_pairing", t_data_support_query)
    check("data.support_query_config_arg", t_data_support_query_config_arg)
    check("data.no_future_leakage", t_data_no_future_leakage)
    check("model.stage1_forward_backward", t_model_stage1)
    check("model.full_v11_forward_backward+sample", t_model_full_v11)
    check("model.static_memory_control", t_static_memory_control)
    check("model.delta_raw_ablation", t_delta_raw_ablation)
    failed = [r for r in RESULTS if r[1] == "FAIL"]
    print(f"\n{len(RESULTS) - len(failed)}/{len(RESULTS)} checks passed")
    sys.exit(1 if failed else 0)