ConsDrive / models /fastvlm_object_driving.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
10.1 kB
"""Stage 3: FastVLM driving model with object-bank tokens and a per-object relation head.
Object rows (dataloader.object_bank: position, heading, speed, size, class, visibility, time unseen)
enter the LM as extra tokens after the fixed inputs and before the action queries, through an MLP
whose last layer is zero-initialised so training starts from the stage-1 behaviour. The LM output at
each object token predicts the expert's relation to that object (ignore / follow / yield); the action
queries read those positions through causal attention.
"""
import torch
import torch.nn.functional as F
from torch import nn
from dataloader.object_bank import DEFAULT_BANK, FEAT_DIM, RELATION_NAMES, RELATION_PAD
from models.fastvlm_driving import FastVLMDrivingModel
from models.utils import summarise_losses
class ObjectTokenAdaptor(nn.Module):
def __init__(self, feat_dim, token_size, hidden_size=256):
super().__init__()
self.type_embed = nn.Parameter(0.02 * torch.randn(1, 1, token_size))
self.mlp = nn.Sequential(nn.Linear(feat_dim, hidden_size), nn.SiLU(True),
nn.Linear(hidden_size, token_size))
nn.init.zeros_(self.mlp[-1].weight)
nn.init.zeros_(self.mlp[-1].bias)
def forward(self, objects):
return self.type_embed + self.mlp(objects)
FEAT_SPEED, FEAT_VISIBLE, FEAT_UNSEEN, FEAT_AGE = 4, 10, 11, 12
# 'full': every bank row; 'visible_only': rows currently in view (no memory of objects that left the
# view or got occluded); 'single_frame': visible_only without the quantities that need association
# over time (speed, time unseen, track age), i.e. what a per-frame detector provides.
FEATURE_MODES = ('full', 'visible_only', 'single_frame')
class FastVLMObjectDrivingModel(FastVLMDrivingModel):
uses_object_tokens = True
def __init__(self, objects=None, **kwargs):
super().__init__(**kwargs)
cfg = dict(objects or {})
self.object_bank_config = {key: cfg.get(key, value) for key, value in DEFAULT_BANK.items()}
self.max_objects = int(self.object_bank_config['max_objects'])
self.relation_loss_weight = float(cfg.get('relation_loss_weight', 0.3))
self.object_dropout_p = float(cfg.get('object_dropout_p', 0.1))
self.feature_mode = str(cfg.get('feature_mode', 'full'))
if self.feature_mode not in FEATURE_MODES:
raise ValueError(f'objects.feature_mode must be one of {FEATURE_MODES}, got {self.feature_mode}')
weights = cfg.get('relation_class_weights', [0.25, 1.0, 1.0])
self.register_buffer('relation_class_weights', torch.tensor(list(weights), dtype=torch.float),
persistent=False)
hidden = self.language_model.hidden_size
self.object_encoder = ObjectTokenAdaptor(FEAT_DIM, hidden, int(cfg.get('hidden_size', 256)))
self.relation_head = nn.Sequential(nn.Linear(hidden, 256), nn.SiLU(True),
nn.Linear(256, len(RELATION_NAMES)))
self._object_outputs = None
self._object_mask = None
self._relation_stats = None
# ------------------------------------------------------------------ inputs
def encode_objects(self, driving_input, batch_size, device):
objects = getattr(driving_input, 'objects', None)
mask = getattr(driving_input, 'object_mask', None)
if objects is None:
objects = torch.zeros(batch_size, self.max_objects, FEAT_DIM, device=device)
mask = torch.zeros(batch_size, self.max_objects, dtype=torch.bool, device=device)
objects = objects.to(device=device, dtype=torch.float32)
mask = mask.to(device=device, dtype=torch.bool)
if self.feature_mode != 'full':
mask = mask & (objects[..., FEAT_VISIBLE] > 0.5)
if self.feature_mode == 'single_frame':
objects = objects.clone()
objects[..., [FEAT_SPEED, FEAT_UNSEEN, FEAT_AGE]] = 0.0
if self.training and self.object_dropout_p > 0:
keep = torch.rand(batch_size, device=device) >= self.object_dropout_p
mask = mask & keep[:, None]
tokens = self.object_encoder(objects) * mask.unsqueeze(-1).to(torch.float32)
return tokens, mask
def forward_model(self, driving_input, adaptor_embeds, driving_labels=None, return_context=False):
fixed_embeds, attention_mask, _ = self.get_fixed_input_embeds(driving_input)
batch_size, device = fixed_embeds.size(0), fixed_embeds.device
object_embeds, object_mask = self.encode_objects(driving_input, batch_size, device)
dtype = self.language_model.model.dtype
input_embeds = torch.cat((fixed_embeds, object_embeds.to(fixed_embeds.dtype), adaptor_embeds), dim=1)
attention_mask = torch.cat((
attention_mask,
object_mask.long(),
torch.ones(adaptor_embeds.shape[:2], dtype=torch.long, device=device),
), dim=1)
outputs = self.language_model.forward(input_embeds.to(dtype=dtype), attention_mask=attention_mask)
n_fixed, n_obj = fixed_embeds.size(1), object_embeds.size(1)
fixed_outputs, object_outputs, adaptor_outputs = outputs.split(
[n_fixed, n_obj, adaptor_embeds.size(1)], dim=1)
self._object_outputs = object_outputs
self._object_mask = object_mask
if return_context:
return adaptor_outputs, fixed_outputs, attention_mask[:, :n_fixed]
return adaptor_outputs
# ------------------------------------------------------------------ outputs
def relation_logits(self):
"""[B, N, 3] relation logits for the object tokens of the last forward pass."""
if self._object_outputs is None:
return None
return self.relation_head(self._object_outputs.float())
def _relation_loss(self, label):
target = getattr(label, 'object_relation', None)
if target is None or self._object_outputs is None:
return None
target = target.to(self._object_outputs.device).clone()
target[~self._object_mask] = RELATION_PAD # objects dropped in encode_objects carry no label
logits = self.relation_logits()
per_object = F.cross_entropy(logits.transpose(1, 2), target, weight=self.relation_class_weights,
ignore_index=RELATION_PAD, reduction='none')
labelled = (target != RELATION_PAD)
per_sample = per_object.sum(1) / labelled.sum(1).clamp_min(1)
counts = labelled.any(1).long()
with torch.no_grad():
# Fixed-shape (correct, total) counts: row 0 = all labelled objects, rows 1.. = per class.
# Fixed shape matters under DDP: per-rank dicts with varying keys would desynchronise
# the epoch-end all-reduce.
pred = logits.argmax(-1)
stats = torch.zeros(len(RELATION_NAMES) + 1, 2, device=logits.device)
stats[0, 0] = (pred[labelled] == target[labelled]).sum()
stats[0, 1] = labelled.sum()
for cls in range(len(RELATION_NAMES)):
sel = labelled & (target == cls)
stats[cls + 1, 0] = (pred[sel] == cls).sum()
stats[cls + 1, 1] = sel.sum()
self._relation_stats = stats
return per_sample * self.relation_loss_weight, counts
@staticmethod
def _stats_to_metrics(stats):
metrics = {}
if stats[0, 1] > 0:
metrics['relation_acc'] = stats[0, 0] / stats[0, 1]
for cls, name in enumerate(RELATION_NAMES):
if stats[cls + 1, 1] > 0:
metrics[f'relation_recall_{name}'] = stats[cls + 1, 0] / stats[cls + 1, 1]
return metrics
@property
def _relation_metrics(self):
stats = getattr(self, '_relation_stats', None)
return None if stats is None else self._stats_to_metrics(stats)
def forward_loss(self, example, per_sample=False):
adaptor_dict = self.adaptors(example)
adaptor_outputs = self.forward_model(example.driving_input, adaptor_dict['inputs'],
driving_labels=example.driving_label)
loss_dict = self.adaptors.compute_loss(adaptor_outputs, adaptor_dict, example)
loss_dict.pop('latent_features', None)
relation = self._relation_loss(example.driving_label)
if relation is not None:
loss_dict['relation_loss'] = relation
losses = {k: v for k, v in loss_dict.items() if k.endswith('loss')}
predictions = {k: v for k, v in loss_dict.items() if not k.endswith('loss')}
if per_sample:
return losses, predictions
return summarise_losses(losses)
def training_step(self, batch, batch_idx=0):
out = super().training_step(batch, batch_idx)
stats = getattr(self, '_relation_stats', None)
self._relation_stats = None
if stats is not None: # per-rank step metrics, no collective involved
for key, value in self._stats_to_metrics(stats).items():
self.log(f'train_metrics/{key}', value, on_step=True, on_epoch=False, sync_dist=False, logger=True)
return out
def on_validation_epoch_start(self):
self._val_relation_stats = torch.zeros(len(RELATION_NAMES) + 1, 2, device=self.device)
def validation_step(self, batch, batch_idx=0):
out = super().validation_step(batch, batch_idx)
stats = getattr(self, '_relation_stats', None)
self._relation_stats = None
if stats is not None:
self._val_relation_stats += stats
return out
def on_validation_epoch_end(self):
stats = getattr(self, '_val_relation_stats', None)
if stats is None:
return
stats = self.trainer.strategy.reduce(stats, reduce_op='sum') # one fixed-shape all-reduce per rank
for key, value in self._stats_to_metrics(stats).items():
self.log(f'val_metrics/{key}', value, on_step=False, on_epoch=True, sync_dist=False, logger=True)
self._val_relation_stats = None