from __future__ import annotations import os from collections import deque from collections.abc import Sequence import torch import torch.nn.functional as F # noqa: N812 from torch import Tensor, nn from lerobot.policies.pretrained import PreTrainedPolicy from lerobot.utils.constants import ACTION, OBS_LANGUAGE, OBS_STATE from .configuration_base import SERAVLAConfig def _init_new(module: nn.Module) -> None: if isinstance(module, nn.Linear): nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.LayerNorm): nn.init.ones_(module.weight) nn.init.zeros_(module.bias) class FusionBlock(nn.Module): def __init__(self) -> None: super().__init__() self.norms = nn.ModuleList([nn.LayerNorm(512, eps=1e-5) for _ in range(4)]) self.text_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True) self.vision_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True) self.self_attn = nn.MultiheadAttention(512, 8, dropout=0.0, bias=True, batch_first=True) self.ffn = nn.Sequential(nn.Linear(512, 2048), nn.GELU(), nn.Linear(2048, 512)) self.capture_vision_attention = False self.last_vision_attention: Tensor | None = None def forward(self, q: Tensor, text: Tensor, vision: Tensor, text_padding: Tensor) -> Tensor: x = self.norms[0](q) q = q + self.text_attn(x, text, text, key_padding_mask=text_padding, need_weights=False)[0] x = self.norms[1](q) if self.capture_vision_attention: vision_out, attention = self.vision_attn( x, vision, vision, need_weights=True, average_attn_weights=False ) self.last_vision_attention = attention.detach() q = q + vision_out else: self.last_vision_attention = None q = q + self.vision_attn(x, vision, vision, need_weights=False)[0] x = self.norms[2](q) q = q + self.self_attn(x, x, x, need_weights=False)[0] return q + self.ffn(self.norms[3](q)) class SwiGLUExpert(nn.Module): def __init__(self, width: int) -> None: super().__init__() self.gate = nn.Linear(512, width, bias=False) self.up = nn.Linear(512, width, bias=False) self.down = nn.Linear(width, 512, bias=False) def forward(self, x: Tensor) -> tuple[Tensor, Tensor]: z = F.silu(self.gate(x)) * self.up(x) return self.down(z), z class MoEBlock(nn.Module): 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)) self.ortho_outputs = False @staticmethod def _orthogonalize(stacked: Tensor) -> Tensor: # Round-2 arm H: stacked [B, T, K, D] selected expert outputs -> # per (b, t) an orthonormal set (Gram-Schmidt via QR of O^T, # sign-stabilized by diag(R)), rescaled by the mean original # vector norm so the routed output scale is preserved. o = stacked.float() norms = o.norm(dim=-1) scale = norms.mean(dim=-1, keepdim=True) q, r = torch.linalg.qr(o.transpose(-1, -2)) signs = torch.sign(torch.diagonal(r, dim1=-2, dim2=-1)) signs = torch.where(signs == 0, torch.ones_like(signs), signs) q = q * signs[:, :, None, :] return (q.transpose(-1, -2) * scale[..., None]).to(stacked.dtype) def forward( self, x: Tensor, context: Tensor, indices: Tensor, weights: Tensor, action_padding: Tensor | None ) -> tuple[Tensor, Tensor | None]: n = self.norms[0](x) x = x + self.self_attn(n, n, n, key_padding_mask=action_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] = [] selected_out: list[Tensor] = [] for batch_index in range(x.shape[0]): sample_z = [] sample_out = [] for slot in range(4): expert_index = int(indices[batch_index, slot]) output, z = self.experts[expert_index](u[batch_index : batch_index + 1]) if self.ortho_outputs: sample_out.append(output) else: routed[batch_index : batch_index + 1] += weights[batch_index, slot] * output sample_z.append(z) if self.ortho_outputs: selected_out.append(torch.stack(sample_out, dim=2)) selected_z.append(torch.stack(sample_z, dim=2)) if self.ortho_outputs: stacked = torch.cat(selected_out, dim=0) # [B,16,4,512] ortho = self._orthogonalize(stacked) routed = (ortho * weights[:, None, :, None].to(ortho.dtype)).sum(2) z_all = torch.cat(selected_z, dim=0) if selected_z else None # [B,16,4,672] return x + shared + routed, z_all class SERAVLAModel(nn.Module): def __init__(self, config: SERAVLAConfig) -> None: super().__init__() from transformers import AutoModel self.config = config self.tips = AutoModel.from_pretrained( config.backbone_id, trust_remote_code=True, local_files_only=config.local_files_only ) self.vision_projection = nn.Linear(768, 512) self.vision_norm = nn.LayerNorm(512, eps=1e-5) self.camera_embeddings = nn.Parameter(torch.empty(2, 512)) self.text_projection = nn.Linear(768, 512) self.text_norm = nn.LayerNorm(512, eps=1e-5) self.queries = nn.Parameter(torch.empty(64, 512)) self.fusion = nn.ModuleList(FusionBlock() for _ in range(3)) self.fusion_norm = nn.LayerNorm(512, eps=1e-5) self.state_mlp = nn.Sequential( nn.Linear(config.state_dim, 512), nn.SiLU(), nn.Linear(512, 512), nn.LayerNorm(512, eps=1e-5) ) router_in_features = 1536 if getattr(config, "v4_moe_mode", "control") == "skillroute" else 1024 self.routers = nn.ModuleList(nn.Linear(router_in_features, 8, bias=False) for _ in range(4)) self.register_buffer("router_bias", torch.zeros(4, 8)) self.register_buffer("router_load_ema", torch.full((4, 8), 0.5)) self.action_projection = nn.Linear(config.action_dim, 512) self.action_positions = nn.Parameter(torch.empty(16, 512)) self.time_mlp = nn.Sequential(nn.Linear(512, 512), nn.SiLU(), nn.Linear(512, 512)) self.blocks = nn.ModuleList(MoEBlock() for _ in range(4)) if getattr(config, "v4_ortho_outputs", False): for _blk in self.blocks: _blk.ortho_outputs = True self.final_norm = nn.LayerNorm(512, eps=1e-5) self.velocity = nn.Linear(512, config.action_dim) for name, module in self.named_children(): if name != "tips": module.apply(_init_new) nn.init.normal_(self.camera_embeddings, std=0.02) nn.init.normal_(self.queries, std=0.02) nn.init.normal_(self.action_positions, std=0.02) self._configure_tips_finetuning() self.tips.eval() self.capture_diagnostics = False self.last_diagnostics: dict[str, Tensor] | None = None def set_diagnostics_enabled(self, enabled: bool) -> None: """Expose inference-only routing and cross-attention telemetry for visual evaluation.""" self.capture_diagnostics = enabled self.last_diagnostics = None for block in self.fusion: block.capture_vision_attention = enabled def train(self, mode: bool = True): super().train(mode) # Evaluation mode avoids changing the frozen backbone's behavior via # dropout/drop-path. Gradients for the selected last blocks still work # in eval mode, and only those blocks have trainable parameters. self.tips.eval() return self @property def _finetunes_vision(self) -> bool: return self.config.finetune_vision_last_n_layers > 0 @property def _finetunes_language(self) -> bool: return self.config.finetune_language_last_n_layers > 0 @staticmethod def _last_transformer_blocks(module: nn.Module, attribute: str, count: int) -> list[nn.Module]: """Return the final ``count`` blocks, rejecting an incompatible TIPS revision.""" blocks = getattr(module, attribute, None) if not isinstance(blocks, (nn.ModuleList, nn.Sequential)): raise RuntimeError(f"Unsupported TIPSv2 {attribute} container: {type(blocks).__name__}") if count > len(blocks): raise ValueError(f"Requested {count} TIPSv2 blocks, but only {len(blocks)} are available") return list(blocks[-count:]) if count else [] def _configure_tips_finetuning(self) -> None: """Freeze TIPSv2, then selectively unfreeze its final transformer blocks. Embeddings, patch projection, positional embeddings, and output norms remain frozen. This is deliberately conservative to preserve pretrained features. """ self.tips.requires_grad_(False) if self._finetunes_vision: if getattr(self.tips.vision_encoder, "chunked_blocks", False): raise RuntimeError("Partial TIPSv2 fine-tuning requires unchunked vision blocks") for block in self._last_transformer_blocks( self.tips.vision_encoder, "blocks", self.config.finetune_vision_last_n_layers ): block.requires_grad_(True) if self._finetunes_language: transformer = getattr(self.tips.text_encoder, "transformer", None) if not isinstance(transformer, nn.Module): raise RuntimeError("Unsupported TIPSv2 text encoder: missing transformer") for block in self._last_transformer_blocks( transformer, "resblocks", self.config.finetune_language_last_n_layers ): block.requires_grad_(True) def _tokenize(self, instructions: Sequence[str], device: torch.device) -> tuple[Tensor, Tensor]: if self.tips._tokenizer is None: self.tips._tokenizer = self.tips._load_tokenizer() lengths = [ len(self.tips._tokenizer.sp.encode(text.lower(), add_bos=False, add_eos=False)) for text in instructions ] if any(length > 64 for length in lengths): raise ValueError(f"TIPSv2 instruction exceeds 64 tokens: lengths={lengths}") ids, padding = self.tips._tokenizer.tokenize(list(instructions), max_len=64) return torch.as_tensor(ids, device=device), torch.as_tensor(padding, device=device, dtype=torch.bool) def _encode_text_tokens(self, ids: Tensor, padding: Tensor) -> Tensor: encoder = self.tips.text_encoder # Do not call TIPSv2's convenience methods here: they are decorated # with no_grad(). Keep the frozen path cheap while allowing gradients # through explicitly selected final language blocks. with torch.set_grad_enabled(torch.is_grad_enabled() and self.training and self._finetunes_language): mask = (padding == 0).float().permute(1, 0) x = encoder.token_embedding(ids) * (encoder.embedding_dim**0.5) x = x + encoder.pos_embedder(seq_length=ids.shape[1]).to(x.device) x = encoder.transformer(x.permute(1, 0, 2), mask).permute(1, 0, 2) return encoder.ln_final(x) def encode_observation(self, images: Tensor, instructions: Sequence[str], state_raw: Tensor): b = images.shape[0] # TIPSv2.encode_image itself is no_grad(), so invoke the vision tower # directly when its final blocks are being adapted. with torch.set_grad_enabled(torch.is_grad_enabled() and self.training and self._finetunes_vision): if self._finetunes_vision: cls_token, register_tokens, patch_tokens = self.tips.vision_encoder(images.flatten(0, 1)) else: output = self.tips.encode_image(images.flatten(0, 1)) cls_token, register_tokens, patch_tokens = ( output.cls_token, output.register_tokens, output.patch_tokens, ) raw = torch.cat([cls_token, register_tokens, patch_tokens], dim=1) raw = raw.view(b, 2, 1026, 768) vision = self.vision_norm( self.vision_projection(raw) + self.camera_embeddings[None, :, None] ).flatten(1, 2) ids, padding = self._tokenize(instructions, images.device) text = self.text_norm(self.text_projection(self._encode_text_tokens(ids, padding))) context = self.queries.unsqueeze(0).expand(b, -1, -1) for block in self.fusion: context = block(context, text, vision, padding) context = self.fusion_norm(context) state = self.state_mlp(state_raw) router_input = torch.cat([context.mean(1), state], dim=-1) probabilities, indices, weights = [], [], [] for router in self.routers: p = router(router_input).softmax(-1) w, i = p.topk(4, dim=-1) probabilities.append(p) indices.append(i) weights.append(w) if self.capture_diagnostics: attention = [block.last_vision_attention for block in self.fusion] if all(item is not None for item in attention): # [fusion layer, B, head, query, vision token] → [B, vision token]. vision_attention = torch.stack([item for item in attention if item is not None]).mean( (0, 2, 3) ) self.last_diagnostics = { "router_probabilities": torch.stack(probabilities, dim=1).detach(), "router_indices": torch.stack(indices, dim=1).detach(), "router_weights": torch.stack(weights, dim=1).detach(), "vision_attention": vision_attention.detach(), } return context, state, probabilities, indices, weights @staticmethod def time_embedding(tau: Tensor) -> Tensor: i = torch.arange(256, device=tau.device, dtype=torch.float32) omega = 10000.0 ** (-2 * i / 512) angles = tau.float().unsqueeze(-1) * omega return torch.cat([angles.sin(), angles.cos()], dim=-1) def velocity_prediction( self, x: Tensor, tau: Tensor, context: Tensor, state: Tensor, indices: list[Tensor], weights: list[Tensor], action_padding: Tensor | None = None, ): h = ( self.action_projection(x) + self.action_positions[None] + self.time_mlp(self.time_embedding(tau))[:, None] + state[:, None] ) intermediates = [] for layer, block in enumerate(self.blocks): h, z = block(h, context, indices[layer], weights[layer], action_padding) intermediates.append(z) return self.velocity(self.final_norm(h)), intermediates # Round-2 arm I: verb/object factors parsed from the templated LIBERO # task names (SPEC round2_probe/SPEC.md). Keys are the exact dataset # instruction strings; values are (verb set, manipulated-object set). _TASK_FACTORS: dict[str, tuple[frozenset, frozenset]] = { "put the white mug on the left plate and put the yellow and white mug on the right plate": (frozenset({"put"}), frozenset({"white mug", "yellow and white mug"})), "put the white mug on the plate and put the chocolate pudding to the right of the plate": (frozenset({"put"}), frozenset({"white mug", "chocolate pudding"})), "put the yellow and white mug in the microwave and close it": (frozenset({"put", "close"}), frozenset({"yellow and white mug"})), "turn on the stove and put the moka pot on it": (frozenset({"turn_on", "put"}), frozenset({"moka pot"})), "put both the alphabet soup and the cream cheese box in the basket": (frozenset({"put"}), frozenset({"alphabet soup", "cream cheese box"})), "put both the alphabet soup and the tomato sauce in the basket": (frozenset({"put"}), frozenset({"alphabet soup", "tomato sauce"})), "put both moka pots on the stove": (frozenset({"put"}), frozenset({"moka pot"})), "put both the cream cheese box and the butter in the basket": (frozenset({"put"}), frozenset({"cream cheese box", "butter"})), "put the black bowl in the bottom drawer of the cabinet and close it": (frozenset({"put", "close"}), frozenset({"black bowl"})), "pick up the book and place it in the back compartment of the caddy": (frozenset({"pick_up"}), frozenset({"book"})), "put the bowl on the plate": (frozenset({"put"}), frozenset({"bowl"})), "put the wine bottle on the rack": (frozenset({"put"}), frozenset({"wine bottle"})), "open the top drawer and put the bowl inside": (frozenset({"open", "put"}), frozenset({"bowl"})), "put the cream cheese in the bowl": (frozenset({"put"}), frozenset({"cream cheese"})), "put the wine bottle on top of the cabinet": (frozenset({"put"}), frozenset({"wine bottle"})), "push the plate to the front of the stove": (frozenset({"push"}), frozenset({"plate"})), "turn on the stove": (frozenset({"turn_on"}), frozenset({"stove"})), "put the bowl on the stove": (frozenset({"put"}), frozenset({"bowl"})), "put the bowl on top of the cabinet": (frozenset({"put"}), frozenset({"bowl"})), "open the middle drawer of the cabinet": (frozenset({"open"}), frozenset({"drawer"})), "pick up the orange juice and place it in the basket": (frozenset({"pick_up"}), frozenset({"orange juice"})), "pick up the ketchup and place it in the basket": (frozenset({"pick_up"}), frozenset({"ketchup"})), "pick up the cream cheese and place it in the basket": (frozenset({"pick_up"}), frozenset({"cream cheese"})), "pick up the bbq sauce and place it in the basket": (frozenset({"pick_up"}), frozenset({"bbq sauce"})), "pick up the alphabet soup and place it in the basket": (frozenset({"pick_up"}), frozenset({"alphabet soup"})), "pick up the milk and place it in the basket": (frozenset({"pick_up"}), frozenset({"milk"})), "pick up the salad dressing and place it in the basket": (frozenset({"pick_up"}), frozenset({"salad dressing"})), "pick up the butter and place it in the basket": (frozenset({"pick_up"}), frozenset({"butter"})), "pick up the tomato sauce and place it in the basket": (frozenset({"pick_up"}), frozenset({"tomato sauce"})), "pick up the chocolate pudding and place it in the basket": (frozenset({"pick_up"}), frozenset({"chocolate pudding"})), "pick up the black bowl next to the cookie box and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl in the top drawer of the wooden cabinet and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl on the ramekin and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl on the stove and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl between the plate and the ramekin and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl on the cookie box and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl next to the plate and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl next to the ramekin and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl from table center and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), "pick up the black bowl on the wooden cabinet and place it on the plate": (frozenset({"pick_up"}), frozenset({"black bowl"})), } def _jaccard(a: frozenset, b: frozenset) -> float: if not a and not b: return 0.0 return len(a & b) / len(a | b) def _factor_weights(language: Sequence[str], device: torch.device) -> Tensor: """Pair weights w_ij = 0.5*Jaccard(verbs) + 0.5*Jaccard(objects), zero diagonal. Unknown instructions fall back to their first token as the verb and no object (never happens on LIBERO).""" verb_sets, obj_sets = [], [] for s in language: v, o = _TASK_FACTORS.get(s, (frozenset({s.split()[0] if s.split() else "unknown"}), frozenset())) verb_sets.append(v) obj_sets.append(o) b = len(language) w = torch.zeros(b, b) for i in range(b): for j in range(b): if i != j: w[i, j] = 0.5 * _jaccard(verb_sets[i], verb_sets[j]) + 0.5 * _jaccard(obj_sets[i], obj_sets[j]) return w.to(device) class SERAVLAPolicy(PreTrainedPolicy): config_class = SERAVLAConfig name = "sera_vla" _fsdp_wrap_modules = ["FusionBlock", "MoEBlock"] def __init__(self, config: SERAVLAConfig, **kwargs) -> None: super().__init__(config) config.validate_features() self.config = config self.model = SERAVLAModel(config) self.reset() def get_optim_params(self): # The backbone gets a smaller LR than the newly initialized SERA heads. # Exclude frozen tensors from optimizer state entirely. backbone, other = [], [] for name, parameter in self.named_parameters(): if not parameter.requires_grad: continue (backbone if name.startswith("model.tips.") else other).append(parameter) groups = [{"params": other}] if backbone: groups.append( {"params": backbone, "lr": self.config.optimizer_lr * self.config.backbone_lr_scale} ) return groups def reset(self): self._action_queue = deque([], maxlen=self.config.n_action_steps) def set_diagnostics_enabled(self, enabled: bool) -> None: self.model.set_diagnostics_enabled(enabled) def _inputs(self, batch: dict) -> tuple[Tensor, Tensor, Sequence[str]]: images = torch.stack([batch[key] for key in self.config.image_keys], dim=1) language = batch.get(OBS_LANGUAGE, batch.get("task")) if isinstance(language, str): language = [language] if not isinstance(language, Sequence): raise ValueError("SERA-VLA-v2 requires a language instruction for every sample") return images, batch[OBS_STATE], language @staticmethod def _specialization_loss(intermediates: list[Tensor], valid: Tensor) -> Tensor: total = torch.zeros((), device=valid.device) for z in intermediates: z_float = z.float() dot = torch.einsum("bhtd,bhsd->bhts", z_float, z_float) norms = z_float.norm(dim=-1) denominator = (norms.unsqueeze(-1) * norms.unsqueeze(-2)).clamp_min(1e-8) similarity = (dot / denominator).square() off_diagonal = ~torch.eye(4, dtype=torch.bool, device=z.device) total = total + (similarity[..., off_diagonal].sum(-1) * valid).sum() return total / valid.sum().clamp_min(1) @staticmethod def _patch_text_align_loss(vision: Tensor, text_pooled: Tensor) -> Tensor: # MIL-InfoNCE (frontend probe F2; spec frontend_probe/SPEC.md): # pair score = tau_pool * logsumexp over patches of cosine / tau_pool, # symmetric cross-entropy over the micro-batch with tau_ce = 0.07. v = F.normalize(vision.float(), dim=-1) t = F.normalize(text_pooled.float(), dim=-1) cos = torch.einsum("bpd,qd->bqp", v, t) scores = 0.1 * torch.logsumexp(cos / 0.1, dim=-1) targets = torch.arange(scores.shape[0], device=scores.device) return 0.5 * ( F.cross_entropy(scores / 0.07, targets) + F.cross_entropy(scores.t() / 0.07, targets) ) @staticmethod def _balance_loss(probabilities: list[Tensor], indices: list[Tensor]) -> Tensor: losses = [] for p, selected in zip(probabilities, indices, strict=True): indicator = F.one_hot(selected, num_classes=8).sum(1).to(p) frequency = (2.0 / p.shape[0]) * indicator.sum(0) losses.append((frequency.detach() * p.mean(0)).sum()) return torch.stack(losses).mean() @staticmethod def _mi_loss(probabilities: list[Tensor], batch: dict, language: Sequence[str]) -> Tensor: # Round-2 arm G (SPEC round2_probe/SPEC.md): per-block batch # estimate of I(Task; Expert) from the full softmax routing # probabilities: I = H(E) - sum_t (n_t/B) H(E|T). Differentiable # through the probabilities (SDP / Mod-Squad batch form). raw_ids = batch.get("task_index") if raw_ids is not None: ids = raw_ids.reshape(-1).long().to(probabilities[0].device) else: uniq: dict[str, int] = {} ids_list = [] for s in language: if s not in uniq: uniq[s] = len(uniq) ids_list.append(uniq[s]) ids = torch.tensor(ids_list, device=probabilities[0].device) mis = [] for p in probabilities: pf = p.float() p_e = pf.mean(0) h_e = -(p_e * p_e.clamp_min(1e-8).log()).sum() h_cond = torch.zeros((), device=pf.device) for t in torch.unique(ids): mask = ids == t p_t = pf[mask].mean(0) h_t = -(p_t * p_t.clamp_min(1e-8).log()).sum() h_cond = h_cond + mask.float().mean() * h_t mis.append(h_e - h_cond) return torch.stack(mis).mean() def _intracl_loss(self, language: Sequence[str]) -> Tensor: # Round-2 arm I (SPEC round2_probe/SPEC.md): weighted InfoNCE on # flattened router logits with verb/object pair weights. The # logits are recomputed from DETACHED router inputs, so this # term's gradient reaches only the router Linears and the # goal-delta Linears - never the vision backbone, projections, # fusion or experts (the F2 failure channel, closed by design). model = self.model router_input = getattr(model, "last_router_input", None) summary = getattr(model, "last_goal_summary", None) goal_deltas = getattr(model, "goal_deltas", None) if router_input is None or summary is None or goal_deltas is None: raise RuntimeError("IntraCL requires the v3 model stash (router input / goal summary)") ri = router_input.detach() sm = summary.detach() logits = [] for router, delta_layer in zip(model.routers, goal_deltas, strict=True): lg = router(ri) if self.config.goal_mode in ("router_only", "router_and_action"): lg = lg + delta_layer(sm) * self.config.goal_router_scale logits.append(lg) r = torch.cat(logits, dim=-1).float() r = F.normalize(r, dim=-1) tau = float(getattr(self.config, "v4_intracl_tau", 0.1)) sim = (r @ r.t()) / tau w = _factor_weights(language, r.device) logp = F.log_softmax(sim, dim=-1) return -(w * logp).sum() / r.shape[0] def forward(self, batch: dict) -> tuple[Tensor, dict[str, float]]: images, state_raw, language = self._inputs(batch) context, state, probabilities, indices, weights = self.model.encode_observation( images, language, state_raw ) quest_on = getattr(self.config, "v4_quest_enabled", False) quest_codes = None if quest_on: quest_codes = self.model.quest_codes_for(batch) self.model.set_skill_from_codes(quest_codes) questfix_metrics = None if quest_on and getattr(self.config, "v4_questfix_enabled", False): questfix_metrics = self.model.questfix_conditioning(quest_codes) action = batch[ACTION] padding = batch.get("action_is_pad") valid = ( torch.ones(action.shape[:2], dtype=torch.bool, device=action.device) if padding is None else ~padding.bool() ) 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(), } align_lambda = getattr(self.config, "v4_align_lambda", 0.0) if align_lambda > 0: align = self._patch_text_align_loss( self.model.last_vision_tokens, self.model.last_text_pooled ) total = total + align_lambda * align metrics["align_loss"] = align.item() entropy_lambda = getattr(self.config, "v4_entropy_lambda", 0.0) if entropy_lambda > 0: ent = torch.stack( [ -(p.float() * p.float().clamp_min(1e-8).log()).sum(-1).mean() for p in probabilities ] ).mean() total = total + entropy_lambda * ent metrics["router_entropy_mean"] = ent.item() mi_gamma = getattr(self.config, "v4_mi_gamma", 0.0) if mi_gamma > 0: # Arm G: MI REPLACES the uniform balance term (the mode # branch above added 0.01 * balance; remove it exactly). mi = self._mi_loss(probabilities, batch, language) total = total - 0.01 * balance - mi_gamma * mi metrics["mi_loss"] = mi.item() metrics["mi_term"] = (mi_gamma * mi).item() intracl_lambda = getattr(self.config, "v4_intracl_lambda", 0.0) if intracl_lambda > 0: icl = self._intracl_loss(language) total = total + intracl_lambda * icl metrics["intracl_loss"] = icl.item() quest_lambda = getattr(self.config, "v4_quest_lambda", 0.0) if quest_on: logits = self.model.skill_prior(self.model.last_router_input, quest_codes) nll = F.cross_entropy(logits.reshape(-1, 1000), quest_codes.reshape(-1)) metrics["prior_nll"] = nll.item() metrics["prior_acc"] = float((logits.argmax(-1) == quest_codes).float().mean()) if quest_lambda > 0: total = total + quest_lambda * nll metrics["prior_term"] = (quest_lambda * nll).item() if questfix_metrics is not None: metrics.update(questfix_metrics) return total, metrics @torch.no_grad() def predict_action_chunk(self, batch: dict) -> Tensor: """Sample one final normalized 16x7 flow-matching chunk.""" self.eval() images, state_raw, language = self._inputs(batch) context, state, _, indices, weights = self.model.encode_observation(images, language, state_raw) if getattr(self.config, "v4_quest_enabled", False): self.model.set_skill_from_prior() if getattr(self.config, "v4_ar_enabled", False): return self.model.ar_predict_chunk(context, state, indices, weights) x = torch.randn(images.shape[0], 16, self.config.action_dim, device=images.device, dtype=state.dtype) for step in range(4): tau = torch.full((images.shape[0],), step / 4, device=images.device, dtype=state.dtype) velocity, _ = self.model.velocity_prediction(x, tau, context, state, indices, weights) x = x + 0.25 * velocity return x @torch.no_grad() def select_action(self, batch: dict) -> Tensor: self.eval() if not self._action_queue: # Evaluation-only replanning ablation. The trained policy always # predicts a 16-step chunk; this controls how many of its first # actions are executed before observing again. It intentionally # does not mutate the checkpoint configuration used in training. execute_steps = int(os.environ.get("SERA_EXECUTE_STEPS", self.config.n_action_steps)) if not 1 <= execute_steps <= self.config.n_action_steps: raise ValueError( f"SERA_EXECUTE_STEPS must be in [1, {self.config.n_action_steps}], got {execute_steps}" ) chunk = self.predict_action_chunk(batch) self._action_queue.extend(chunk[:, :execute_steps].transpose(0, 1)) return self._action_queue.popleft()