torch_world.safety
INFO
本页尚未翻译。 阅读英文版
class FailureMargin
FailureMargin(
latent_shape: int | tuple[int, ...],
hidden: tuple[int, ...] = (256, 256),
delta: float = 0.75,
)A failure classifier on the latents of a frozen world model, read as a signed safety margin l(z).
An MLP scores each latent; margin squashes the score with tanh so that l(z) lies in (-1, 1), is positive on safe latents and negative on failures, and the failure set is {z : l(z) < 0}. The score is trained with two hinges that push safe latents above delta and failures below -delta, each averaged over its own class so that rare failures weigh as much as the safe majority:
loss = mean_safe relu(delta - s(z)) + mean_failure relu(delta + s(z))
Nakamura, Peters and Bajcsy, "Generalizing Safety Beyond Collision-Avoidance via Latent-Space Reachability Analysis", 2025. Paper: https://arxiv.org/abs/2502.00935 Code: https://github.com/CMU-IntentLab/latent-safety
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
latent_shape | `int | tuple[int, ...]` | shape of one latent, for example 128 or (196, 384); latents are flattened. |
hidden | tuple[int, ...] | hidden widths of the MLP. | (256, 256) |
delta | float | hinge margin; the paper leaves it unreported, the reference code uses 0.75. | 0.75 |
Members
| Member | Description |
|---|---|
score | Raw score (...,) of latents (..., *latent_shape), the quantity the hinges train. |
margin | Safety margin l(z) = tanh(score(z)) (...,); negative means failure. |
forward | z (N, *latent_shape) and failure labels (N,) (true or 1 for failures). |
Source code in torch_world/safety/margin.py
class FailureMargin(nn.Module):
"""A failure classifier on the latents of a frozen world model, read as a signed safety margin ``l(z)``.
An MLP scores each latent; ``margin`` squashes the score with ``tanh`` so that ``l(z)`` lies in ``(-1, 1)``, is
positive on safe latents and negative on failures, and the failure set is ``{z : l(z) < 0}``. The score is
trained with two hinges that push safe latents above ``delta`` and failures below ``-delta``, each averaged over
its own class so that rare failures weigh as much as the safe majority:
``loss = mean_safe relu(delta - s(z)) + mean_failure relu(delta + s(z))``
Nakamura, Peters and Bajcsy, "Generalizing Safety Beyond Collision-Avoidance via Latent-Space Reachability Analysis", 2025.
Paper: https://arxiv.org/abs/2502.00935
Code: https://github.com/CMU-IntentLab/latent-safety
Args:
latent_shape: shape of one latent, for example ``128`` or ``(196, 384)``; latents are flattened.
hidden: hidden widths of the MLP.
delta: hinge margin; the paper leaves it unreported, the reference code uses 0.75.
"""
def __init__(self, latent_shape: int | tuple[int, ...], hidden: tuple[int, ...] = (256, 256), delta: float = 0.75):
super().__init__()
self.shape = (latent_shape,) if isinstance(latent_shape, int) else tuple(latent_shape)
self.net = MLP([math.prod(self.shape), *hidden, 1], act=nn.ReLU)
self.delta = delta
def score(self, z: Tensor) -> Tensor:
"""Raw score ``(...,)`` of latents ``(..., *latent_shape)``, the quantity the hinges train."""
return self.net(flat(z, self.shape))[..., 0]
def margin(self, z: Tensor) -> Tensor:
"""Safety margin ``l(z) = tanh(score(z))`` ``(...,)``; negative means failure."""
return self.score(z).tanh()
def forward(self, z: Tensor, failure: Tensor) -> dict[str, Tensor]:
"""``z`` ``(N, *latent_shape)`` and ``failure`` labels ``(N,)`` (true or 1 for failures)."""
s, failure = self.score(z), failure.bool().reshape(-1)
s = s.reshape(-1)
safe_loss = (self.delta - s[~failure]).relu().mean() if (~failure).any() else s.new_zeros(())
failure_loss = (self.delta + s[failure]).relu().mean() if failure.any() else s.new_zeros(())
accuracy = ((s >= 0) != failure).float().mean()
return {
"loss": safe_loss + failure_loss,
"safe_loss": safe_loss,
"failure_loss": failure_loss,
"accuracy": accuracy,
}method score
score(z: Tensor) -> TensorRaw score (...,) of latents (..., *latent_shape), the quantity the hinges train.
Source code in torch_world/safety/margin.py
def score(self, z: Tensor) -> Tensor:
"""Raw score ``(...,)`` of latents ``(..., *latent_shape)``, the quantity the hinges train."""
return self.net(flat(z, self.shape))[..., 0]method margin
margin(z: Tensor) -> TensorSafety margin l(z) = tanh(score(z)) (...,); negative means failure.
Source code in torch_world/safety/margin.py
def margin(self, z: Tensor) -> Tensor:
"""Safety margin ``l(z) = tanh(score(z))`` ``(...,)``; negative means failure."""
return self.score(z).tanh()method forward
forward(z: Tensor, failure: Tensor) -> dict[str, Tensor]z (N, *latent_shape) and failure labels (N,) (true or 1 for failures).
Source code in torch_world/safety/margin.py
def forward(self, z: Tensor, failure: Tensor) -> dict[str, Tensor]:
"""``z`` ``(N, *latent_shape)`` and ``failure`` labels ``(N,)`` (true or 1 for failures)."""
s, failure = self.score(z), failure.bool().reshape(-1)
s = s.reshape(-1)
safe_loss = (self.delta - s[~failure]).relu().mean() if (~failure).any() else s.new_zeros(())
failure_loss = (self.delta + s[failure]).relu().mean() if failure.any() else s.new_zeros(())
accuracy = ((s >= 0) != failure).float().mean()
return {
"loss": safe_loss + failure_loss,
"safe_loss": safe_loss,
"failure_loss": failure_loss,
"accuracy": accuracy,
}class SafetyValue
SafetyValue(
latent_shape: int | tuple[int, ...],
action_dim: int,
hidden: tuple[int, ...] = (512, 512, 512, 512),
gamma: float = 0.9999,
tau: float = 0.005,
bounds: tuple[float, float] = (-1.0, 1.0),
)Safety value function of a latent world model, learned by discounted Hamilton-Jacobi reachability.
The value V(z) is the best worst-case safety margin reachable from latent z: the lowest l the system will ever see when the safety policy acts. Its sign splits the latent space into states from which failure can be avoided forever (V > 0) and states from which it cannot. With continuous actions it is learned as in the paper with DDPG: a critic Q(z, a) regresses the discounted avoid backup on imagined transitions (z, a, z') of the frozen world model, with target networks Q', pi' updated by Polyak averaging, and an actor pi(z) (the safety policy) maximizes the critic:
Q(z, a) <- (1 - gamma) l(z) + gamma min(l(z), Q'(z', pi'(z'))), V(z) = Q(z, pi(z))
critic_loss = (Q(z, a) - target)^2, actor_loss = -Q(z, pi(z)) (the critic held fixed).
Nakamura, Peters and Bajcsy, "Generalizing Safety Beyond Collision-Avoidance via Latent-Space Reachability Analysis", 2025. Paper: https://arxiv.org/abs/2502.00935 Code: https://github.com/CMU-IntentLab/latent-safety
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
latent_shape | `int | tuple[int, ...]` | shape of one latent of the world model; latents are flattened. |
action_dim | int | dimension of one world-model action. | required |
hidden | tuple[int, ...] | hidden widths of the actor and the critic (the paper's DDPG uses four layers of 512). | (512, 512, 512, 512) |
gamma | float | discount; the paper uses 0.9999. gamma < 1 makes the backup a contraction. | 0.9999 |
tau | float | Polyak rate of the target networks (the reference code's 0.005). | 0.005 |
bounds | tuple[float, float] | action range of the safety policy, reached through a tanh. | (-1.0, 1.0) |
Members
| Member | Description |
|---|---|
action | Safety policy pi(z): latents (N, *latent_shape) to actions (N, action_dim) inside bounds. |
q | Critic Q(z, a) (N,); params evaluates it with other parameters (for example detached ones). |
value | Safety value V(z) = Q(z, pi(z)) (N,); positive where failure can be avoided. |
target | Discounted avoid backup (1 - gamma) l(z) + gamma min(l(z), Q'(z', pi'(z'))) (N,). |
forward | Losses on transitions: latents z and z_next (N, *latent_shape), actions (N, action_dim) and margins l(z) (N,). |
update_target | Polyak update of both target networks with rate tau. |
Source code in torch_world/safety/reachability.py
class SafetyValue(nn.Module):
"""Safety value function of a latent world model, learned by discounted Hamilton-Jacobi reachability.
The value ``V(z)`` is the best worst-case safety margin reachable from latent ``z``: the lowest ``l`` the system
will ever see when the safety policy acts. Its sign splits the latent space into states from which failure can be
avoided forever (``V > 0``) and states from which it cannot. With continuous actions it is learned as in the paper
with DDPG: a critic ``Q(z, a)`` regresses the discounted avoid backup on imagined transitions ``(z, a, z')`` of
the frozen world model, with target networks ``Q'``, ``pi'`` updated by Polyak averaging, and an actor ``pi(z)``
(the safety policy) maximizes the critic:
``Q(z, a) <- (1 - gamma) l(z) + gamma min(l(z), Q'(z', pi'(z')))``, ``V(z) = Q(z, pi(z))``
``critic_loss = (Q(z, a) - target)^2``, ``actor_loss = -Q(z, pi(z))`` (the critic held fixed).
Nakamura, Peters and Bajcsy, "Generalizing Safety Beyond Collision-Avoidance via Latent-Space Reachability Analysis", 2025.
Paper: https://arxiv.org/abs/2502.00935
Code: https://github.com/CMU-IntentLab/latent-safety
Args:
latent_shape: shape of one latent of the world model; latents are flattened.
action_dim: dimension of one world-model action.
hidden: hidden widths of the actor and the critic (the paper's DDPG uses four layers of 512).
gamma: discount; the paper uses 0.9999. ``gamma < 1`` makes the backup a contraction.
tau: Polyak rate of the target networks (the reference code's 0.005).
bounds: action range of the safety policy, reached through a ``tanh``.
"""
def __init__(
self,
latent_shape: int | tuple[int, ...],
action_dim: int,
hidden: tuple[int, ...] = (512, 512, 512, 512),
gamma: float = 0.9999,
tau: float = 0.005,
bounds: tuple[float, float] = (-1.0, 1.0),
):
super().__init__()
self.shape = (latent_shape,) if isinstance(latent_shape, int) else tuple(latent_shape)
dim = math.prod(self.shape)
self.actor = MLP([dim, *hidden, action_dim], act=nn.ReLU)
self.critic = MLP([dim + action_dim, *hidden, 1], act=nn.ReLU)
self.actor_target = copy.deepcopy(self.actor).requires_grad_(False)
self.critic_target = copy.deepcopy(self.critic).requires_grad_(False)
self.action_dim, self.gamma, self.tau, self.bounds = action_dim, gamma, tau, bounds
def action(self, z: Tensor, target: bool = False) -> Tensor:
"""Safety policy ``pi(z)``: latents ``(N, *latent_shape)`` to actions ``(N, action_dim)`` inside ``bounds``."""
low, high = self.bounds
u = (self.actor_target if target else self.actor)(flat(z, self.shape)).tanh()
return low + (u + 1) * (high - low) / 2
def q(self, z: Tensor, action: Tensor, target: bool = False, params: dict | None = None) -> Tensor:
"""Critic ``Q(z, a)`` ``(N,)``; ``params`` evaluates it with other parameters (for example detached ones)."""
x = torch.cat([flat(z, self.shape), action], -1)
critic = self.critic_target if target else self.critic
return (critic(x) if params is None else functional_call(critic, params, (x,)))[..., 0]
def value(self, z: Tensor) -> Tensor:
"""Safety value ``V(z) = Q(z, pi(z))`` ``(N,)``; positive where failure can be avoided."""
return self.q(z, self.action(z))
def target(self, margin: Tensor, z_next: Tensor, gamma: float | None = None) -> Tensor:
"""Discounted avoid backup ``(1 - gamma) l(z) + gamma min(l(z), Q'(z', pi'(z')))`` ``(N,)``."""
gamma = self.gamma if gamma is None else gamma
with torch.no_grad():
future = self.q(z_next, self.action(z_next, target=True), target=True)
return (1 - gamma) * margin + gamma * torch.minimum(margin, future)
def forward(
self, z: Tensor, actions: Tensor, z_next: Tensor, margin: Tensor, gamma: float | None = None
) -> dict[str, Tensor]:
"""Losses on transitions: latents ``z`` and ``z_next`` ``(N, *latent_shape)``, ``actions`` ``(N, action_dim)``
and margins ``l(z)`` ``(N,)``. ``gamma=0`` regresses ``Q`` on ``l`` alone (the reference's warm-up)."""
critic_loss = (self.q(z, actions) - self.target(margin, z_next, gamma)).square().mean()
frozen = {k: v.detach() for k, v in self.critic.named_parameters()}
actor_loss = -self.q(z, self.action(z), params=frozen).mean()
return {"loss": critic_loss + actor_loss, "critic_loss": critic_loss, "actor_loss": actor_loss}
def update_target(self):
"""Polyak update of both target networks with rate ``tau``."""
ema_update(self.actor_target, self.actor, 1 - self.tau)
ema_update(self.critic_target, self.critic, 1 - self.tau)method action
action(z: Tensor, target: bool = False) -> TensorSafety policy pi(z): latents (N, *latent_shape) to actions (N, action_dim) inside bounds.
Source code in torch_world/safety/reachability.py
def action(self, z: Tensor, target: bool = False) -> Tensor:
"""Safety policy ``pi(z)``: latents ``(N, *latent_shape)`` to actions ``(N, action_dim)`` inside ``bounds``."""
low, high = self.bounds
u = (self.actor_target if target else self.actor)(flat(z, self.shape)).tanh()
return low + (u + 1) * (high - low) / 2method q
q(
z: Tensor, action: Tensor, target: bool = False, params: dict | None = None
) -> TensorCritic Q(z, a) (N,); params evaluates it with other parameters (for example detached ones).
Source code in torch_world/safety/reachability.py
def q(self, z: Tensor, action: Tensor, target: bool = False, params: dict | None = None) -> Tensor:
"""Critic ``Q(z, a)`` ``(N,)``; ``params`` evaluates it with other parameters (for example detached ones)."""
x = torch.cat([flat(z, self.shape), action], -1)
critic = self.critic_target if target else self.critic
return (critic(x) if params is None else functional_call(critic, params, (x,)))[..., 0]method value
value(z: Tensor) -> TensorSafety value V(z) = Q(z, pi(z)) (N,); positive where failure can be avoided.
Source code in torch_world/safety/reachability.py
def value(self, z: Tensor) -> Tensor:
"""Safety value ``V(z) = Q(z, pi(z))`` ``(N,)``; positive where failure can be avoided."""
return self.q(z, self.action(z))method target
target(
margin: Tensor, z_next: Tensor, gamma: float | None = None
) -> TensorDiscounted avoid backup (1 - gamma) l(z) + gamma min(l(z), Q'(z', pi'(z'))) (N,).
Source code in torch_world/safety/reachability.py
def target(self, margin: Tensor, z_next: Tensor, gamma: float | None = None) -> Tensor:
"""Discounted avoid backup ``(1 - gamma) l(z) + gamma min(l(z), Q'(z', pi'(z')))`` ``(N,)``."""
gamma = self.gamma if gamma is None else gamma
with torch.no_grad():
future = self.q(z_next, self.action(z_next, target=True), target=True)
return (1 - gamma) * margin + gamma * torch.minimum(margin, future)method forward
forward(
z: Tensor,
actions: Tensor,
z_next: Tensor,
margin: Tensor,
gamma: float | None = None,
) -> dict[str, Tensor]Losses on transitions: latents z and z_next (N, *latent_shape), actions (N, action_dim) and margins l(z) (N,). gamma=0 regresses Q on l alone (the reference's warm-up).
Source code in torch_world/safety/reachability.py
def forward(
self, z: Tensor, actions: Tensor, z_next: Tensor, margin: Tensor, gamma: float | None = None
) -> dict[str, Tensor]:
"""Losses on transitions: latents ``z`` and ``z_next`` ``(N, *latent_shape)``, ``actions`` ``(N, action_dim)``
and margins ``l(z)`` ``(N,)``. ``gamma=0`` regresses ``Q`` on ``l`` alone (the reference's warm-up)."""
critic_loss = (self.q(z, actions) - self.target(margin, z_next, gamma)).square().mean()
frozen = {k: v.detach() for k, v in self.critic.named_parameters()}
actor_loss = -self.q(z, self.action(z), params=frozen).mean()
return {"loss": critic_loss + actor_loss, "critic_loss": critic_loss, "actor_loss": actor_loss}method update_target
update_target()Polyak update of both target networks with rate tau.
Source code in torch_world/safety/reachability.py
def update_target(self):
"""Polyak update of both target networks with rate ``tau``."""
ema_update(self.actor_target, self.actor, 1 - self.tau)
ema_update(self.critic_target, self.critic, 1 - self.tau)function fit_safety_value
fit_safety_value(
value: SafetyValue,
model: WorldModel,
margin: FailureMargin,
starts: Tensor,
iterations: int,
warmup: int = 0,
horizon: int = 25,
envs: int = 8,
updates: int = 1,
batch_size: int = 512,
buffer_size: int = 40000,
actor_lr: float = 0.0001,
critic_lr: float = 0.001,
noise: float = 0.1,
generator: torch.Generator | None = None,
) -> dict[str, list[float]]Train value by reachability in imagination; the world model and the margin stay frozen.
envs imagined episodes run in parallel. Each starts from a latent drawn from starts (N, *latent_shape) (encoded dataset frames) and runs horizon steps of model before it is reset, to limit the drift away from the data (the paper's 25). Each iteration steps every episode once, stores the transitions with l(z) in a replay buffer of buffer_size and makes updates AdamW steps on batches of batch_size. Exploration follows the reference code: the actor's action plus Gaussian noise, replaced by a uniform random action whenever the critic judges that one safe (Q >= 0). The first warmup iterations act at random and use gamma = 0, fitting Q to l before the backup starts. Returns the critic and actor losses.
Source code in torch_world/safety/reachability.py
def fit_safety_value(
value: SafetyValue,
model: WorldModel,
margin: FailureMargin,
starts: Tensor,
iterations: int,
warmup: int = 0,
horizon: int = 25,
envs: int = 8,
updates: int = 1,
batch_size: int = 512,
buffer_size: int = 40_000,
actor_lr: float = 1e-4,
critic_lr: float = 1e-3,
noise: float = 0.1,
generator: torch.Generator | None = None,
) -> dict[str, list[float]]:
"""Train ``value`` by reachability in imagination; the world model and the margin stay frozen.
``envs`` imagined episodes run in parallel. Each starts from a latent drawn from ``starts`` ``(N, *latent_shape)``
(encoded dataset frames) and runs ``horizon`` steps of ``model`` before it is reset, to limit the drift away from
the data (the paper's 25). Each iteration steps every episode once, stores the transitions with ``l(z)`` in a
replay buffer of ``buffer_size`` and makes ``updates`` AdamW steps on batches of ``batch_size``. Exploration
follows the reference code: the actor's action plus Gaussian ``noise``, replaced by a uniform random action
whenever the critic judges that one safe (``Q >= 0``). The first ``warmup`` iterations act at random and use
``gamma = 0``, fitting ``Q`` to ``l`` before the backup starts. Returns the ``critic`` and ``actor`` losses.
"""
device = starts.device
model.eval().requires_grad_(False)
margin.eval().requires_grad_(False)
opt = torch.optim.AdamW(
[{"params": value.actor.parameters(), "lr": actor_lr}, {"params": value.critic.parameters(), "lr": critic_lr}]
)
low, high = value.bounds
shape, A = starts.shape[1:], value.action_dim
buffer = {
"z": starts.new_zeros(buffer_size, *shape),
"actions": starts.new_zeros(buffer_size, A),
"z_next": starts.new_zeros(buffer_size, *shape),
"margin": starts.new_zeros(buffer_size),
}
size, head = 0, 0
def draw(n: int) -> Tensor:
return starts[torch.randint(len(starts), (n,), generator=generator).to(device)]
def uniform(n: int) -> Tensor:
return (low + (high - low) * torch.rand(n, A, generator=generator)).to(device)
z, t = draw(envs), 0
log: dict[str, list[float]] = {"critic": [], "actor": []}
for i in range(warmup + iterations):
warm = i < warmup
with torch.no_grad():
if warm:
a = uniform(envs)
else:
a = value.action(z) + noise * torch.randn(envs, A, generator=generator).to(device)
a = a.clamp(low, high)
random = uniform(envs)
a = torch.where((value.q(z, random) >= 0)[:, None], random, a)
z_next = imagine_step(model, z, a)
idx = (head + torch.arange(envs, device=device)) % buffer_size
for k, v in zip(buffer, (z, a, z_next, margin.margin(z))):
buffer[k][idx] = v
head, size = (head + envs) % buffer_size, min(size + envs, buffer_size)
t += 1
z, t = (draw(envs), 0) if t == horizon else (z_next, t)
for _ in range(updates):
b = torch.randint(size, (batch_size,), generator=generator).to(device)
out = value(*(buffer[k][b] for k in buffer), gamma=0.0 if warm else None)
opt.zero_grad()
out["loss"].backward()
opt.step()
value.update_target()
log["critic"].append(out["critic_loss"].item())
log["actor"].append(out["actor_loss"].item())
value.eval()
return logfunction imagine_step
imagine_step(model: WorldModel, z: Tensor, actions: Tensor) -> TensorOne imagined step of the world model from single latents (N, *latent_shape): (N, *latent_shape).
Source code in torch_world/safety/reachability.py
@torch.no_grad()
def imagine_step(model: WorldModel, z: Tensor, actions: Tensor) -> Tensor:
"""One imagined step of the world model from single latents ``(N, *latent_shape)``: ``(N, *latent_shape)``."""
return model.rollout(z[:, None], actions[:, None])[:, -1]class SafetyFilter
SafetyFilter(
model: WorldModel,
value: SafetyValue,
threshold: float = 0.4,
rule: str = "value",
)Least-restrictive latent safety filter: keep the task action unless it leads where the safety value is low.
The world model imagines the next latent under the task's action; if the safety value there stays above threshold the task action runs, otherwise the safety policy pi(z) of the value function takes over:
a = a_task if V(f(z, a_task)) > threshold else pi(z)
A threshold above zero absorbs errors of the learned value and of the predicted latent; the paper uses 0.4 in simulation and 0.3 on hardware. rule="q" checks Q(z, a_task) > threshold instead, which needs no world-model call; the critic was trained on the same imagined transitions, so the two rules agree when it fits.
Nakamura, Peters and Bajcsy, "Generalizing Safety Beyond Collision-Avoidance via Latent-Space Reachability Analysis", 2025. Paper: https://arxiv.org/abs/2502.00935 Code: https://github.com/CMU-IntentLab/latent-safety
Members
| Member | Description |
|---|---|
safe | Whether each task action (B, action_dim) keeps latents (B, *latent_shape) safe (B,). |
wrap | Closed-loop policy observation -> action that filters policy; see FilteredPolicy. |
Source code in torch_world/safety/filter.py
class SafetyFilter:
"""Least-restrictive latent safety filter: keep the task action unless it leads where the safety value is low.
The world model imagines the next latent under the task's action; if the safety value there stays above
``threshold`` the task action runs, otherwise the safety policy ``pi(z)`` of the value function takes over:
``a = a_task if V(f(z, a_task)) > threshold else pi(z)``
A ``threshold`` above zero absorbs errors of the learned value and of the predicted latent; the paper uses 0.4 in
simulation and 0.3 on hardware. ``rule="q"`` checks ``Q(z, a_task) > threshold`` instead, which needs no
world-model call; the critic was trained on the same imagined transitions, so the two rules agree when it fits.
Nakamura, Peters and Bajcsy, "Generalizing Safety Beyond Collision-Avoidance via Latent-Space Reachability Analysis", 2025.
Paper: https://arxiv.org/abs/2502.00935
Code: https://github.com/CMU-IntentLab/latent-safety
"""
def __init__(self, model: WorldModel, value: SafetyValue, threshold: float = 0.4, rule: str = "value"):
if rule not in ("value", "q"):
raise ValueError(f"rule must be 'value' or 'q', not {rule!r}")
self.model, self.value, self.threshold, self.rule = model, value, threshold, rule
@torch.no_grad()
def safe(self, z: Tensor, actions: Tensor) -> Tensor:
"""Whether each task action ``(B, action_dim)`` keeps latents ``(B, *latent_shape)`` safe ``(B,)``."""
if self.rule == "q":
return self.value.q(z, actions) > self.threshold
return self.value.value(imagine_step(self.model, z, actions)) > self.threshold
@torch.no_grad()
def __call__(self, z: Tensor, actions: Tensor) -> tuple[Tensor, Tensor]:
"""Filtered actions ``(B, action_dim)`` and whether the safety policy overrode each ``(B,)``."""
safe = self.safe(z, actions)
return torch.where(safe[:, None], actions, self.value.action(z).to(actions)), ~safe
def wrap(self, policy: Callable[[Tensor], Tensor], **encode) -> "FilteredPolicy":
"""Closed-loop policy ``observation -> action`` that filters ``policy``; see ``FilteredPolicy``."""
return FilteredPolicy(self, policy, encode)method safe
safe(z: Tensor, actions: Tensor) -> TensorWhether each task action (B, action_dim) keeps latents (B, *latent_shape) safe (B,).
Source code in torch_world/safety/filter.py
@torch.no_grad()
def safe(self, z: Tensor, actions: Tensor) -> Tensor:
"""Whether each task action ``(B, action_dim)`` keeps latents ``(B, *latent_shape)`` safe ``(B,)``."""
if self.rule == "q":
return self.value.q(z, actions) > self.threshold
return self.value.value(imagine_step(self.model, z, actions)) > self.thresholdmethod wrap
wrap(policy: Callable[[Tensor], Tensor], **encode) -> FilteredPolicyClosed-loop policy observation -> action that filters policy; see FilteredPolicy.
Source code in torch_world/safety/filter.py
def wrap(self, policy: Callable[[Tensor], Tensor], **encode) -> "FilteredPolicy":
"""Closed-loop policy ``observation -> action`` that filters ``policy``; see ``FilteredPolicy``."""
return FilteredPolicy(self, policy, encode)class FilteredPolicy
FilteredPolicy(
safety_filter: SafetyFilter,
policy: Callable[[Tensor], Tensor],
encode: dict,
)A task policy observation -> action behind a SafetyFilter.
Observations (B, C, H, W) are encoded with model.encode (one frame, on the model's device, encode holding extra keyword arguments). overrides records, per call, which episodes the safety policy took over (B,); reset clears it, and resets the task policy when it has a reset.
Source code in torch_world/safety/filter.py
class FilteredPolicy:
"""A task policy ``observation -> action`` behind a ``SafetyFilter``.
Observations ``(B, C, H, W)`` are encoded with ``model.encode`` (one frame, on the model's device, ``encode``
holding extra keyword arguments). ``overrides`` records, per call, which episodes the safety policy took over
``(B,)``; ``reset`` clears it, and resets the task policy when it has a ``reset``.
"""
def __init__(self, safety_filter: SafetyFilter, policy: Callable[[Tensor], Tensor], encode: dict):
self.filter, self.policy, self.encode = safety_filter, policy, encode
self.device = next(safety_filter.model.parameters()).device
self.overrides: list[Tensor] = []
def reset(self):
self.overrides = []
if hasattr(self.policy, "reset"):
self.policy.reset()
@torch.no_grad()
def __call__(self, observation: Tensor) -> Tensor:
action = torch.as_tensor(self.policy(observation))
z = self.filter.model.encode(observation[:, None].to(self.device), **self.encode)[:, 0]
filtered, override = self.filter(z, action.to(self.device).float())
self.overrides.append(override.cpu())
return filtered.to(action.device)