File size: 3,487 Bytes
0a3f650 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | """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}
|