ConsDrive / models /adaptors /adaptors.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
13.5 kB
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from utils.custom_types import DrivingExample
def compute_waypoint_loss(
prediction: Tensor,
label: Tensor,
loss_fn: str = "mse",
smooth_l1_beta: float = 1.0,
) -> Tensor:
"""Per-sample waypoint loss averaged over waypoints; last dim is (x, y) or distance."""
if loss_fn == "mse":
return F.mse_loss(prediction, label, reduction="none").sum(-1).mean(-1)
if loss_fn == "smooth_l1":
return F.smooth_l1_loss(
prediction,
label,
beta=smooth_l1_beta,
reduction="none",
).sum(-1).mean(-1)
raise ValueError(f"waypoint_loss_fn must be 'mse' or 'smooth_l1', not {loss_fn!r}")
class NormZeroOne(nn.Module):
def __init__(self, min_max: Tuple[float, float]):
super().__init__()
self.register_buffer("min_max", torch.tensor(min_max, dtype=torch.float), persistent=False)
def forward(self, x: Tensor) -> Tensor:
"""Normalise tensor to [0, 1] using values from min_max"""
return (x - self.min_max[0]) / (self.min_max[1] - self.min_max[0])
class WaypointInputAdaptor(nn.Module):
"""
Takes an input of shape [B, N, 2] and returns an output of shape [B, N, token_size]
Args:
token_size: feature dimension of output tensor.
hidden_size: hidden dimension used in Linear layers under the hood.
norm_layer: the `Module` to use to normalize the values of the input tensor.
"""
def __init__(
self, token_size: int = 258, hidden_size: int = 64, norm_layer: Optional[nn.Module] = None
):
super().__init__()
self.hidden_size = hidden_size
self.norm_layer = norm_layer
self.mlp = nn.Sequential(nn.Linear(2, hidden_size), nn.ReLU(True), nn.Linear(hidden_size, token_size))
def forward(self, x: Tensor) -> Tensor:
"""
Args:
x: Input with dims [B, N, 2]
Returns:
Output with dims [B, N, token_size]
"""
if self.norm_layer is not None:
x = self.norm_layer(x)
x = self.mlp(x)
return x
class VectorInputAdaptor(nn.Module):
"""
Takes an input of shape [B, input_size] and returns an output of shape [B, 1, token_size]
Args:
input_size: Expected feature dimension of input tensor.
token_size: feature dimension of output tensor.
hidden_size: hidden dimension used in Linear layers under the hood.
norm_layer: the `Module` to use to normalize the values of the input tensor.
"""
def __init__(
self,
input_size: int,
token_size: int = 258,
hidden_size: int = 64,
norm_layer: Optional[nn.Module] = None,
):
super().__init__()
# store args
self.hidden_size = hidden_size
self.input_size = input_size
self.norm_layer = norm_layer
# networks
self.mlp = nn.Sequential(nn.Linear(input_size, hidden_size), nn.ReLU(True), nn.Linear(hidden_size, token_size))
def forward(self, x: Tensor) -> Tensor:
"""
Args:
x: Input with dims [B, input_size]
Returns:
Output with dims [B, 1, token_size]
"""
if self.norm_layer is not None:
x = self.norm_layer(x)
x = self.mlp(x).unsqueeze(1)
return x
class DrivingAdaptor(nn.Module):
def __init__(self,
hidden_size: int,
mlp_dim=256,
predict_route_as_wps=False,
speed_wps_mode=False,
waypoint_loss_fn: str = "mse",
smooth_l1_beta: float = 1.0,
latent_tokens: int = 0,
):
super().__init__()
self.heads = {}
self.queries = {}
self.sizes = {}
self.order = []
self.speed_wps_mode = speed_wps_mode
self.predict_route_as_wps = predict_route_as_wps
self.waypoint_loss_fn = waypoint_loss_fn
self.smooth_l1_beta = smooth_l1_beta
# Latent world-model queries: no prediction head, the LM hidden states
# at these positions are supervised through the world predictor.
# Placed first so route/speed queries can attend to them (causal LM).
self.num_latent_tokens = int(latent_tokens)
if self.num_latent_tokens > 0:
self.query_embeds_latent = nn.Parameter(
0.02 * torch.randn((1, self.num_latent_tokens, hidden_size))
)
self.queries['latent'] = self.query_embeds_latent
self.sizes['latent'] = self.num_latent_tokens
self.order.append('latent')
if predict_route_as_wps:
self.future_waypoints = 20
self.query_embeds_wps = nn.Parameter(0.02 * torch.randn((1, self.future_waypoints, hidden_size)))
self.route_head = nn.Sequential(
nn.Linear(hidden_size, mlp_dim), nn.SiLU(True), nn.Linear(mlp_dim, 2, bias=False)
)
self.queries['route'] = self.query_embeds_wps
self.sizes['route'] = self.future_waypoints
self.heads["route"] = self.route_head
self.order.append('route')
if speed_wps_mode == '2d':
dim = 2
elif speed_wps_mode == '1d':
dim = 1
else:
raise ValueError(f"speed_wps_mode must be '1d' or '2d', not {speed_wps_mode}")
self.future_speed_waypoints = 10
self.query_embeds_speed = nn.Parameter(0.02 * torch.randn((1, self.future_speed_waypoints, hidden_size)))
self.speed_wps_head = nn.Sequential(
nn.Linear(hidden_size, mlp_dim), nn.SiLU(True), nn.Linear(mlp_dim, dim, bias=False)
)
self.heads["speed_wps"] = self.speed_wps_head
self.queries['speed_wps'] = self.query_embeds_speed
self.sizes['speed_wps'] = self.future_speed_waypoints
self.order.append('speed_wps')
def _head_input(self, input_type: str, features: Tensor) -> Tensor:
head_dtype = next(self.heads[input_type].parameters()).dtype
return features.to(dtype=head_dtype)
def forward(self,
driving_example: DrivingExample,
**kwargs
) -> Dict[str, Tensor]:
try:
driving_input = driving_example.driving_input
except AttributeError:
driving_input = driving_example
b = driving_input.vehicle_speed.shape[0]
inputs = None
for input_type in self.order:
query_embed = self.queries[input_type]
if inputs is None:
inputs = query_embed.expand(b, -1, -1)
else:
inputs = torch.cat((inputs, query_embed.expand(b, -1, -1)), dim=1)
inputs_mask = torch.ones_like(inputs[:, :, 0], dtype=torch.bool)
return {"inputs": inputs, "inputs_mask": inputs_mask}
def get_predictions(
self,
features: Tensor
) -> Dict:
current_index = 0
predictions = {}
for i, input_type in enumerate(self.order):
size = self.sizes[input_type]
if input_type not in self.heads:
# latent world-model queries have no prediction head
current_index += size
continue
feature = self._head_input(input_type, features[:, current_index: current_index + size])
prediction = self.heads[input_type](feature).cumsum(1)
predictions[input_type] = prediction
current_index += size
return predictions
def compute_loss(
self, adaptor_features: Tensor, _inputs: Dict[str, Tensor], example: DrivingExample
) -> Dict[str, Tuple[Tensor, Tensor]]:
label = example.driving_label
assert label is not None
if self.predict_route_as_wps:
label_route = label.route_adjusted
else:
label_route = None
if self.speed_wps_mode == '2d':
label_speed_wps = label.waypoints[:, : self.future_speed_waypoints]
elif self.speed_wps_mode == '1d':
label_speed_wps = label.waypoints_1d
else:
label_speed_wps = None
current_index = 0
loss_dict = {}
for i, input_type in enumerate(self.order):
size = self.sizes[input_type]
if input_type not in self.heads:
# expose the raw LM features (e.g. latent world-model tokens)
# to the caller instead of applying a head/loss
loss_dict[f"{input_type}_features"] = adaptor_features[:, current_index: current_index + size]
current_index += size
continue
features_tmp = self._head_input(input_type, adaptor_features[:, current_index: current_index + size])
label = locals()[f'label_{input_type}']
prediction = self.heads[input_type](features_tmp).cumsum(1)
loss = compute_waypoint_loss(
prediction,
label,
loss_fn=self.waypoint_loss_fn,
smooth_l1_beta=self.smooth_l1_beta,
)
loss_dict[f"{input_type}_loss"] = (loss, torch.ones_like(loss, dtype=torch.long))
loss_dict[f"{input_type}_prediction"] = prediction
loss_dict[f"{input_type}_label"] = label
current_index += size
return loss_dict
class AdaptorList(nn.Module):
"""
Each adaptor is responsible for converting a driving example
to a sequence of tokens and computing the loss on the token outputs.
Adaptors are only used during training.
"""
def __init__(
self,
driving: Optional[DrivingAdaptor] = None,
):
super().__init__()
self.driving = driving
@property
def adaptors(self):
dct: Dict[str, Adaptor] = {}
if self.driving is not None:
dct["driving"] = self.driving
return dct
def forward(self, example: DrivingExample) -> Dict[str, Tensor]:
"""
Construct input embeddings for the given driving example.
"""
input_dict: Dict[str, Tensor] = {}
inputs_list: List[Tensor] = []
inputs_mask_list: List[Tensor] = []
for key, adaptor in self.adaptors.items():
adaptor_input_dict = adaptor.forward(example)
inputs_list.append(adaptor_input_dict["inputs"])
inputs_mask_list.append(adaptor_input_dict["inputs_mask"])
input_dict.update({key + "_" + k: v for k, v in adaptor_input_dict.items()})
inputs = torch.cat(inputs_list, dim=1)
inputs_mask = torch.cat(inputs_mask_list, dim=1)
split_sizes = torch.as_tensor([x.size(1) for x in inputs_list])
arange = torch.arange(inputs.size(0), device=inputs.device)[:, None]
# Apply random permutation of modalities during training
rand_perm = torch.arange(inputs.size(1), device=inputs.device).expand(inputs.size(0), -1)
# Apply permutation to move invalid tokens to end of sequence
valid_perm = inputs_mask[arange, rand_perm].byte().argsort(dim=-1, descending=True, stable=True)
perm = rand_perm.gather(1, valid_perm)
input_dict["inputs"] = inputs[arange, perm]
input_dict["inputs_mask"] = inputs_mask[arange, perm]
input_dict["perm"] = perm
input_dict["split_sizes"] = split_sizes
return input_dict
def compute_loss(
self, features: Tensor, input_dict: Dict[str, Tensor], example: DrivingExample
) -> Dict[str, Tuple[Tensor, Tensor]]:
"""
Distributes the output embeddings from the transformer to
the correct loss function and returns a dictionary of losses.
"""
features_by_adaptor = self.split_outputs_by_adaptor(input_dict, features)
loss_dict: Dict[str, Tuple[Tensor, Tensor]] = {}
# Compute loss in each adaptor
loss_dict: Dict[str, Tuple[Tensor, Tensor]] = {}
for key, adaptor in self.adaptors.items():
adaptor_input_dict = _gather_from_dict(input_dict, key + "_")
adaptor_features = features_by_adaptor[key]
losses = adaptor.compute_loss(adaptor_features, adaptor_input_dict, example)
loss_dict.update(losses)
return loss_dict
def split_outputs_by_adaptor(self, input_dict: Dict[str, Tensor], outputs: Tensor) -> Dict[str, Tensor]:
"""
Splits the output tensor into the correct output for each adaptor, according to the
split_sizes in the input_dict.
"""
# First reverse permutation
inv_perm = input_dict["perm"].argsort(-1)
arange = torch.arange(inv_perm.size(0), device=inv_perm.device)[:, None]
outputs = outputs[arange, inv_perm]
# Now split output for each adaptor
split_sizes = [int(x) for x in input_dict["split_sizes"]]
outputs_list = list(outputs.split(split_sizes, dim=1))
return {key: outputs_list[i] for i, key in enumerate(self.adaptors.keys())}
def _gather_from_dict(d: Dict[str, Tensor], prefix: str):
out: Dict[str, Tensor] = {} # dict comprehensions with if not supported
for k, v in d.items():
if k.startswith(prefix):
out[k[len(prefix) :]] = v
return out