trace-vla-code / code /sera_v4 /tools /apply_ar_patch.py
phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report
b4396f0 verified
Raw History Blame Contribute Delete
20 kB
#!/usr/bin/env python3
"""sera-vla-v4_1 patch: autoregressive ActionCodec2 head (SPEC in
WORKLOG, locked 2026-11-19 by Young's order; applies on top of the
quest + questfix patches, which must already be applied).
Defaults OFF (v4_ar_enabled=False): every existing arm behaves
exactly as before — the FM path is byte-identical and the AR
modules are constructed but never called.
When enabled, ONLY the action head changes:
- SERAVLAV3Model gains an AR decoder: token embedding (codec vocab
4,096 + PAD/BOS/EOS specials) + positions, 4 causal ARMoEBlocks
(self-attn causal + cross-attn to the trunk context + the SAME
per-sample skillroute routing indices/weights from
encode_observation; FFN = shared SwiGLU + Top-4 of 8 experts,
mirroring MoEBlock), goal FiLM + quest skill FiLM after the
stack (same order as velocity_prediction), final norm, LM head.
- Skill-token injection mirrors the FM head: skill summary added
to the token embeddings pre-blocks; skill FiLM post-stack.
- Policy forward: FM loss is replaced by CE(next token, PAD mask)
+ the mode's balance/specialization terms (control recipe:
0.01 balance + 0.0002 specialization, from the AR blocks'
intermediates); the quest prior-NLL tail is unchanged. Targets
come from the precomputed ActionCodec2 token map keyed by
(episode_index, frame_index); the base/segment variant is chosen
by matching the item's action_is_pad clamping (DATA V2).
- predict_action_chunk: greedy token generation -> official
ActionCodec2 decode (fps 10) -> physical actions -> stored
command space -> MEAN_STD normalization (the space the FM path
returns). FM Euler path untouched when the flag is off.
Exact-match replacements; every count is asserted.
"""
from pathlib import Path
PKG = Path.home() / "lerobot/src/lerobot/policies/sera_vla_v3"
def patch(path: Path, pairs: list[tuple[str, str]]) -> None:
text = path.read_text()
for old, new in pairs:
n = text.count(old)
assert n == 1, f"{path.name}: anchor found {n}x: {old[:70]!r}"
text = text.replace(old, new)
path.write_text(text)
print(f"patched {path.name}: {len(pairs)} replacements")
cfg_pairs = [
(
" v4_questfix_p_gt_override: float = -1.0\n",
" v4_questfix_p_gt_override: float = -1.0\n"
" v4_ar_enabled: bool = False\n"
" v4_ar_vocab: int = 4096\n"
" v4_ar_max_len: int = 96\n",
),
(
" if not -1.0 <= self.v4_questfix_p_gt_override <= 1.0:\n"
" raise ValueError(f\"Invalid v4_questfix_p_gt_override: {self.v4_questfix_p_gt_override}\")\n",
" if not -1.0 <= self.v4_questfix_p_gt_override <= 1.0:\n"
" raise ValueError(f\"Invalid v4_questfix_p_gt_override: {self.v4_questfix_p_gt_override}\")\n"
" if self.v4_ar_enabled and self.v4_moe_mode != \"skillroute\":\n"
" raise ValueError(\"v4_ar_enabled requires v4_moe_mode='skillroute'\")\n"
" if self.v4_ar_vocab <= 0:\n"
" raise ValueError(f\"Invalid v4_ar_vocab: {self.v4_ar_vocab}\")\n"
" if self.v4_ar_max_len <= 0:\n"
" raise ValueError(f\"Invalid v4_ar_max_len: {self.v4_ar_max_len}\")\n",
),
]
AR_BLOCK = '''
class ARMoEBlock(nn.Module):
"""Causal twin of MoEBlock for the v4_1 AR decoder: causal
self-attention + cross-attention to the trunk context + the
shared/routed SwiGLU MoE FFN with per-sample routing (the
indices/weights produced by encode_observation, exactly as the
FM stack consumes them). Returns (h, z_all) like MoEBlock so
the specialization loss applies unchanged."""
def __init__(self) -> None:
super().__init__()
self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(3)])
self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
self.cross_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True)
self.shared = SwiGLUExpert(1344)
self.experts = nn.ModuleList(SwiGLUExpert(672) for _ in range(8))
def forward(
self, x: Tensor, context: Tensor, indices: Tensor, weights: Tensor,
key_padding: Tensor | None,
) -> tuple[Tensor, Tensor | None]:
n = self.norms[0](x)
L = x.shape[1]
causal = torch.full((L, L), float("-inf"), device=x.device, dtype=x.dtype).triu(1)
x = x + self.self_attn(
n, n, n, attn_mask=causal, key_padding_mask=key_padding, need_weights=False
)[0]
n = self.norms[1](x)
x = x + self.cross_attn(n, context, context, need_weights=False)[0]
u = self.norms[2](x)
shared, _ = self.shared(u)
routed = torch.zeros_like(x)
selected_z: list[Tensor] = []
for batch_index in range(x.shape[0]):
sample_z = []
for slot in range(4):
expert_index = int(indices[batch_index, slot])
output, z = self.experts[expert_index](u[batch_index:batch_index + 1])
routed[batch_index:batch_index + 1] += weights[batch_index, slot] * output
sample_z.append(z)
selected_z.append(torch.stack(sample_z, dim=2))
z_all = torch.cat(selected_z, dim=0) if selected_z else None
return x + shared + routed, z_all
'''
AR_INIT = '''
# sera-vla-v4_1: autoregressive ActionCodec2 head. Constructed
# always (defaults-off keeps every FM arm exact); used only
# when config.v4_ar_enabled is true.
_ar_vocab = int(getattr(config, "v4_ar_vocab", 4096))
self.ar_embed = nn.Embedding(_ar_vocab + 3, 512, padding_idx=_ar_vocab)
self.ar_pos = nn.Parameter(torch.zeros(128, 512))
nn.init.normal_(self.ar_pos, std=0.02)
self.ar_blocks = nn.ModuleList(ARMoEBlock() for _ in range(4))
self.ar_head = nn.Linear(512, _ar_vocab + 3)
for _m in (self.ar_embed, self.ar_blocks, self.ar_head):
_m.apply(_init_new)
self._acodec2_table: dict | None = None
self._acodec2_offset: int = 4096
self._acodec2_codec_obj = None
self._acodec2_mean: Tensor | None = None
self._acodec2_std: Tensor | None = None
'''
AR_METHODS = '''
# ---- sera-vla-v4_1: ActionCodec2 token targets + AR head ----
def _acodec2_load(self) -> None:
if self._acodec2_table is not None:
return
import os
import numpy as np
path = os.environ.get(
"SERA_ACODEC2_MAP",
os.path.expanduser("~/sera_v4_experiments/quest_probe/acodec2_map.npz"),
)
m = np.load(path)
self._acodec2_table = {
k: torch.from_numpy(m[k])
for k in ("tok_base_ids", "tok_base_len", "tok_seg_ids",
"tok_seg_len", "ep_len")
}
self._acodec2_offset = int(m["id_offset"])
def acodec2_tokens_for(self, batch: dict, valid_len: Tensor):
"""Token targets for the batch anchors from the precomputed
map. The base variant (window clamped at the episode end)
matches an item iff its non-pad step count equals
min(16, ep_len - frame); DATA V2 segment items clamp at the
segment end instead and take the segment variant. The two
variants coincide whenever the clamping coincides."""
self._acodec2_load()
t = self._acodec2_table
ep = batch["episode_index"].long().cpu()
fr = batch["frame_index"].long().cpu()
ep_valid = (t["ep_len"][ep] - fr).clamp(0, 16)
use_seg = valid_len.long().cpu() != ep_valid
ids = torch.where(use_seg[:, None], t["tok_seg_ids"][ep, fr],
t["tok_base_ids"][ep, fr])
lens = torch.where(use_seg, t["tok_seg_len"][ep, fr],
t["tok_base_len"][ep, fr])
return ids.long(), lens.long()
def ar_forward(self, context, state, indices, weights, input_ids, key_padding):
cfg = self.config
if input_ids.shape[1] > self.ar_pos.shape[0]:
raise ValueError(f"AR sequence {input_ids.shape[1]} exceeds positions")
h = self.ar_embed(input_ids) + self.ar_pos[None, : input_ids.shape[1]] + state[:, None]
quest_on = getattr(cfg, "v4_quest_enabled", False)
if quest_on:
if self.last_skill_summary is None:
self.set_skill_from_prior()
h = h + self.last_skill_summary[:, None]
intermediates = []
for layer, block in enumerate(self.ar_blocks):
h, z = block(h, context, indices[layer], weights[layer], key_padding)
intermediates.append(z)
if cfg.goal_mode in ("action_only", "router_and_action"):
if self.last_goal is None:
raise RuntimeError("encode_observation must precede ar_forward")
gamma, beta = self.dual_action(self.last_goal.mean(1)).chunk(2, dim=-1)
h = h + gamma[:, None] * self.final_norm(h) + beta[:, None]
if quest_on:
gamma_s, beta_s = self.skill_film(self.last_skill_summary).chunk(2, dim=-1)
h = h + gamma_s[:, None] * self.final_norm(h) + beta_s[:, None]
return self.ar_head(self.final_norm(h)), intermediates
@torch.no_grad()
def ar_predict_chunk(self, context, state, indices, weights):
"""Greedy AR decode constrained by the codec grammar
(grammar(16, fps=10).next_token_mask), then the official
streaming decoder. Returns normalized actions [B, 16, 7]."""
cfg = self.config
codec = self._acodec2_codec()
grammar = codec.grammar(16, fps=10)
offset = self._acodec2_offset()
vocab = int(cfg.v4_ar_vocab)
max_len = int(cfg.v4_ar_max_len)
bsz = context.shape[0]
dev = context.device
prefixes: list[list[int]] = [[] for _ in range(bsz)]
done = [False] * bsz
for _ in range(max_len):
if all(done):
break
seqs = []
for r in range(bsz):
seqs.append([vocab + 1] + [t - offset for t in prefixes[r]])
width = max(len(s) for s in seqs)
ids = torch.full((bsz, width), vocab, dtype=torch.long)
for r, s in enumerate(seqs):
ids[r, :len(s)] = torch.tensor(s, dtype=torch.long)
ids = ids.to(dev)
pad = ids == vocab
logits = self.ar_forward(context, state, indices, weights,
ids, pad)
for r in range(bsz):
if done[r]:
continue
mask = grammar.next_token_mask(prefixes[r])
allowed = torch.as_tensor(mask, device=dev)[offset:offset + vocab]
row_logits = logits[r, len(seqs[r]) - 1, :vocab].clone()
row_logits[~allowed] = float("-inf")
nxt = int(row_logits.argmax().item())
if not bool(allowed[nxt]):
done[r] = True
continue
prefixes[r].append(nxt + offset)
if grammar.is_complete(prefixes[r]):
done[r] = True
rows = []
for r in range(bsz):
pref = prefixes[r]
while pref and not grammar.is_prefix_complete(pref):
pref = pref[:-1]
rows.append(pref)
return self._acodec2_decode(rows, dev, context.dtype)
def _acodec2_decode(self, seqs, device, dtype):
import os
import numpy as np
if self._acodec2_codec_obj is None:
from transformers import AutoProcessor
path = os.environ.get(
"SERA_ACODEC2_TOKENIZER",
os.path.expanduser(
"~/sera_v4_experiments/quest_probe/acodec2_tokenizer"),
)
self._acodec2_codec_obj = AutoProcessor.from_pretrained(
path, action_space="single_eef_delta", trust_remote_code=True
)
spath = os.environ.get(
"SERA_ACODEC2_STATS",
os.path.expanduser(
"~/sera_v4_experiments/quest_probe/acodec2_action_stats.npz"),
)
st = np.load(spath)
self._acodec2_mean = torch.tensor(st["mean"], dtype=torch.float32)
self._acodec2_std = torch.tensor(st["std"], dtype=torch.float32)
self._acodec2_load()
codec = self._acodec2_codec
chunks = []
for s in seqs:
if len(s) == 0:
phys = np.zeros((0, 7), dtype=np.float32)
else:
raw = [[t + self._acodec2_offset for t in s]]
phys = np.asarray(codec.decode(raw, fps=10), dtype=np.float32)[0]
if len(phys) < 16:
tail = (np.repeat(phys[-1:], 16 - len(phys), axis=0)
if len(phys) else np.zeros((16 - len(phys), 7), np.float32))
phys = np.concatenate([phys, tail], 0)
phys = phys[:16]
stored = np.empty_like(phys)
stored[:, 0:3] = phys[:, 0:3] / 0.05
stored[:, 3:6] = phys[:, 3:6] / 0.5
stored[:, 6] = np.where(phys[:, 6] > 0.5, -1.0, 1.0)
chunks.append(stored)
arr = torch.tensor(np.stack(chunks), dtype=torch.float32, device=device)
mean = self._acodec2_mean.to(device)
std = self._acodec2_std.to(device)
return ((arr - mean) / std).to(dtype)
'''
v3_pairs = [
(
"from .modeling_base import SERAVLAModel, SERAVLAPolicy",
"from .modeling_base import SERAVLAModel, SERAVLAPolicy, SwiGLUExpert, _init_new",
),
(
"class SERAVLAV3Model(SERAVLAModel):",
AR_BLOCK.strip("\n") + "\n\n\nclass SERAVLAV3Model(SERAVLAModel):",
),
(
" self.register_buffer(\"skill_decode_table\", (_ks - _half) / _half)\n",
" self.register_buffer(\"skill_decode_table\", (_ks - _half) / _half)\n"
+ AR_INIT,
),
(
" def encode_observation(self, images: Tensor, instructions: Sequence[str], state_raw: Tensor):",
AR_METHODS.strip("\n")
+ "\n\n def encode_observation(self, images: Tensor, instructions: Sequence[str], state_raw: Tensor):",
),
]
FM_BLOCK = ''' noise = torch.randn_like(action)
tau = torch.rand(action.shape[0], device=action.device, dtype=action.dtype)
x_tau = (1 - tau[:, None, None]) * noise + tau[:, None, None] * action
prediction, intermediates = self.model.velocity_prediction(
x_tau, tau, context, state, indices, weights, ~valid
)
target = action - noise
fm = ((prediction - target).square() * valid[..., None]).sum() / (
self.config.action_dim * valid.sum()
).clamp_min(1)
balance = self._balance_loss(probabilities, indices)
specialization = self._specialization_loss(intermediates, valid)
v4_mode = getattr(self.config, "v4_moe_mode", "control")
if v4_mode == "nobal":
total = fm
elif v4_mode == "bias":
total = fm + 0.0002 * specialization
else:
total = fm + 0.01 * balance + 0.0002 * specialization
metrics = {
"flow_matching_loss": fm.item(),
"balance_loss": balance.item(),
"specialization_loss": specialization.item(),
}
'''
AR_BRANCH = ''' v4_mode = getattr(self.config, "v4_moe_mode", "control")
if getattr(self.config, "v4_ar_enabled", False):
# sera-vla-v4_1: CE over ActionCodec2 tokens replaces FM.
valid_len = valid.long().sum(1)
tok_ids, tok_lens = self.model.acodec2_tokens_for(batch, valid_len)
vocab = int(getattr(self.config, "v4_ar_vocab", 4096))
pad_id, bos_id, eos_id = vocab, vocab + 1, vocab + 2
bsz = tok_ids.shape[0]
maxlen = int(tok_lens.max().item())
dev = action.device
lens_dev = tok_lens.to(dev)
pos = torch.arange(maxlen, device=dev)[None, :]
body = torch.where(
pos < lens_dev[:, None],
tok_ids.to(dev)[:, :maxlen],
torch.full((bsz, maxlen), pad_id, dtype=torch.long, device=dev),
)
full = torch.full((bsz, maxlen + 2), pad_id, dtype=torch.long, device=dev)
full[:, 0] = bos_id
full[:, 1:1 + maxlen] = body
full.scatter_(1, (1 + lens_dev)[:, None], eos_id)
input_ids = full[:, :-1]
target = full[:, 1:]
logits, intermediates = self.model.ar_forward(
context, state, indices, weights, input_ids, input_ids == pad_id
)
tmask = target != pad_id
ce = F.cross_entropy(
logits.float().reshape(-1, vocab + 3), target.reshape(-1),
ignore_index=pad_id, reduction="sum",
) / tmask.sum().clamp_min(1)
balance = self._balance_loss(probabilities, indices)
specialization = self._specialization_loss(
intermediates, input_ids != pad_id)
if v4_mode == "nobal":
total = ce
elif v4_mode == "bias":
total = ce + 0.0002 * specialization
else:
total = ce + 0.01 * balance + 0.0002 * specialization
with torch.no_grad():
acc = ((logits.argmax(-1) == target) & tmask).float().sum() \\
/ tmask.sum().clamp_min(1)
metrics = {
"ar_ce": ce.item(),
"ar_acc": float(acc),
"ar_tokens_mean": float(tok_lens.float().mean()),
"balance_loss": balance.item(),
"specialization_loss": specialization.item(),
}
else:
noise = torch.randn_like(action)
tau = torch.rand(action.shape[0], device=action.device, dtype=action.dtype)
x_tau = (1 - tau[:, None, None]) * noise + tau[:, None, None] * action
prediction, intermediates = self.model.velocity_prediction(
x_tau, tau, context, state, indices, weights, ~valid
)
target = action - noise
fm = ((prediction - target).square() * valid[..., None]).sum() / (
self.config.action_dim * valid.sum()
).clamp_min(1)
balance = self._balance_loss(probabilities, indices)
specialization = self._specialization_loss(intermediates, valid)
if v4_mode == "nobal":
total = fm
elif v4_mode == "bias":
total = fm + 0.0002 * specialization
else:
total = fm + 0.01 * balance + 0.0002 * specialization
metrics = {
"flow_matching_loss": fm.item(),
"balance_loss": balance.item(),
"specialization_loss": specialization.item(),
}
'''
base_pairs = [
(FM_BLOCK, AR_BRANCH),
(
" if getattr(self.config, \"v4_quest_enabled\", False):\n"
" self.model.set_skill_from_prior()\n"
" x = torch.randn(images.shape[0], 16, self.config.action_dim, device=images.device, dtype=state.dtype)",
" if getattr(self.config, \"v4_quest_enabled\", False):\n"
" self.model.set_skill_from_prior()\n"
" if getattr(self.config, \"v4_ar_enabled\", False):\n"
" return self.model.ar_predict_chunk(context, state, indices, weights)\n"
" x = torch.randn(images.shape[0], 16, self.config.action_dim, device=images.device, dtype=state.dtype)",
),
]
patch(PKG / "configuration_sera_vla_v3.py", cfg_pairs)
patch(PKG / "modeling_sera_vla_v3.py", v3_pairs)
patch(PKG / "modeling_base.py", base_pairs)
print("ar patch applied")