keypose-vs-dense / fair-comparison /flow-v1 /code /lim /act_optimization.py
OpenGHz's picture
Add fair-comparison/flow-v1
0a3f650 verified
Raw History Blame Contribute Delete
3.49 kB
"""Isolated training-only ACT candidates; inference stays on the native path."""
from typing import Literal
import torch
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, NonNegativeInt, PositiveFloat
class ACTOptimizationConfig(BaseModel, frozen=True):
model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
method: Literal["control", "random_shift", "near_action", "deterministic"] = (
"control"
)
"""One isolated candidate; methods are not combined during screening."""
shift_pixels: NonNegativeInt = 4
"""Symmetric replicated-image padding before integer random cropping."""
horizon_decay: PositiveFloat = 10.0
"""Exponential L1 weighting time scale, in predicted actions."""
augmentation_seed: NonNegativeInt = 20260915
"""Private augmentation RNG, independent of sampling and native dropout/latent RNG."""
def shift_rgb(rgb, pad, generator):
"""Translate each sample/camera equally across channels, without interpolation."""
if pad == 0:
return rgb
batch, cameras, channels, height, width = rgb.shape
flat = rgb.reshape(batch * cameras, channels, height, width)
padded = F.pad(flat, (pad, pad, pad, pad), mode="replicate")
shifts = torch.randint(
2 * pad + 1, (batch * cameras, 2), device=rgb.device, generator=generator
)
ys = (
torch.arange(height, device=rgb.device)[None, :, None]
+ shifts[:, 0, None, None]
)
xs = (
torch.arange(width, device=rgb.device)[None, None, :] + shifts[:, 1, None, None]
)
indices = torch.arange(batch * cameras, device=rgb.device)[:, None, None]
# NHWC indexing keeps all channels at the same spatial displacement.
return (
padded.permute(0, 2, 3, 1)[indices, ys, xs]
.permute(0, 3, 1, 2)
.reshape(batch, cameras, channels, height, width)
)
class ACTTrainingObjective:
def __init__(self, config: ACTOptimizationConfig):
self.config = config
self.generator = None
def compute_loss(self, agent, native, obs, actions):
method = self.config.method
if method == "control":
return agent.compute_loss(obs=obs, action_seq=actions)
if method == "random_shift":
if self.generator is None:
self.generator = torch.Generator(device=obs["rgb"].device)
self.generator.manual_seed(self.config.augmentation_seed)
obs = dict(obs)
obs["rgb"] = shift_rgb(obs["rgb"], self.config.shift_pixels, self.generator)
return agent.compute_loss(obs=obs, action_seq=actions)
obs = dict(obs)
obs["rgb"] = agent.normalize(obs["rgb"].float() / 255.0)
if method == "deterministic":
prediction, _ = agent.model(obs) # Same zero latent used during deployment.
l1 = F.l1_loss(prediction, actions)
return {"loss": l1, "l1": l1, "kl": l1.new_zeros(())}
prediction, (mu, logvar) = agent.model(obs, actions)
error = F.l1_loss(prediction, actions, reduction="none")
weights = torch.exp(
-torch.arange(actions.shape[1], device=actions.device, dtype=error.dtype)
/ self.config.horizon_decay
)
weights = weights / weights.mean()
l1 = (error * weights[None, :, None]).mean()
kl = native.kl_divergence(mu, logvar)[0][0]
return {"loss": l1 + agent.kl_weight * kl, "l1": l1, "kl": kl}