OpenGHz's picture
Add fair-comparison/flow-v1
0a3f650 verified
Raw History Blame Contribute Delete
62.3 kB
"""Small ACT policy variants sharing the pinned visual and transformer components.""" import hashlib import math from pathlib import Path from types import SimpleNamespace from typing import Any, Literal import numpy as np import torch import torch.nn.functional as F from pydantic import ( BaseModel, ConfigDict, Field, NonNegativeFloat, NonNegativeInt, PositiveFloat, PositiveInt, model_validator, ) from torch import nn from torch.utils.data import Dataset from lim.action_encoding import ( ActionEncoding, EncodedEnvConfig, Rotation6DEnv, encoded_dimension, sixd_to_controller, ) from lim.action_objective import ( ActionLossConfig, BinaryGripperEnv, BinaryGripperEnvConfig, BinaryGripperModel, BinaryGripperModelConfig, pose_reconstruction, ) from lim.bspline_chunk import demonstration_segments, segment_reconstruction from lim.chunk_flow import ChunkFlowConfig, ChunkFlowModel, flow_reconstruction from lim.chunk_coordinates import ( ChunkAnchor, ChunkGripperSupervision, ChunkPadding, ChunkPoseSupervision, chunk_relative_to_world, controller_pose_targets, pose_target_contract, resolve_anchor, world_to_chunk_relative, ) from lim.keypose_context import ( KeyposeContextMode, KeyposeContextModel, KeyposeContextModelConfig, ) from lim.keypose_control import ( KeyposeControlConfig, KeyposeEnv, KeyposeEnvConfig, encode_keypose, ) from lim.keypose_dense import ( DenseAuxiliaryHead, DenseAuxiliaryHeadConfig, read_dense_actions, ) from lim.keypose_phase import ( DONE_PHASE, KeyposePhaseHead, KeyposePhaseHeadConfig, read_phase_logits, ) from lim.keypose_policy import FirstKeyposeAgent, FirstKeyposeAgentConfig from lim.keypose_stop import KeyposeStopHead, KeyposeStopHeadConfig, read_stop_logits from lim.chunk_done import ( ChunkDoneHead, ChunkDoneHeadConfig, labels_from_valid, batch_done_items, read_done_logits, ) from lim.chunk_switch import ( SWITCH_HORIZON, ChunkSwitchHead, ChunkSwitchHeadConfig, read_switch_fraction, ) from lim.normalization import ( NormalizationConfig, NormalizedModel, NormalizedModelConfig, checked_statistics, ) class ACTPolicyConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) method: Literal["cvae", "state_free", "flow", "chunk_relative"] = "cvae" """One independent policy intervention; cvae preserves the native agent.""" action_encoding: ActionEncoding = "controller" """Rotation6D learns ten-dimensional labels and decodes only after ensembling.""" chunk_anchor: ChunkAnchor = "chunk_start_tcp" """Chunk label frame. Identity isolates the anchor: targets become absolute world poses while the controller boundary still converts against real TCP.""" chunk_pose_supervision: ChunkPoseSupervision = "dense" """Replace only valid-slot pose labels; padding and dense normalization stay shared. Endpoint inference needs no prefix.""" chunk_gripper_supervision: ChunkGripperSupervision = "future" """Future commands, or current command repeated in valid slots; independent of pose and phase labels, with terminal padding and fitted scales preserved.""" chunk_padding: ChunkPadding = "terminal" """Out-of-range slots keep measured terminal targets, or repeat the current complete endpoint target. Valid labels and normalization are unchanged.""" chunk_normalization_population: Literal["dense", "supervised"] = "dense" """Action statistics use dense valid pairs, or one complete current target per observation for the repeated current-target recipe.""" chunk_label_offset: NonNegativeInt = 0 """Slot i supervises time t+offset+i; zero preserves every existing recipe.""" chunk_waypoint_threshold_m: PositiveFloat | None = None """AWE distance threshold (metres) for future_waypoint labels; None otherwise.""" chunk_bspline_knots: PositiveInt | None = None """Unique knots per B-spline segment for bspline labels (lim.bspline_chunk; num_queries = knots + 6 rows); None otherwise.""" chunk_switch_head: bool = False """Regress the current phase's remaining steps from decoder query zero.""" chunk_switch_weight: NonNegativeFloat = Field(default=1.0, allow_inf_nan=False) """L1 weight on the remaining-steps fraction when the switch head exists.""" chunk_phase_done: bool = False """Label padded items with a seventh "done" phase instead of ignoring them; requires a trained per-item phase head (chunk_phase_weight > 0).""" chunk_done_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False) """BCE weight of the per-item end-of-demonstration logits (lim.chunk_done); positive values add the head. Action labels, padding and statistics are unchanged.""" flow_steps: PositiveInt = 8 """Euler evaluations per fresh observation for the conditional flow head (method flow) or the flow-matching head (chunk_flow).""" inference_seed: NonNegativeInt = 20260916 """Private flow inference noise stream, independent of the training RNG; chunk_flow evaluations seed each episode with inference_seed + scene seed.""" chunk_flow: bool = False """Replace the CVAE decoder pass by a flow-matching head on the same observation encoder (lim.chunk_flow); False keeps the CVAE.""" normalization: NormalizationConfig = NormalizationConfig() """Independent training-fitted scaling; none preserves existing policies.""" state_input: Literal["full", "no_velocity", "tcp_only", "no_state"] = "full" """State25 information subset, masked in both CVAE branches with capacity fixed; no_state masks all 25 values, leaving the images as the only observation.""" action_loss: ActionLossConfig = ActionLossConfig() """Action objective and linked inference semantics, persisted with the policy.""" keypose: KeyposeControlConfig | None = None """When set, learn next world keypose on all queries; execute the first at 20Hz.""" keypose_phase_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False) """Weight on six-class primitive CE from query-zero features; zero preserves the native action-only model. Labels are supervision only, never inputs.""" keypose_target_sequence: Literal["current", "future"] = "current" """Repeat the current primitive goal, or supervise each future time's goal; both variants still execute query zero with the same keypose controller.""" keypose_context: KeyposeContextMode = "none" """Optional completed-target11 input shared by prior and posterior state projections; zero and previous_target have identical trainable structure.""" keypose_stop_head: bool = False """Add independent terminal-intent logits from decoder query zero.""" keypose_stop_weight: NonNegativeFloat = Field(default=0.1, allow_inf_nan=False) """BCE weight when the stop head exists; zero retains the same head for controls.""" keypose_dense_head: bool = False """Add a dense30 auxiliary decoder projection; never executed at inference.""" keypose_dense_weight: NonNegativeFloat = Field(default=1.0, allow_inf_nan=False) """Dense group-balanced reconstruction weight; zero is the matched head control.""" chunk_phase_head: bool = False """Retain the per-query phase head even when its auxiliary loss is zero.""" chunk_phase_weight: NonNegativeFloat = Field(default=0.0, allow_inf_nan=False) """Per-query phase CE weight. Positive values also enable the head, preserving the architecture of existing checkpoints with no explicit head field.""" @property def has_chunk_phase_head(self): """Whether model construction and diagnostic labels include a phase head.""" return self.chunk_phase_head or self.chunk_phase_weight > 0 @property def has_chunk_done_head(self): """Whether model construction and training labels include the done head.""" return self.chunk_done_weight > 0 def action_dimension(self, controller_dimension): """Per-item model output width: the encoded target, plus the knot column of B-spline segments.""" width = encoded_dimension(controller_dimension, self.action_encoding) return width + (self.chunk_pose_supervision == "bspline") @model_validator(mode="after") def check_bspline(self): if (self.chunk_pose_supervision == "bspline") != (self.chunk_bspline_knots is not None): raise ValueError("Exactly the B-spline supervision carries a knot count") if self.chunk_pose_supervision == "bspline" and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" or self.chunk_anchor != "chunk_start_tcp" or self.chunk_gripper_supervision != "future" or self.chunk_padding != "terminal" or self.chunk_normalization_population != "dense" or self.chunk_label_offset or self.has_chunk_phase_head or self.chunk_switch_head or self.has_chunk_done_head or self.action_loss.method != "group_balanced" ): raise ValueError( "B-spline segments use TCP-anchored pose6D, default label fields," " no per-item heads and the group-balanced objective" ) return self @model_validator(mode="after") def check_flow(self): if self.chunk_flow and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" or self.chunk_pose_supervision not in ("dense", "future_endpoint") or self.has_chunk_phase_head or self.chunk_switch_head or self.has_chunk_done_head or self.state_input != "full" or self.action_loss.method != "group_balanced" ): raise ValueError( "The flow head replaces the CVAE of full-state TCP-anchored dense or" " endpoint pose6D chunks, without per-item heads" ) return self @model_validator(mode="after") def check_phase_done(self): if self.chunk_phase_done and ( self.chunk_phase_weight <= 0 or self.chunk_done_weight > 0 or self.chunk_padding != "terminal" or self.chunk_label_offset or self.chunk_pose_supervision == "phase_segments" or self.chunk_switch_head ): raise ValueError( "The done phase labels terminal padding of a trained per-item phase head, without the done head" ) return self @model_validator(mode="after") def check_done(self): # Labels are the dataset's in-range mask; offsets and two-segment # outputs index items by something other than consecutive steps. if self.has_chunk_done_head and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" or self.chunk_padding != "terminal" or self.chunk_label_offset or self.chunk_pose_supervision == "phase_segments" or self.chunk_switch_head ): raise ValueError( "The done head labels consecutive pose6D chunk items with terminal padding" ) return self @model_validator(mode="after") def check_normalization(self): compact = ( self.chunk_label_offset > 0 or self.chunk_pose_supervision == "phase_segments" or self.chunk_switch_head ) # A Q30 future-endpoint switch arm keeps its template's zero-weight phase # head, so it differs from that template only by the switch head. phase_head_allowed = ( self.chunk_pose_supervision == "future_endpoint" and not self.chunk_label_offset and self.chunk_phase_weight == 0 ) if compact and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" or self.chunk_anchor != "chunk_start_tcp" or self.chunk_gripper_supervision != "future" or self.chunk_padding != "terminal" or self.chunk_normalization_population != "dense" or (self.has_chunk_phase_head and not phase_head_allowed) ): raise ValueError( "Compact endpoint outputs use TCP-anchored pose6D, own gripper labels, no phase head" ) if self.chunk_label_offset > 0 and self.chunk_pose_supervision != "future_endpoint": raise ValueError("Lookahead labels shift future-time endpoint supervision only") if (self.chunk_pose_supervision == "future_waypoint") != ( self.chunk_waypoint_threshold_m is not None ): raise ValueError("Exactly the waypoint supervision carries a waypoint threshold") if self.chunk_pose_supervision == "phase_segments" and not self.chunk_switch_head: raise ValueError("Phase segments always carry the switch head (weight may be zero)") if self.chunk_switch_head and ( self.chunk_pose_supervision not in ("phase_segments", "future_endpoint") or self.chunk_label_offset ): raise ValueError("The switch head supervises unshifted endpoint recipes only") if self.chunk_pose_supervision == "phase_segments" and self.chunk_label_offset: raise ValueError("Phase segments are indexed by phase, not by time offset") if self.chunk_padding == "current_target" and ( self.chunk_pose_supervision != "current_endpoint" or self.chunk_gripper_supervision != "current" ): raise ValueError( "Current-target padding requires current endpoint and gripper" ) if self.chunk_gripper_supervision != "future" and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" ): raise ValueError("Chunk gripper supervision requires chunk-relative pose6D") if self.chunk_pose_supervision != "dense" and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" ): raise ValueError( "Matched endpoint supervision requires pose6D chunk-relative targets" ) if self.has_chunk_phase_head and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" ): raise ValueError( "Chunk phase supervision requires fixed-anchor pose6D targets" ) if self.chunk_normalization_population == "supervised" and ( self.chunk_pose_supervision != "current_endpoint" or self.chunk_gripper_supervision != "current" or self.chunk_padding != "current_target" ): raise ValueError( "Supervised normalization requires repeated complete current-target endpoint labels" ) if self.keypose_dense_head and not self.keypose_stop_head: raise ValueError( "Dense auxiliary screen requires the existing stop/context policy" ) if self.keypose_stop_head and ( self.keypose is None or self.method != "cvae" or self.state_input != "full" or self.keypose_target_sequence != "current" or self.keypose_context != "previous_target" or self.keypose_phase_weight != 0 ): raise ValueError( "Stop supervision requires current previous-target full-state CVAE keypose without phase" ) if self.keypose_context != "none" and ( self.keypose is None or self.method != "cvae" or self.state_input != "full" or self.keypose_target_sequence != "current" or self.keypose_phase_weight != 0 ): raise ValueError( "Completed-goal context requires current full-state CVAE keypose without a phase head" ) if self.keypose_target_sequence == "future" and self.keypose is None: raise ValueError("Future keypose supervision requires a keypose policy") if self.keypose_phase_weight > 0 and self.keypose is None: raise ValueError("Phase classification requires a keypose policy") if self.chunk_anchor != "chunk_start_tcp" and ( self.method != "chunk_relative" or self.action_encoding != "rotation6d" ): raise ValueError( "Absolute chunk anchors are only defined for pose6D chunk_relative" ) if ( self.method == "chunk_relative" and self.action_encoding == "controller" and self.normalization.method != "none" ): raise ValueError( "Position-only chunk-relative checkpoints retain their original unnormalized contract" ) if self.keypose is not None and ( self.method != "cvae" or self.action_encoding != "rotation6d" or self.state_input != "full" or self.action_loss.method != "group_balanced" or self.normalization.method != "action_zscore" ): raise ValueError( "Keypose screen requires full-state CVAE, rotation6d, group-balanced action-zscore" ) if self.normalization.method != "none" and self.method not in ( "cvae", "chunk_relative", ): raise ValueError( "Screen normalization on the native state-conditioned CVAE" ) if self.state_input != "full" and self.method not in ("cvae", "chunk_relative"): raise ValueError("State subsets are screened on the CVAE policies") if self.action_loss.method != "native" and ( self.method not in ("cvae", "chunk_relative") or self.action_encoding != "rotation6d" or (self.state_input != "full" and self.method != "chunk_relative") ): raise ValueError("Screen pose action losses on full-state Rotation6D CVAE") if ( self.method == "chunk_relative" and self.action_encoding == "rotation6d" and ( self.keypose is not None or self.normalization.method != "action_zscore" or self.action_loss.method != "group_balanced" ) ): raise ValueError( "Pose chunk-relative screen requires full-state/group-balanced/action-zscore" ) return self class ModelBuildConfig(BaseModel, frozen=True): model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid") native_model: Any """Newly initialized pinned DETRVAE; selected modules are reused unchanged.""" policy: ACTPolicyConfig """Validated policy variant and sampler configuration.""" class StateFreeModel(nn.Module): """Constant state tokens preserve capacity but carry no proprioceptive signal.""" def __init__(self, config: ModelBuildConfig): super().__init__() self.base = config.native_model self.state_dim = self.base.input_proj_robot_state.in_features def forward(self, obs, actions=None): # Both the posterior and action decoder see constants, including training. # The original state values are never read; images determine batch/device. state = torch.zeros( obs["rgb"].shape[0], self.state_dim, device=obs["rgb"].device, dtype=obs["rgb"].dtype, ) return self.base({"rgb": obs["rgb"], "state": state}, actions) class StateSubsetModel(nn.Module): """Remove selected state information without changing initialization or width.""" def __init__(self, config: ModelBuildConfig): super().__init__() self.config = config self.base = config.native_model if self.base.input_proj_robot_state.in_features != 25: raise ValueError( "State subsets require qpos9, qvel9, TCP position3/quaternion4" ) keep = torch.zeros(25, dtype=torch.bool) if config.policy.state_input == "no_velocity": keep[:9] = True keep[18:] = True elif config.policy.state_input == "tcp_only": keep[18:] = True elif config.policy.state_input != "no_state": raise ValueError("Full-state control must use the unwrapped native model") self.register_buffer("keep_state", keep, persistent=False) def forward(self, obs, actions=None): # Applied after optional per-axis normalization, before posterior/decoder. # masked_fill also prevents discarded NaNs from reaching either branch. state = obs["state"].masked_fill(~self.keep_state, 0) return self.base({**obs, "state": state}, actions) class FlowACT(nn.Module): """Conditional linear-path flow: Gaussian noise -> normalized action chunks. Observation memory is encoded once per fresh observation. Only the action decoder is iterated, with noisy actions and continuous time as inputs. """ def __init__(self, config: ModelBuildConfig): super().__init__() native = config.native_model self.config = config.policy self.backbones = native.backbones self.input_proj = native.input_proj self.input_proj_robot_state = native.input_proj_robot_state self.transformer = native.transformer self.query_embed = native.query_embed self.action_head = native.action_head self.additional_pos_embed = native.additional_pos_embed self.num_queries = native.num_queries width = self.transformer.d_model self.action_input = nn.Linear(self.action_head.out_features, width) self.time_mlp = nn.Sequential( nn.Linear(width, width), nn.SiLU(), nn.Linear(width, width) ) self.register_buffer( "time_frequencies", torch.exp( -math.log(10000) * torch.arange(width // 2) / max(1, width // 2 - 1) ), ) self.generator = None def encode_observation(self, obs): features, positions = [], [] for camera in range(obs["rgb"].shape[1]): feature, position = self.backbones[0](obs["rgb"][:, camera]) features.append(self.input_proj(feature[0])) positions.append(position[0]) batch = obs["rgb"].shape[0] src = torch.cat(features, dim=3).flatten(2).permute(2, 0, 1) pos = ( torch.cat(positions, dim=3).flatten(2).permute(2, 0, 1).repeat(1, batch, 1) ) proprio = self.input_proj_robot_state(obs["state"]).unsqueeze(0) # Keep the native proprioceptive position; there is no CVAE latent token. pos = torch.cat( [self.additional_pos_embed.weight[1:2, None].expand(-1, batch, -1), pos] ) src = torch.cat([proprio, src]) memory = self.transformer.encoder(src, pos=pos) return memory, pos def velocity(self, noisy, time, memory, pos): angles = time[:, None] * self.time_frequencies[None] * 1000 time_embedding = self.time_mlp(torch.cat([angles.sin(), angles.cos()], dim=-1)) target = (self.action_input(noisy) + time_embedding[:, None]).transpose(0, 1) queries = self.query_embed.weight[:, None].expand(-1, noisy.shape[0], -1) hidden = self.transformer.decoder(target, memory, pos=pos, query_pos=queries)[ -1 ] return self.action_head(hidden.transpose(0, 1)) def training_loss(self, obs, actions): memory, pos = self.encode_observation(obs) noise = torch.randn_like(actions) time = torch.rand(actions.shape[0], device=actions.device) noisy = (1 - time[:, None, None]) * noise + time[:, None, None] * actions target = actions - noise return F.mse_loss(self.velocity(noisy, time, memory, pos), target) def forward(self, obs): memory, pos = self.encode_observation(obs) if self.generator is None or self.generator.device != obs["rgb"].device: self.generator = torch.Generator(device=obs["rgb"].device) self.generator.manual_seed(self.config.inference_seed) batch = obs["rgb"].shape[0] action = torch.randn( batch, self.num_queries, self.action_head.out_features, device=obs["rgb"].device, generator=self.generator, ) step = 1 / self.config.flow_steps for index in range(self.config.flow_steps): time = action.new_full((batch,), index * step) action = action + step * self.velocity(action, time, memory, pos) # Match native ACT: the controller clips after temporal aggregation. return action, (None, None) def build_policy(native, spaces, args, policy, normalization=None): fitted = checked_statistics( normalization, policy.normalization, policy.action_encoding ) if policy.action_encoding != "controller": spaces = SimpleNamespace( single_observation_space=spaces.single_observation_space, single_action_space=SimpleNamespace( shape=(policy.action_dimension(spaces.single_action_space.shape[-1]),) ), ) agent = native.Agent(spaces, args) if policy.keypose_stop_head: # Attach to the actual native decoder before context/normalization wrappers. agent.model.action_head = KeyposeStopHead( KeyposeStopHeadConfig(action_head=agent.model.action_head) ) if policy.keypose_dense_head: agent.model.action_head = DenseAuxiliaryHead( DenseAuxiliaryHeadConfig( primary=agent.model.action_head, hidden_size=agent.model.action_head.action.in_features, ) ) if policy.keypose_context != "none": if fitted is None: raise ValueError( "Completed-goal context requires checkpoint-owned action statistics" ) agent.model = KeyposeContextModel( KeyposeContextModelConfig( model=agent.model, mode=policy.keypose_context, statistics=fitted ) ) if policy.keypose_phase_weight > 0 or policy.has_chunk_phase_head: agent.model.action_head = KeyposePhaseHead( KeyposePhaseHeadConfig( action_head=agent.model.action_head, all_queries=policy.has_chunk_phase_head, done_class=policy.chunk_phase_done, ) ) if policy.chunk_switch_head: # Outermost: it may wrap the phase head; both read the same features. agent.model.action_head = ChunkSwitchHead( ChunkSwitchHeadConfig(action_head=agent.model.action_head) ) if policy.has_chunk_done_head: agent.model.action_head = ChunkDoneHead( ChunkDoneHeadConfig(action_head=agent.model.action_head) ) if policy.chunk_flow: agent.model = ChunkFlowModel( ChunkFlowConfig(native_model=agent.model, steps=policy.flow_steps) ) if policy.method == "state_free": agent.model = StateFreeModel( ModelBuildConfig(native_model=agent.model, policy=policy) ) elif policy.method == "flow": agent.model = FlowACT(ModelBuildConfig(native_model=agent.model, policy=policy)) if policy.state_input != "full": agent.model = StateSubsetModel( ModelBuildConfig(native_model=agent.model, policy=policy) ) if policy.action_loss.method == "gripper_bce": agent.model = BinaryGripperModel(BinaryGripperModelConfig(model=agent.model)) if fitted is not None: if spaces.single_action_space.shape != ( len(fitted.action.center), ) or spaces.single_observation_space["state"].shape != ( len(fitted.state.center), ): raise ValueError("Fitted normalization shapes differ from the policy") agent.model = NormalizedModel( NormalizedModelConfig(model=agent.model, statistics=fitted) ) return agent def policy_loss( agent, native, obs, actions, policy, objective, phase_labels=None, stop_labels=None, dense_labels=None, switch_labels=None, done_labels=None, ): if policy.action_loss.method != "native": if objective.config.method != "control": raise ValueError( "Action loss candidates require the control training recipe" ) obs = {**obs, "rgb": agent.normalize(obs["rgb"].float() / 255)} if policy.chunk_flow: # No latent and no per-item heads (check_flow): only the velocity loss. velocity, target = agent.model(obs, actions) losses = flow_reconstruction(velocity, target) return {"loss": losses["reconstruction"], **losses} prediction, (mu, logvar) = agent.model(obs, actions) reconstruction = ( segment_reconstruction if policy.chunk_pose_supervision == "bspline" else pose_reconstruction ) losses = reconstruction(prediction, actions, policy.action_loss) kl = native.kl_divergence(mu, logvar)[0][0] result = { "loss": losses["reconstruction"] + agent.kl_weight * kl, "kl": kl, **losses, } if policy.keypose_phase_weight > 0: logits = read_phase_logits(agent) if ( phase_labels is None or phase_labels.dtype != torch.long or phase_labels.shape != logits.shape[:1] or not ((phase_labels >= 0) & (phase_labels < 6)).all() ): raise ValueError( "Expected one integer primitive label in [0, 5] per observation" ) phase_ce = F.cross_entropy(logits, phase_labels) result.update( loss=result["loss"] + policy.keypose_phase_weight * phase_ce, phase_ce=phase_ce, phase_accuracy=(logits.argmax(-1) == phase_labels).float().mean(), ) if policy.has_chunk_phase_head: logits = read_phase_logits(agent) classes = DONE_PHASE + int(policy.chunk_phase_done) if ( phase_labels is None or phase_labels.dtype != torch.long or phase_labels.shape != prediction.shape[:2] or logits.shape != (*prediction.shape[:2], classes) or not ( (phase_labels == -100) | ((phase_labels >= 0) & (phase_labels < classes)) ).all() or (policy.chunk_phase_done and (phase_labels == -100).any()) or not ((phase_labels[:, 0] >= 0) & (phase_labels[:, 0] < DONE_PHASE)).all() ): raise ValueError( "Expected valid future phase labels and -100 only for padding" ) phase_ce = F.cross_entropy( logits.flatten(0, 1), phase_labels.flatten(), ignore_index=-100 ) valid = phase_labels != -100 # Keep CE as a diagnostic at weight zero, but remove its graph from # the objective entirely: unused head parameters must get no gradient. if policy.chunk_phase_weight > 0: result["loss"] = result["loss"] + policy.chunk_phase_weight * phase_ce result.update( phase_ce=phase_ce, phase_accuracy=(logits.argmax(-1)[valid] == phase_labels[valid]) .float() .mean(), phase_query0_accuracy=(logits[:, 0].argmax(-1) == phase_labels[:, 0]) .float() .mean(), ) if policy.keypose_stop_head: logits = read_stop_logits(agent) if ( stop_labels is None or not stop_labels.is_floating_point() or stop_labels.shape != logits.shape or logits.ndim != 1 or not ((stop_labels == 0) | (stop_labels == 1)).all() ): raise ValueError("Expected one float binary stop label per observation") stop_bce = F.binary_cross_entropy_with_logits(logits, stop_labels) result.update( loss=result["loss"] + policy.keypose_stop_weight * stop_bce, stop_bce=stop_bce, stop_accuracy=((logits >= 0) == stop_labels.bool()).float().mean(), stop_predicted_positive=(logits >= 0).float().mean(), ) if policy.chunk_switch_head: fraction = read_switch_fraction(agent) if ( switch_labels is None or not switch_labels.is_floating_point() or switch_labels.shape != fraction.shape or not ((switch_labels > 0) & (switch_labels <= 1)).all() ): raise ValueError("Expected one remaining-steps fraction in (0, 1] per observation") switch_l1 = (fraction - switch_labels).abs().mean() # At weight zero the head stays a diagnostic: no graph, no gradient. if policy.chunk_switch_weight > 0: result["loss"] = result["loss"] + policy.chunk_switch_weight * switch_l1 result["switch_l1"] = switch_l1.detach() if policy.has_chunk_done_head: logits = read_done_logits(agent) if ( done_labels is None or not done_labels.is_floating_point() or done_labels.shape != prediction.shape[:2] or logits.shape != done_labels.shape or not ((done_labels == 0) | (done_labels == 1)).all() or (done_labels[:, 0] != 0).any() ): raise ValueError("Expected one binary end label per item, item 0 never done") done_bce = F.binary_cross_entropy_with_logits(logits, done_labels) with torch.no_grad(): # Training forwards carry the posterior latent: diagnostics only. items = batch_done_items(logits) truth = (1 - done_labels).sum(-1) result.update( loss=result["loss"] + policy.chunk_done_weight * done_bce, done_bce=done_bce, done_accuracy=((logits >= 0) == done_labels.bool()).float().mean(), done_items_exact=(items == truth).float().mean(), ) if policy.keypose_dense_head: dense_prediction = read_dense_actions(agent) if ( dense_labels is None or dense_labels.shape != prediction.shape or dense_prediction.shape != prediction.shape or not torch.isfinite(dense_labels).all() ): raise ValueError( "Expected finite normalized dense labels matching the original Q30 horizon" ) dense_loss = pose_reconstruction( dense_prediction, dense_labels, ActionLossConfig(method="group_balanced"), ) result.update( loss=result["loss"] + policy.keypose_dense_weight * dense_loss["reconstruction"], **{f"dense_{key}": value for key, value in dense_loss.items()}, ) return result if policy.method != "flow": return objective.compute_loss(agent, native, obs, actions) obs = {**obs, "rgb": agent.normalize(obs["rgb"].float() / 255)} loss = agent.model.training_loss(obs, actions) return {"loss": loss, "flow_mse": loss} class ChunkDatasetConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) dataset: Any """Pinned native preprocessed StackCube dataset with state25 and delta actions.""" action_encoding: ActionEncoding = "controller" """Existing position-only controller labels, or dense fixed-reference pose6D.""" source: Path | None = None """Pose6D H5 used to verify robot-root axes in every saved state.""" chunk_anchor: ChunkAnchor = "chunk_start_tcp" """Label origin; identity makes every target an absolute world pose.""" phase_supervision: bool = False """Return each valid future action's primitive label; ignore padded labels.""" phase_done: bool = False """Label padded items DONE_PHASE instead of ignoring them.""" chunk_pose_supervision: ChunkPoseSupervision = "dense" """Only valid-slot pose labels change; phase and fitted scales do not.""" chunk_gripper_supervision: ChunkGripperSupervision = "future" """Future commands or current command repeated in valid slots only.""" chunk_padding: ChunkPadding = "terminal" """Measured terminal pose/last gripper, or repeat the current complete target.""" chunk_normalization_population: Literal["dense", "supervised"] = "dense" """Action statistics use dense valid pairs, or one complete current target per observation for the repeated current-target recipe.""" chunk_label_offset: NonNegativeInt = 0 """Slot i supervises time t+offset+i; zero preserves every existing recipe.""" chunk_waypoint_threshold_m: PositiveFloat | None = None """AWE distance threshold for future_waypoint labels.""" chunk_bspline_knots: PositiveInt | None = None """Unique knots per segment for bspline labels (lim.bspline_chunk).""" switch_supervision: bool = False """Also return the current primitive's remaining-steps fraction.""" done_supervision: bool = False """Also return each item's end-of-demonstration label (lim.chunk_done).""" @model_validator(mode="after") def check_supervision(self): if (self.chunk_pose_supervision == "bspline") != (self.chunk_bspline_knots is not None): raise ValueError("Exactly the B-spline supervision carries a knot count") if self.chunk_pose_supervision == "bspline" and ( self.action_encoding != "rotation6d" or self.phase_supervision or self.switch_supervision or self.done_supervision ): raise ValueError("B-spline segments carry pose6D rows and no per-item labels") if self.done_supervision and ( self.action_encoding != "rotation6d" or self.chunk_padding != "terminal" or self.chunk_label_offset or self.chunk_pose_supervision == "phase_segments" ): raise ValueError("End labels mark consecutive pose6D items with terminal padding") if self.chunk_padding == "current_target" and ( self.chunk_pose_supervision != "current_endpoint" or self.chunk_gripper_supervision != "current" ): raise ValueError( "Current-target padding requires current endpoint and gripper" ) if ( self.chunk_gripper_supervision != "future" and self.action_encoding != "rotation6d" ): raise ValueError("Chunk gripper supervision requires pose6D data") if ( self.chunk_pose_supervision != "dense" and self.action_encoding != "rotation6d" ): raise ValueError( "Endpoint labels require pose6D chunk-relative data" ) if self.chunk_normalization_population == "supervised" and ( self.chunk_pose_supervision != "current_endpoint" or self.chunk_gripper_supervision != "current" or self.chunk_padding != "current_target" ): raise ValueError( "Supervised normalization requires repeated complete current-target endpoint labels" ) return self def remaining_fraction(ends, labels): """Steps left in each observation's primitive, min(steps, horizon)/horizon.""" remaining = torch.from_numpy(ends).long()[labels] - torch.arange(len(labels)) if not (remaining >= 1).all(): raise ValueError("Every observation must have at least one remaining step") return remaining.clamp(max=SWITCH_HORIZON).float() / SWITCH_HORIZON class ChunkRelativeDataset(Dataset): """Encode actual controller goals relative to each query's current TCP. StackCube panda_wristcam state = qpos9, qvel9, world TCP pose7. The root orientation is identity and pd_ee_delta_pos uses scale 0.1 m. Positions at future steps are supervised data only, never policy inputs. """ def __init__(self, config: ChunkDatasetConfig): self.config = config self.dataset = config.dataset self.phase_chunks = [] self.waypoint_counts = [] if config.phase_supervision and config.action_encoding != "rotation6d": raise ValueError("Chunk phase labels require pose6D data") if config.phase_done and not config.phase_supervision: raise ValueError("The done phase extends per-item phase labels") for trajectory in self.dataset.trajectories["observations"]: if trajectory["state"].shape[-1] != 25: raise ValueError("Chunk labels require the audited state25 layout") if config.action_encoding == "rotation6d": import h5py if config.source is None: raise ValueError( "Pose chunk-relative labels require source H5 root-frame verification" ) self.chunks = [] self.world_targets = [] self.segment_fits = [] self.switch_labels = [] self.done_chunks = [] populations = [] with h5py.File(config.source) as data: names = sorted(data, key=lambda n: int(n.split("_")[-1]))[ : self.dataset.num_traj ] if len(names) != self.dataset.num_traj: raise ValueError( "Source trajectory count differs from the native dataset" ) for name, actions, obs in zip( names, self.trajectories["actions"], self.trajectories["observations"], strict=True, ): tcp = obs["state"][:, 18:25] if actions.shape[-1] != 7 or len(tcp) != len(actions) + 1: raise ValueError( "Expected unencoded pose actions and a terminal TCP" ) stored_tcp = torch.from_numpy(data[name]["obs/extra/tcp_pose"][:]) torch.testing.assert_close(tcp, stored_tcp, atol=0, rtol=0) roots = data[name]["env_states/articulations/panda_wristcam"][ :, 3:7 ] np.testing.assert_allclose( roots, np.tile([1, 0, 0, 0], (len(roots), 1)), atol=1e-5 ) goals = controller_pose_targets(actions, tcp[:-1]) terminal = encode_keypose(tcp[-1], actions[-1, -1])[None] goals = torch.cat([goals, terminal]) if config.chunk_pose_supervision == "bspline": labels, fit = demonstration_segments( goals, tcp, config.chunk_bspline_knots ) if labels.shape[1] != self.num_queries: raise ValueError("Segment rows differ from the query count") self.segment_fits.append(fit) populations.append(labels.flatten(0, 1)) self.chunks.append(labels) self.world_targets.append(goals) continue times = ( torch.arange(len(actions))[:, None] + config.chunk_label_offset + torch.arange(self.num_queries)[None] ) valid = times < len(actions) if config.done_supervision: self.done_chunks.append(labels_from_valid(valid)) if config.chunk_pose_supervision == "future_waypoint": from lim.waypoints import next_waypoint, select_waypoints waypoints = select_waypoints( goals[: len(actions), :3].numpy(), config.chunk_waypoint_threshold_m, actions[:, -1].numpy(), ) self.waypoint_counts.append((len(waypoints), len(actions))) following = torch.from_numpy( next_waypoint(len(actions), waypoints) ) if ( config.phase_supervision or config.chunk_pose_supervision not in ("dense", "future_waypoint") ): from lim.keypose_phase import KEYPOSE_PHASE_NAMES key = data[name]["keyframes"] labels = torch.from_numpy( key["action_keyframe_index"][:] ).long() starts, ends = key["start_action"][:], key["end_action"][:] # Six-class phase labels exist only for the canonical # StackCube primitives; other tasks' experts record # their own primitive list, used for endpoints alone. segments = len(starts) if ( ( config.phase_supervision and tuple(key["name"].asstr()[:]) != KEYPOSE_PHASE_NAMES ) or segments < 1 or starts.shape != (segments,) or ends.shape != (segments,) or starts[0] != 0 or ends[-1] != len(actions) or np.any(ends <= starts) or not np.array_equal(starts[1:], ends[:-1]) or not np.array_equal( labels.numpy(), np.repeat(np.arange(segments), ends - starts) ) ): raise ValueError( "Expected aligned canonical primitive indices" ) phase = labels[times.clamp(max=len(actions) - 1)].clone() phase[~valid] = DONE_PHASE if config.phase_done else -100 self.phase_chunks.append(phase) relative = world_to_chunk_relative( goals[times.clamp(max=len(actions))], resolve_anchor(tcp[:-1, None], config.chunk_anchor), ) # The default population preserves the original dense labels # and physical loss weights across supervision variants. if config.chunk_normalization_population == "dense": populations.append(relative[valid]) if config.chunk_pose_supervision == "future_waypoint": replacement = world_to_chunk_relative( goals[following[times.clamp(max=len(actions) - 1)]], resolve_anchor(tcp[:-1, None], config.chunk_anchor), ) relative[valid] = torch.cat( [replacement[valid][:, :9], relative[valid][:, -1:]], -1 ) elif config.chunk_pose_supervision != "dense": poses = torch.from_numpy(key["target_pose_world"][:]) grippers = torch.from_numpy(key["gripper_command"][:]) if ( poses.shape != (segments, 7) or grippers.shape != (segments,) or not torch.isfinite(poses).all() or not torch.isfinite(grippers).all() or not torch.equal(grippers[labels], actions[:, -1]) ): raise ValueError( "Endpoint and dense primitive labels disagree" ) endpoints = encode_keypose(poses, grippers) if config.chunk_pose_supervision == "phase_segments": if self.num_queries != 2: raise ValueError("Phase segments require exactly two queries") segments = torch.stack( [labels, (labels + 1).clamp(max=5)], -1 ) # Both slots carry their own primitive gripper command. relative = world_to_chunk_relative( endpoints[segments], resolve_anchor(tcp[:-1, None], config.chunk_anchor), ) self.switch_labels.append(remaining_fraction(ends, labels)) self.chunks.append(relative) self.world_targets.append(goals) continue if config.switch_supervision: self.switch_labels.append(remaining_fraction(ends, labels)) endpoint_indices = ( labels[times.clamp(max=len(actions) - 1)] if config.chunk_pose_supervision == "future_endpoint" else labels[:, None].expand_as(times) ) replacement = world_to_chunk_relative( endpoints[endpoint_indices], resolve_anchor(tcp[:-1, None], config.chunk_anchor), ) # Preserve original dense terminal padding and every # future gripper command, including in current_endpoint. relative[valid] = torch.cat( [replacement[valid][:, :9], relative[valid][:, -1:]], -1 ) if config.chunk_gripper_supervision == "current": # Change the supervised gripper timing only. The current # command is not the phase-end command and never replaces # the terminal padding or dense normalization population. repeated = actions[:, -1, None].expand_as(times) relative[..., -1][valid] = repeated[valid] if config.chunk_padding == "current_target": # Query zero always exists and already has the complete # current endpoint. Only replace out-of-range slots. repeated = relative[:, :1].expand_as(relative) relative[~valid] = repeated[~valid] if config.chunk_normalization_population == "supervised": # One target per original observation, independent of Q # and padding, matching the old KeyposeDataset weighting. populations.append(relative[:, 0]) self.chunks.append(relative) self.world_targets.append(goals) self.normalization_actions = torch.cat(populations) self.target_contract = pose_target_contract( config.chunk_anchor, config.chunk_pose_supervision, config.chunk_gripper_supervision, config.chunk_padding, config.chunk_normalization_population, config.chunk_label_offset, config.chunk_waypoint_threshold_m, config.chunk_bspline_knots, ) all_chunks = torch.cat(self.chunks) tensors = { "sample_indices": torch.tensor(self.dataset.slices), **( {"segment_labels": all_chunks} if self.segment_fits else { "pose_labels": all_chunks[..., :9], "gripper_labels": all_chunks[..., -1], } ), "normalization_population": self.normalization_actions, } if self.phase_chunks: tensors["phase_labels"] = torch.cat(self.phase_chunks) if self.switch_labels: tensors["switch_labels"] = torch.cat(self.switch_labels) if self.done_chunks: tensors["done_labels"] = torch.cat(self.done_chunks) self.supervision_audit = { "pose_supervision": config.chunk_pose_supervision, "gripper_supervision": config.chunk_gripper_supervision, "samples": len(self.dataset.slices), "normalization_samples": len(self.normalization_actions), **{ f"{name}_sha256": hashlib.sha256( tensor.contiguous().numpy().tobytes() ).hexdigest() for name, tensor in tensors.items() }, **( { "waypoints": sum(w for w, _ in self.waypoint_counts), "actions": sum(n for _, n in self.waypoint_counts), "waypoint_threshold_m": config.chunk_waypoint_threshold_m, } if self.waypoint_counts else {} ), **( { "segment_knots": config.chunk_bspline_knots, "fitted_unique_knots": sum(f["knots"] for f in self.segment_fits), "fitted_control_points": sum( f["control_points"] for f in self.segment_fits ), "max_fit_error": max(f["max_error"] for f in self.segment_fits), } if self.segment_fits else {} ), **( { # Over the sampled observations, i.e. what training sees. "done_items": len(self.dataset.slices) * self.num_queries, "done_positives": int( sum(self.done_chunks[j][t].sum() for j, t in self.dataset.slices) ), } if self.done_chunks else {} ), **( { "phase_done_items": int( sum( (self.phase_chunks[j][t] == DONE_PHASE).sum() for j, t in self.dataset.slices ) ) } if config.phase_done else {} ), } def __getattr__(self, name): return getattr(self.dataset, name) def __len__(self): return len(self.dataset) def __getitem__(self, index): trajectory, start = self.dataset.slices[index] if self.config.action_encoding == "rotation6d": return { "observations": { k: v[start] for k, v in self.trajectories["observations"][trajectory].items() }, "actions": self.chunks[trajectory][start], **( {"phase": self.phase_chunks[trajectory][start]} if self.config.phase_supervision else {} ), **( {"switch": self.switch_labels[trajectory][start]} if self.switch_labels else {} ), **( {"done": self.done_chunks[trajectory][start]} if self.done_chunks else {} ), } sample = self.dataset[index] positions = self.dataset.trajectories["observations"][trajectory]["state"][ :, 18:21 ] length = len(self.dataset.trajectories["actions"][trajectory]) if len(positions) != length + 1: raise ValueError("Expected terminal TCP observation for stationary padding") times = torch.arange(start, start + self.dataset.num_queries).clamp(max=length) actions = sample["actions"].clone() # Native labels contain already bounded normalized delta commands. Do not # clip the resulting chunk targets: legitimate offsets can exceed +/-1. actions[:, :3] += (positions[times] - positions[start]) / 0.1 return {"observations": sample["observations"], "actions": actions} class TargetTransportConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) wrapped: Any """Agent or environment at the existing native evaluator boundary.""" action_encoding: ActionEncoding = "controller" """Position-only scaled world goals, or world xyz plus 6D rotation goals.""" chunk_anchor: ChunkAnchor = "chunk_start_tcp" """Frame the model's output is expressed in; must match its training labels.""" class TargetFrameAgent: """Express all predicted TCP goals in one frame before native ensembling.""" def __init__(self, config: TargetTransportConfig): self.config = config self.wrapped = config.wrapped def __getattr__(self, name): return getattr(self.wrapped, name) def get_action(self, obs): target = self.wrapped.get_action(obs).clone() if self.config.action_encoding == "rotation6d": # Restore with the SAME frame the labels were written in. return chunk_relative_to_world( target, resolve_anchor(obs["state"][:, None, 18:25], self.config.chunk_anchor), ) if self.config.chunk_anchor != "chunk_start_tcp": raise ValueError("Absolute anchors require the pose6D encoding") target[:, :, :3] += obs["state"][:, None, 18:21] / 0.1 return target class TargetFrameEnv: """Convert the ensembled goal to the current controller delta exactly once.""" def __init__(self, config: TargetTransportConfig): self.config = config self.wrapped = config.wrapped self.current_tcp = None if config.action_encoding == "rotation6d": import gymnasium as gym self.action_space = gym.spaces.Box( -np.inf, np.inf, (self.wrapped.num_envs, 10), dtype=np.float32 ) self.single_action_space = gym.spaces.Box( -np.inf, np.inf, (10,), dtype=np.float32 ) def __getattr__(self, name): return getattr(self.wrapped, name) def remember(self, observation): self.current_tcp = np.array(observation["state"][:, 18:25], copy=True) def reset(self): observation, info = self.wrapped.reset() self.remember(observation) return observation, info def step(self, target): if self.config.action_encoding == "rotation6d": delta = world_to_chunk_relative( torch.as_tensor(target), torch.as_tensor(self.current_tcp) ) action = sixd_to_controller(delta).numpy() else: action = np.array(target, copy=True) action[:, :3] -= self.current_tcp[:, :3] / 0.1 result = self.wrapped.step(action) self.remember(result[0]) return result def evaluation_transport(agent, env, policy): if policy.keypose is not None: return ( FirstKeyposeAgent(FirstKeyposeAgentConfig(agent=agent)), KeyposeEnv(KeyposeEnvConfig(env=env, control=policy.keypose)), ) if policy.method == "chunk_relative": return ( TargetFrameAgent( TargetTransportConfig( wrapped=agent, action_encoding=policy.action_encoding, chunk_anchor=policy.chunk_anchor, ) ), # The environment converts world goals against the real measured TCP # under every anchor mode; that boundary is physical, not a label frame. TargetFrameEnv( TargetTransportConfig( wrapped=env, action_encoding=policy.action_encoding ) ), ) if policy.action_loss.method == "gripper_bce": env = BinaryGripperEnv(BinaryGripperEnvConfig(env=env)) if policy.action_encoding == "rotation6d": return agent, Rotation6DEnv(EncodedEnvConfig(env=env)) return agent, env
"""Small ACT policy variants sharing the pinned visual and transformer components."""
import hashlib
import math
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Literal
import numpy as np
import torch
import torch.nn.functional as F
from pydantic import (
BaseModel,
ConfigDict,
Field,
NonNegativeFloat,
NonNegativeInt,
PositiveFloat,
PositiveInt,
model_validator,
)
from torch import nn
from torch.utils.data import Dataset
from lim.action_encoding import (
ActionEncoding,
EncodedEnvConfig,
Rotation6DEnv,
encoded_dimension,
sixd_to_controller,
)
from lim.action_objective import (
ActionLossConfig,
BinaryGripperEnv,
BinaryGripperEnvConfig,
BinaryGripperModel,
BinaryGripperModelConfig,
pose_reconstruction,
)
from lim.bspline_chunk import demonstration_segments, segment_reconstruction
from lim.chunk_flow import ChunkFlowConfig, ChunkFlowModel, flow_reconstruction
from lim.chunk_coordinates import (
ChunkAnchor,
ChunkGripperSupervision,
ChunkPadding,
ChunkPoseSupervision,
chunk_relative_to_world,
controller_pose_targets,
pose_target_contract,
resolve_anchor,
world_to_chunk_relative,
)
from lim.keypose_context import (
KeyposeContextMode,
KeyposeContextModel,
KeyposeContextModelConfig,
)
from lim.keypose_control import (
KeyposeControlConfig,
KeyposeEnv,
KeyposeEnvConfig,
encode_keypose,
)
from lim.keypose_dense import (
DenseAuxiliaryHead,
DenseAuxiliaryHeadConfig,
read_dense_actions,
)
from lim.keypose_phase import (
DONE_PHASE,
KeyposePhaseHead,
KeyposePhaseHeadConfig,
read_phase_logits,
)
from lim.keypose_policy import FirstKeyposeAgent, FirstKeyposeAgentConfig
from lim.keypose_stop import KeyposeStopHead, KeyposeStopHeadConfig, read_stop_logits
from lim.chunk_done import (
ChunkDoneHead,
ChunkDoneHeadConfig,
labels_from_valid,
batch_done_items,
read_done_logits,
)
from lim.chunk_switch import (
SWITCH_HORIZON,
ChunkSwitchHead,
ChunkSwitchHeadConfig,
read_switch_fraction,
)
from lim.normalization import (
NormalizationConfig,
NormalizedModel,
NormalizedModelConfig,
checked_statistics,
)
class ACTPolicyConfig(BaseModel, frozen=True):
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
method: Literal["cvae", "state_free", "flow", "chunk_relative"] = "cvae"