File size: 7,393 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 | """Unit tests for the TRACE-VLA v2 core modules (spec v2.0).
Covers DemoObjectBinding, DemoToLiveCorrespondence,
ObjectConditionedAdapter and the TraceVLA2 wrapper:
- output shapes and probability sanity;
- gradient flow into every new module;
- zero-condition sanity: at initialization the adapter contributes
exactly zero, so the v2 context equals the v1 context bitwise,
with and without C_object supplied;
- candidate permutation equivariance of the correspondence probs;
- parameter counts against the spec XXII budgets.
Run with the training venv python (needs torch):
python -m tests.test_v2_modules (from the trace_vla dir)
python tests/test_v2_modules.py
"""
import sys
from pathlib import Path
import torch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from trace_vla.binding import DemoObjectBinding # noqa: E402
from trace_vla.config import TraceConfig # noqa: E402
from trace_vla.correspondence import DemoToLiveCorrespondence # noqa: E402
from trace_vla.model_v2 import ObjectConditionedAdapter, TraceVLA2 # noqa: E402
PASS = []
def check(name, fn):
try:
fn()
PASS.append((name, True, ""))
print(f"PASS {name}")
except Exception as e: # noqa: BLE001
PASS.append((name, False, repr(e)))
print(f"FAIL {name}: {e!r}")
def n_params(m):
return sum(p.numel() for p in m.parameters())
B, T, C, K = 2, 40, 2, 5
demo = torch.randn(B, T, 64, 768)
fmask = torch.ones(B, T, dtype=torch.bool)
fmask[1, 30:] = False
live = torch.randn(B, C, 64, 768)
cand = torch.zeros(B, K, C * 64)
for k in range(K):
cand[:, k, k * 20:(k + 1) * 20] = 1.0
def t_binding_shapes():
m = DemoObjectBinding()
out = m(demo, fmask)
assert out["target_embedding"].shape == (B, 256)
assert out["interaction_tokens"].shape == (B, 4, 256)
assert out["confidence"].shape == (B, 1)
assert bool(((out["confidence"] > 0) & (out["confidence"] < 1)).all())
assert out["relevance"].shape == (B, T)
assert torch.allclose(out["relevance"].sum(1),
torch.ones(B), atol=1e-5)
n = torch.linalg.vector_norm(out["target_embedding"], dim=-1)
assert torch.allclose(n, torch.ones(B), atol=1e-5)
def t_binding_grad():
m = DemoObjectBinding()
out = m(demo, fmask)
loss = out["target_embedding"].sum() + out["interaction_tokens"].sum() \
+ out["confidence"].sum()
loss.backward()
for name, p in m.named_parameters():
assert p.grad is not None, f"no grad: {name}"
def t_corr_shapes():
m = DemoToLiveCorrespondence()
te = torch.randn(B, 256)
out = m(te, live, cand)
assert out["probs"].shape == (B, K)
assert torch.allclose(out["probs"].sum(1), torch.ones(B), atol=1e-5)
assert out["heatmap"].shape == (B, C, 8, 8)
assert out["target_features"].shape == (B, 256)
assert out["target_features_512"].shape == (B, 512)
assert out["best_idx"].shape == (B,)
def t_corr_grad():
m = DemoToLiveCorrespondence()
out = m(torch.randn(B, 256), live, cand)
(out["probs"].sum() + out["target_features_512"].sum()
+ out["heatmap"].sum()).backward()
for name, p in m.named_parameters():
assert p.grad is not None, f"no grad: {name}"
def t_corr_permutation():
torch.manual_seed(0)
m = DemoToLiveCorrespondence().eval()
te = torch.randn(B, 256)
perm = torch.tensor([2, 0, 4, 1, 3])
with torch.no_grad():
p1 = m(te, live, cand)["probs"]
p2 = m(te, live, cand[:, perm])["probs"]
assert torch.allclose(p1[:, perm], p2, atol=1e-6)
def t_adapter_zero():
m = ObjectConditionedAdapter()
cond = m(torch.randn(B, 256), torch.randn(B, 512),
torch.randn(B, 2, 8, 8), torch.rand(B, 1))
assert cond.shape == (B, 512)
assert torch.equal(cond, torch.zeros(B, 512)), \
"zero-init adapter must output exactly zero at init"
def _v1_inputs():
torch.manual_seed(1)
cfg = TraceConfig(delta_use_residuals=False, use_echo_loss=False)
pooled_live = torch.randn(B, 2, 64, 768)
state = torch.randn(B, 8)
hist = (torch.randn(B, 3, 2, 64, 768), torch.randn(B, 3, 8),
torch.randn(B, 3, 7), torch.rand(B, 3),
torch.ones(B, 3, dtype=torch.bool))
demo_p = torch.randn(B, T, 64, 768)
times = torch.arange(T).float().unsqueeze(0).expand(B, T) / 10.0
return cfg, pooled_live, state, hist, demo_p, times
def t_v2_zero_condition():
cfg, pooled_live, state, hist, demo_p, times = _v1_inputs()
m2 = TraceVLA2(cfg, load_anchor=False).eval()
with torch.no_grad():
mem, wm, _ = m2.v1.encode_demo(demo_p, fmask, times)
ctx_v1 = m2.v1.compute_context(pooled_live, None, state, hist,
demo_memory=mem, window_mask=wm)
ctx_v2, aux = m2.compute_context_v2(
pooled_live, None, state, hist, demo_pooled=demo_p,
frame_mask=fmask, frame_times=times, cand_mask=cand)
ctx_v2_nocand, aux_none = m2.compute_context_v2(
pooled_live, None, state, hist, demo_pooled=demo_p,
frame_mask=fmask, frame_times=times)
assert aux is not None and aux_none is None
assert torch.equal(ctx_v1, ctx_v2), \
"adapter at init must leave the v1 context bitwise unchanged"
assert torch.equal(ctx_v1, ctx_v2_nocand)
def t_v2_grad_and_sample():
cfg, pooled_live, state, hist, demo_p, times = _v1_inputs()
m2 = TraceVLA2(cfg, load_anchor=False)
ctx, aux = m2.compute_context_v2(
pooled_live, None, state, hist, demo_pooled=demo_p,
frame_mask=fmask, frame_times=times, cand_mask=cand)
assert ctx.shape == (B, 64, 512)
# Perturb the adapter output layer so C_object is live, then the
# full path (context -> FLUX sample is no_grad; use velocity path
# through a training-style loss on the context) must carry grad.
with torch.no_grad():
m2.adapter.mlp[-1].weight.normal_(0, 0.1)
ctx2, _ = m2.compute_context_v2(
pooled_live, None, state, hist, demo_pooled=demo_p,
frame_mask=fmask, frame_times=times, cand_mask=cand)
assert not torch.allclose(ctx, ctx2)
ctx2.sum().backward()
assert m2.binding.patch_proj.weight.grad is not None
assert m2.correspondence.score_mlp[0].weight.grad is not None
acts, _ = m2.sample_actions(ctx.detach(), B, torch.device("cpu"))
assert acts.shape == (B, 16, 7)
def t_param_budgets():
b = n_params(DemoObjectBinding())
c = n_params(DemoToLiveCorrespondence())
a = n_params(ObjectConditionedAdapter())
print(f" params: binding={b:,} correspondence={c:,} adapter={a:,}")
assert 2_000_000 <= b <= 4_000_000, b
assert c <= 5_000_000, c
assert 1_000_000 <= a <= 3_000_000, a
if __name__ == "__main__":
check("binding.shapes", t_binding_shapes)
check("binding.grad", t_binding_grad)
check("correspondence.shapes", t_corr_shapes)
check("correspondence.grad", t_corr_grad)
check("correspondence.permutation", t_corr_permutation)
check("adapter.zero_init", t_adapter_zero)
check("v2.zero_condition_sanity", t_v2_zero_condition)
check("v2.grad_and_sample", t_v2_grad_and_sample)
check("v2.param_budgets", t_param_budgets)
n_fail = sum(1 for _, ok, _ in PASS if not ok)
print(f"{len(PASS) - n_fail}/{len(PASS)} PASS")
sys.exit(1 if n_fail else 0)
|