trace-vla-code / code /trace_vla /pkg /model_v4.py
phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report (part 2)
ae1ed83 verified
Raw History Blame Contribute Delete
11 kB
"""TRACE-VLA v4 — PDF full assembly (TRACE-ARCH-002), arm R6.
TraceVLA3 (PDF core) plus EVERY optional module of the PDF:
- Temporal progress alignment (PDF 8.4): a progress head reads
the live features and estimates live task progress; a progress
token carrying (demo progress anchor, live progress, their
difference, demo time-span width) enters the SYNC memory set.
Trained with an MSE loss against the query frame's normalized
position inside its episode (training-only label).
- SDE (PDF 12): a skill-discovery encoder over the demo frame
encodings — boundary head + soft segment assignment + segment
embeddings, appended to SYNC as an extra token window.
Self-supervised (boundary sparsity + assignment smoothness);
its standalone gates (PDF 12.4 in MD numbering) are NOT run in
this run and it is integrated as a conditioning window only.
- ECHO v2 (PDF 13): action-conditioned world model — predicts
the ANCHOR feature delta from the NEXUS effect features AND
the candidate action chunk (explicit action input, the v2
change). Auxiliary loss only in this run; candidate reranking
(a separate gated integration) is not performed.
- Adaptive execution horizon (PDF 11.2): inference-time rule in
the evaluation policy, driven by the correspondence
confidence (perception-derived phase estimate): conf >= 0.8
-> execute 1 step, >= 0.55 -> 2 steps, else 4 steps before
replanning. No training signal; the rule lives in
df_eval_arms.py (TracePolicyV4.act_h).
- Precision correction head (PDF 11.3): a zero-init residual
head refining the FLUX velocity per action step from
(action features, noisy action, tau); trained end-to-end by
the FLUX loss, active in both training and sampling.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from .echo import echo_loss
from .flux import flux_loss
from .model_v3 import TraceVLA3
LAM_PROG, LAM_SDE = 0.1, 0.1
class SkillDiscoveryV4(nn.Module):
def __init__(self, hidden: int = 256, d_model: int = 512,
n_segments: int = 4):
super().__init__()
self.n_segments = n_segments
self.boundary_head = nn.Sequential(
nn.Linear(hidden, hidden // 2), nn.SiLU(),
nn.Linear(hidden // 2, 1))
self.seg_queries = nn.Parameter(torch.zeros(n_segments, hidden))
self.seg_attn = nn.MultiheadAttention(hidden, 4, batch_first=True)
self.out_proj = nn.Linear(hidden, d_model)
nn.init.normal_(self.seg_queries, std=0.02)
nn.init.zeros_(self.out_proj.weight)
nn.init.zeros_(self.out_proj.bias)
def forward(self, frame_enc: torch.Tensor,
frame_mask: torch.Tensor):
"""frame_enc [B,T,256]. Returns (tokens [B,4,512], loss)."""
b, t, _ = frame_enc.shape
device = frame_enc.device
boundary = torch.sigmoid(
self.boundary_head(frame_enc).squeeze(-1)) # [B,T]
boundary = boundary * frame_mask.to(boundary.dtype)
q = self.seg_queries[None].expand(b, -1, -1)
# Gaussian temporal window bias around fixed centres:
# soft segment assignment with a time prior; the boundary
# head modulates the effective centres through its
# cumulative mass.
pos = torch.linspace(0.0, 1.0, t, device=device)
centres = (torch.arange(self.n_segments, device=device)
.float() + 0.5) / self.n_segments
bias = -((pos[None, None] - centres[None, :, None]) ** 2) \
/ (2 * 0.18 ** 2) # [1,S,T]
seg, attn_w = self.seg_attn(
q, frame_enc, frame_enc,
key_padding_mask=~frame_mask, need_weights=True,
attn_mask=None)
# Recompute assignment with the window bias for the loss
# and use plain attention output as the embedding.
assign = torch.softmax(
attn_w + bias.expand(b, -1, -1), dim=-1)
smooth = (assign[:, :, 1:] - assign[:, :, :-1]).abs().mean()
sparsity = (boundary.mean(dim=1)
- 3.0 / max(t, 1)).pow(2).mean()
loss = sparsity + 0.1 * smooth
tokens = self.out_proj(seg) # [B,S,512]
return tokens, loss
class EchoV2(nn.Module):
"""Action-conditioned feature-delta predictor (PDF 13).
Same output contract as the v1 Echo head: a per-patch
residual map [B, 64, D] over the pooled grid of the main
camera, in a 512-dim space reached through a FIXED (buffer,
non-trainable) target projection, exactly like the v1 512
variant. The v2 change: the prediction is conditioned on the
candidate action chunk as an explicit input, fused with the
pooled NEXUS effect features; a shared per-patch head keeps
the parameter count small.
"""
def __init__(self, d_model: int = 512, vision_width: int = 768,
chunk: int = 16, action_dim: int = 7,
n_patches: int = 64):
super().__init__()
gen = torch.Generator().manual_seed(1234)
proj = torch.randn(vision_width, d_model, generator=gen) \
/ (vision_width ** 0.5)
self.register_buffer("fixed_target_proj", proj)
self.fuse = nn.Sequential(
nn.Linear(d_model + chunk * action_dim, d_model),
nn.SiLU())
self.patch_emb = nn.Parameter(torch.zeros(n_patches, d_model))
self.head = nn.Linear(d_model, d_model)
nn.init.normal_(self.patch_emb, std=0.02)
def forward(self, eff_feat: torch.Tensor,
action_chunk: torch.Tensor) -> torch.Tensor:
if eff_feat.dim() == 3:
eff_feat = eff_feat.mean(dim=1)
x = torch.cat([eff_feat,
action_chunk.flatten(1).to(eff_feat.dtype)],
dim=-1)
fused = self.fuse(x) # [B,512]
per_patch = fused.unsqueeze(1) + self.patch_emb[None]
return self.head(per_patch) # [B,64,512]
def project_target(self, target: torch.Tensor) -> torch.Tensor:
return target @ self.fixed_target_proj
class PrecisionHead(nn.Module):
def __init__(self, d_model: int = 512, action_dim: int = 7):
super().__init__()
self.mlp = nn.Sequential(
nn.Linear(d_model + action_dim + 1, 256), nn.SiLU(),
nn.Linear(256, action_dim))
nn.init.zeros_(self.mlp[-1].weight)
nn.init.zeros_(self.mlp[-1].bias)
def forward(self, act_feat, a_tau, tau):
tau_e = tau.view(-1, 1, 1).expand(-1, a_tau.shape[1], 1)
x = torch.cat([act_feat, a_tau, tau_e.to(act_feat.dtype)],
dim=-1)
return self.mlp(x)
class TraceVLA4(TraceVLA3):
def __init__(self, cfg, load_anchor: bool = True):
super().__init__(cfg, load_anchor=load_anchor)
d = cfg.d_model
self.progress_head = nn.Sequential(
nn.Linear(cfg.vision_width + cfg.state_dim, 256),
nn.SiLU(), nn.Linear(256, 1))
self.progress_token = nn.Sequential(
nn.Linear(4, 128), nn.SiLU(), nn.Linear(128, d))
nn.init.zeros_(self.progress_token[-1].weight)
nn.init.zeros_(self.progress_token[-1].bias)
self.sde = SkillDiscoveryV4(hidden=256, d_model=d)
self.echo2 = EchoV2(d_model=d, vision_width=cfg.vision_width,
chunk=cfg.chunk, action_dim=cfg.action_dim)
self.precision = PrecisionHead(d_model=d,
action_dim=cfg.action_dim)
# -- context with all token windows --------------------------------
def compute_context_v4(self, pooled_live, text_emb, state_norm,
history, demo_pooled=None, frame_mask=None,
frame_times=None, cand_mask=None,
cand_valid=None):
demo_memory = window_mask = None
if demo_pooled is not None:
demo_memory, window_mask, _ = self.v1.encode_demo(
demo_pooled, frame_mask, frame_times)
aux = None
windows = []
if demo_pooled is not None and cand_mask is not None:
tokens, e_demo, corr = self.object_condition(
demo_pooled, frame_mask, pooled_live, cand_mask,
cand_valid)
windows.append(tokens.unsqueeze(1))
# Temporal progress alignment.
live_mean = pooled_live.float().mean(dim=(1, 2))
p_live = torch.sigmoid(self.progress_head(
torch.cat([live_mean, state_norm.float()],
dim=-1))).squeeze(-1) # [B]
span = e_demo["time_span"] # [B,2]
prog_in = torch.stack([span[:, 0], p_live,
span[:, 0] - p_live, span[:, 1]],
dim=-1)
prog_tok = self.progress_token(prog_in) # [B,512]
nulls = torch.zeros_like(prog_tok).unsqueeze(1) \
.expand(-1, 3, -1)
windows.append(torch.cat(
[prog_tok.unsqueeze(1), nulls], dim=1).unsqueeze(1))
# SDE window.
sde_tokens, sde_loss = self.sde(e_demo["frame_enc"],
frame_mask)
windows.append(sde_tokens.unsqueeze(1))
aux = {"binding": e_demo, "correspondence": corr,
"object_tokens": tokens, "p_live": p_live,
"sde_loss": sde_loss}
if windows and demo_memory is not None:
demo_memory = torch.cat([demo_memory] + windows, dim=1)
ones = torch.ones(window_mask.shape[0], len(windows),
dtype=torch.bool,
device=window_mask.device)
window_mask = torch.cat([window_mask, ones], dim=1)
context = self.v1.compute_context(
pooled_live, text_emb, state_norm, history,
demo_memory=demo_memory, window_mask=window_mask)
return context, aux
# -- velocity with precision correction -----------------------------
def _velocity_v4(self, context, noisy_actions, tau):
tokens = self.v1.flux.action_tokens(noisy_actions, tau)
act_feat, eff_feat = self.v1.nexus(tokens, context)
v = self.v1.flux.velocity(act_feat)
return v + self.precision(act_feat, noisy_actions, tau), \
eff_feat
def sample_actions(self, context, batch_size, device,
generator=None):
cfg = self.cfg
a = torch.randn(batch_size, cfg.chunk, cfg.action_dim,
device=device, generator=generator)
steps = cfg.euler_steps
for j in range(steps):
tau = torch.full((batch_size,), j / steps, device=device)
v, _ = self._velocity_v4(context, a, tau)
a = a + (1.0 / steps) * v
return a, None