File size: 7,056 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 | """TRACE-VLA assembled model (spec v1.1, sections 4, 14, 16).
Default training objective (spec 16.1):
L_total = L_flux + 0.1 * L_echo
The cross-skill alignment loss (lambda_delta = 0) and the progress
loss (lambda_pulse = 0) are optional experiments and are not part of
the default objective. SYNC retrieves from the full demo memory with
global soft attention; no pointer is used anywhere in v1.1's initial
configuration. Stage 1 (TRACE-Base) disables the ECHO loss via
cfg.use_echo_loss and uses the null demo token; the 16 effect query
tokens stay in NEXUS so the effect pathway cost stays visible.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from .anchor import AnchorHeads, TipsAnchor
from .delta import Delta, skill_alignment_loss
from .echo import Echo, echo_loss
from .flux import Flux, flux_loss
from .nexus import Nexus
from .pulse import Pulse
from .static_memory import StaticDemoEncoder
from .sync import Sync
class TraceVLA(nn.Module):
def __init__(self, cfg, load_anchor: bool = True):
super().__init__()
self.cfg = cfg
self.anchor = TipsAnchor(cfg.backbone_id) if load_anchor else None
self.heads = AnchorHeads(cfg)
self.delta = Delta(cfg)
self.static_encoder = StaticDemoEncoder(cfg) \
if cfg.demo_mode == "static" else None
self.static_encoder = StaticDemoEncoder(cfg) \
if cfg.demo_mode == "static" else None
self.sync = Sync(cfg)
self.pulse = Pulse(cfg)
self.nexus = Nexus(cfg)
self.flux = Flux(cfg)
self.echo = Echo(cfg)
# ---- context assembly -------------------------------------------------
def compute_context(self, pooled_live, text_emb, state_norm, history,
demo_memory=None, window_mask=None):
"""pooled_live [B,2,64,768]; text_emb [B,768] or None; state_norm
[B,8]; history = (past_pooled, past_state, past_action,
past_elapsed, past_mask). Returns SYNC context [B,64,512]."""
live = self.heads.project_live(pooled_live)
text = self.heads.project_text(text_emb, pooled_live.shape[0],
pooled_live.device)
state = self.heads.project_state(state_norm)
hist = self.heads.build_history(*history)
return self.sync(live, text, state, hist, history[4],
demo_memory=demo_memory, window_mask=window_mask)
def encode_demo(self, demo_pooled, frame_mask, frame_times):
if self.cfg.demo_mode == "static":
return self.static_encoder(demo_pooled, frame_mask,
frame_times)
return self.delta(demo_pooled, frame_mask, frame_times)
# ---- one NEXUS/FLUX pass ----------------------------------------------
def _velocity(self, context, noisy_actions, tau):
tokens = self.flux.action_tokens(noisy_actions, tau)
act_feat, eff_feat = self.nexus(tokens, context)
return self.flux.velocity(act_feat), eff_feat
# ---- training forward ---------------------------------------------------
def forward_train(self, batch: dict) -> dict:
cfg = self.cfg
demo_memory = window_mask = change_tokens = None
if batch.get("demo_pooled") is not None:
demo_memory, window_mask, change_tokens = self.encode_demo(
batch["demo_pooled"], batch["frame_mask"],
batch["frame_times"])
context = self.compute_context(
batch["pooled_live"], batch.get("text_emb"), batch["state_norm"],
batch["history"], demo_memory=demo_memory,
window_mask=window_mask)
target = batch["action_target"] # [B,16,7]
b = target.shape[0]
device = target.device
tau = batch.get("tau")
if tau is None:
tau = torch.rand(b, device=device)
eps = torch.randn_like(target)
a_tau = (1.0 - tau).view(b, 1, 1) * eps + tau.view(b, 1, 1) * target
velocity, eff_feat = self._velocity(context, a_tau, tau)
v_star = target - eps
losses = {"flux": flux_loss(velocity, v_star, batch["action_mask"])}
if cfg.use_echo_loss and batch.get("echo_target") is not None:
pred = self.echo(eff_feat)
tgt = self.echo.project_target(batch["echo_target"])
losses["echo"] = echo_loss(
pred, tgt, tau, batch["echo_valid"],
huber_delta=cfg.huber_delta, tau_min=cfg.echo_tau_min)
# Optional objectives (spec 16.3, 10.1): computed only when
# explicitly enabled; both default to off with weight 0.
if cfg.use_pulse_loss and batch.get("pulse_label") is not None:
ptr_idx = batch.get("pointer")
if ptr_idx is None:
ptr_idx = torch.full((b,), cfg.max_windows, dtype=torch.long,
device=device)
logits = self.pulse(context, ptr_idx, batch["prev_class"])
losses["pulse"] = F.cross_entropy(
logits[batch["pulse_valid"]],
batch["pulse_label"][batch["pulse_valid"]]) \
if bool(batch["pulse_valid"].any()) else logits.sum() * 0.0
if cfg.use_delta_loss and change_tokens is not None \
and batch.get("skill_label") is not None:
losses["delta"] = skill_alignment_loss(
change_tokens[batch["skill_valid"]],
batch["skill_label"][batch["skill_valid"]],
batch["skill_episode"][batch["skill_valid"]],
temperature=cfg.skill_temperature) \
if bool(batch["skill_valid"].any()) else change_tokens.sum() * 0.0
total = cfg.lambda_flux * losses["flux"]
if "echo" in losses:
total = total + cfg.lambda_echo * losses["echo"]
if "delta" in losses:
total = total + cfg.lambda_delta * losses["delta"]
if "pulse" in losses:
total = total + cfg.lambda_pulse * losses["pulse"]
losses["total"] = total
return losses
# ---- inference ----------------------------------------------------------
@torch.no_grad()
def sample_actions(self, context, batch_size: int, device,
generator: torch.Generator | None = None):
"""Four Euler steps from noise (spec 12.3). Returns the action
chunk [B, 16, 7] in normalized action units and the ECHO
residual estimate from the last flow evaluation (spec 13.9)."""
cfg = self.cfg
a = torch.randn(batch_size, cfg.chunk, cfg.action_dim,
device=device, generator=generator)
steps = cfg.euler_steps
eff_feat = None
for j in range(steps):
tau = torch.full((batch_size,), j / steps, device=device)
v, eff_feat = self._velocity(context, a, tau)
a = a + (1.0 / steps) * v
echo_pred = self.echo(eff_feat) if eff_feat is not None else None
return a, echo_pred
|