|
| 1 | +"""Unit tests for the JEPA target encoder (frozen / EMA, stop-gradient). |
| 2 | +
|
| 3 | +Verifies the collapse-safety guarantees of the target branch and that it |
| 4 | +plugs into the already-merged ``FutureState`` + ``FeatureReconstructionLoss``: |
| 5 | + - the target encoder never carries gradient (frozen params, detached output), |
| 6 | + - "frozen" mode is a stable deep copy independent of the online encoder, |
| 7 | + - "ema" mode moves the target toward the online encoder on ``update()``, |
| 8 | + - ``compute_jepa_loss`` is differentiable w.r.t. the prediction ONLY, |
| 9 | + - end-to-end with the real FutureState world-model head. |
| 10 | +""" |
| 11 | + |
| 12 | +import pytest |
| 13 | +import torch |
| 14 | +import torch.nn as nn |
| 15 | + |
| 16 | +from model_components.future_state import FutureState |
| 17 | +from model_components.jepa_target_encoder import ( |
| 18 | + JepaTargetEncoder, |
| 19 | + compute_jepa_loss, |
| 20 | +) |
| 21 | +from model_components.losses.feature_reconstruction_loss import ( |
| 22 | + FeatureReconstructionLoss, |
| 23 | +) |
| 24 | + |
| 25 | +EMBED_DIM = 256 |
| 26 | +NUM_FUTURE = 4 |
| 27 | + |
| 28 | + |
| 29 | +class _TinyEncoder(nn.Module): |
| 30 | + """Maps a feature map [B, C, H, W] -> [B, C, H, W] (stand-in for backbone).""" |
| 31 | + |
| 32 | + def __init__(self, c=EMBED_DIM): |
| 33 | + super().__init__() |
| 34 | + self.conv = nn.Conv2d(c, c, 3, padding=1) |
| 35 | + self.bn = nn.BatchNorm2d(c) |
| 36 | + |
| 37 | + def forward(self, x): |
| 38 | + return self.bn(self.conv(x)) |
| 39 | + |
| 40 | + |
| 41 | +def _future_obs(batch, device, h=8, w=8): |
| 42 | + return [torch.randn(batch, EMBED_DIM, h, w, device=device) |
| 43 | + for _ in range(NUM_FUTURE)] |
| 44 | + |
| 45 | + |
| 46 | +def test_invalid_mode_and_decay(): |
| 47 | + enc = _TinyEncoder() |
| 48 | + with pytest.raises(ValueError, match="mode must be"): |
| 49 | + JepaTargetEncoder(enc, mode="bogus") |
| 50 | + with pytest.raises(ValueError, match="ema_decay"): |
| 51 | + JepaTargetEncoder(enc, mode="ema", ema_decay=1.5) |
| 52 | + |
| 53 | + |
| 54 | +def test_target_params_are_frozen(device): |
| 55 | + target = JepaTargetEncoder(_TinyEncoder(), mode="frozen").to(device) |
| 56 | + assert all(not p.requires_grad for p in target.parameters()) |
| 57 | + |
| 58 | + |
| 59 | +def test_forward_output_is_detached(device): |
| 60 | + target = JepaTargetEncoder(_TinyEncoder(), mode="ema").to(device) |
| 61 | + outs = target(_future_obs(2, device)) |
| 62 | + assert len(outs) == NUM_FUTURE |
| 63 | + for o in outs: |
| 64 | + assert not o.requires_grad |
| 65 | + assert o.grad_fn is None |
| 66 | + assert o.shape == (2, EMBED_DIM, 8, 8) |
| 67 | + |
| 68 | + |
| 69 | +def test_frozen_is_independent_deep_copy(device): |
| 70 | + online = _TinyEncoder().to(device) |
| 71 | + target = JepaTargetEncoder(online, mode="frozen").to(device) |
| 72 | + before = [p.clone() for p in target.encoder.parameters()] |
| 73 | + |
| 74 | + # Mutate the ONLINE encoder; the frozen target must not change. |
| 75 | + with torch.no_grad(): |
| 76 | + for p in online.parameters(): |
| 77 | + p.add_(1.0) |
| 78 | + target.update(online) # no-op in frozen mode |
| 79 | + |
| 80 | + for b, p in zip(before, target.encoder.parameters()): |
| 81 | + assert torch.equal(b, p) |
| 82 | + |
| 83 | + |
| 84 | +def test_ema_update_moves_target_toward_online(device): |
| 85 | + torch.manual_seed(0) |
| 86 | + online = _TinyEncoder().to(device) |
| 87 | + target = JepaTargetEncoder(online, mode="ema", ema_decay=0.9).to(device) |
| 88 | + |
| 89 | + # Push the online encoder far away, then EMA-update once. |
| 90 | + with torch.no_grad(): |
| 91 | + for p in online.parameters(): |
| 92 | + p.add_(10.0) |
| 93 | + |
| 94 | + t_before = [p.clone() for p in target.encoder.parameters()] |
| 95 | + target.update(online) |
| 96 | + |
| 97 | + for tb, t_after, o_p in zip(t_before, target.encoder.parameters(), |
| 98 | + online.parameters()): |
| 99 | + moved = (t_after - tb).abs().sum().item() |
| 100 | + assert moved > 0.0, "ema target did not move" |
| 101 | + # decay=0.9 -> target should move ~10% of the way, not all the way. |
| 102 | + assert not torch.allclose(t_after, o_p), "target jumped fully to online" |
| 103 | + expected = 0.9 * tb + 0.1 * o_p |
| 104 | + assert torch.allclose(t_after, expected, atol=1e-5) |
| 105 | + |
| 106 | + |
| 107 | +def test_compute_jepa_loss_zero_when_prediction_matches_target(device): |
| 108 | + target = JepaTargetEncoder(_TinyEncoder(), mode="frozen").to(device) |
| 109 | + loss_fn = FeatureReconstructionLoss(num_future_steps=NUM_FUTURE).to(device) |
| 110 | + obs = _future_obs(2, device) |
| 111 | + targets = target(obs) |
| 112 | + predicted = [t.clone().requires_grad_(True) for t in targets] |
| 113 | + loss = compute_jepa_loss(predicted, obs, target, loss_fn, weight=1.0) |
| 114 | + assert loss.ndim == 0 |
| 115 | + assert loss.item() == pytest.approx(0.0, abs=1e-6) |
| 116 | + |
| 117 | + |
| 118 | +def test_compute_jepa_loss_weight_scales_linearly(device): |
| 119 | + target = JepaTargetEncoder(_TinyEncoder(), mode="frozen").to(device) |
| 120 | + loss_fn = FeatureReconstructionLoss(num_future_steps=NUM_FUTURE).to(device) |
| 121 | + obs = _future_obs(3, device) |
| 122 | + predicted = [torch.randn(3, EMBED_DIM, 8, 8, device=device) |
| 123 | + for _ in range(NUM_FUTURE)] |
| 124 | + l1 = compute_jepa_loss(predicted, obs, target, loss_fn, weight=1.0) |
| 125 | + l2 = compute_jepa_loss(predicted, obs, target, loss_fn, weight=0.25) |
| 126 | + assert l2.item() == pytest.approx(0.25 * l1.item(), rel=1e-5) |
| 127 | + |
| 128 | + |
| 129 | +def test_gradient_flows_to_prediction_only(device): |
| 130 | + target = JepaTargetEncoder(_TinyEncoder(), mode="ema").to(device) |
| 131 | + loss_fn = FeatureReconstructionLoss(num_future_steps=NUM_FUTURE).to(device) |
| 132 | + obs = _future_obs(2, device) |
| 133 | + predicted = [torch.randn(2, EMBED_DIM, 8, 8, device=device, |
| 134 | + requires_grad=True) for _ in range(NUM_FUTURE)] |
| 135 | + |
| 136 | + loss = compute_jepa_loss(predicted, obs, target, loss_fn, weight=0.5) |
| 137 | + loss.backward() |
| 138 | + |
| 139 | + assert all(p.grad is not None for p in predicted), \ |
| 140 | + "prediction must receive gradient" |
| 141 | + assert all(p.grad is None for p in target.parameters()), \ |
| 142 | + "target encoder must NOT receive gradient (stop-gradient)" |
| 143 | + |
| 144 | + |
| 145 | +def test_end_to_end_with_future_state(device): |
| 146 | + """FutureState (predictor) + JepaTargetEncoder (targets) + recon loss. |
| 147 | +
|
| 148 | + Mirrors the intended training step: the world-model head predicts future |
| 149 | + features, targets come from the frozen/EMA encoder on future observations, |
| 150 | + and the JEPA loss back-props into FutureState but never into the target.""" |
| 151 | + torch.manual_seed(0) |
| 152 | + future_state = FutureState(embed_dim=EMBED_DIM, |
| 153 | + ego_hidden_dim=EMBED_DIM).to(device) |
| 154 | + target = JepaTargetEncoder(_TinyEncoder(), mode="ema").to(device) |
| 155 | + loss_fn = FeatureReconstructionLoss(num_future_steps=NUM_FUTURE).to(device) |
| 156 | + |
| 157 | + fused = torch.randn(2, EMBED_DIM, 8, 8, device=device) |
| 158 | + ego_hidden = torch.randn(2, EMBED_DIM, device=device) |
| 159 | + predicted = future_state(fused, ego_hidden) |
| 160 | + assert len(predicted) == NUM_FUTURE |
| 161 | + |
| 162 | + future_obs = _future_obs(2, device) |
| 163 | + loss = compute_jepa_loss(predicted, future_obs, target, loss_fn, weight=0.1) |
| 164 | + assert loss.ndim == 0 and torch.isfinite(loss) |
| 165 | + |
| 166 | + loss.backward() |
| 167 | + assert any(p.grad is not None for p in future_state.parameters()), \ |
| 168 | + "FutureState must receive gradient from the JEPA loss" |
| 169 | + assert all(p.grad is None for p in target.parameters()), \ |
| 170 | + "target encoder must stay gradient-free" |
0 commit comments