Download models/pim_driving.py from ZenoNing/ConsDrive: direct link, hf CLI and curl.
- Browser
- Download file 9.71 kB
-
https://huggingface.co/ZenoNing/ConsDrive/resolve/main/models/pim_driving.py
- Command line
-
hf download hf://ZenoNing/ConsDrive/models/pim_driving.py
-
curl -L -o pim_driving.py https://huggingface.co/ZenoNing/ConsDrive/resolve/main/models/pim_driving.py
9.71 kB
| """Single-current-image FastVLM driving with explicit persistent interaction state.""" | |
| from collections import defaultdict | |
| import torch | |
| from torch import nn | |
| from models.driving import DrivingModel | |
| from models.fastvlm import load_fastvlm | |
| from models.pim import PersistentInteractionMemory | |
| from models.pim_losses import interaction_losses | |
| from models.utils import summarise_losses | |
| from utils.pim_types import PIMStepOutput, PIMStreamBatch | |
| class PIMDrivingModel(DrivingModel): | |
| def __init__(self, fastvlm=None, pim=None, vision_model=None, language_model=None, **kwargs): | |
| if (vision_model is None) != (language_model is None): | |
| raise ValueError('Provide both injected vision/language adapters, or neither') | |
| if vision_model is None: | |
| if fastvlm is None: | |
| raise ValueError('FastVLM configuration is required') | |
| vision_model, language_model = load_fastvlm(**dict(fastvlm)) | |
| super().__init__(vision_model=vision_model, language_model=language_model, **kwargs) | |
| self.pim_cfg = dict(pim or {}) | |
| self.pim_enabled = bool(self.pim_cfg.get('enabled', True)) | |
| self.pim_read_enabled = True | |
| self.pim = None | |
| if self.pim_enabled: | |
| self.pim = PersistentInteractionMemory( | |
| language_model.hidden_size, | |
| slots=int(self.pim_cfg.get('slots', 8)), | |
| memory_dim=int(self.pim_cfg.get('memory_dim', 256)), | |
| heads=int(self.pim_cfg.get('heads', 4)), | |
| observation_threshold=float(self.pim_cfg.get('observation_threshold', .5)), | |
| release_threshold=float(self.pim_cfg.get('release_threshold', .9))) | |
| if self.use_world_loss: | |
| raise ValueError('PIM first release does not combine world-latent supervision') | |
| def forward_step(self, driving_input, timestamp, ego_pose, state=None, reset=None): | |
| images = driving_input.camera_images | |
| if images.ndim == 6 and tuple(images.shape[1:3]) != (1, 1): | |
| raise ValueError('PIM receives one current image; do not pass historical frames') | |
| prefix, prefix_mask, _ = self.get_fixed_input_embeds(driving_input) | |
| if self.use_deepstack: | |
| raise ValueError('PIMDrivingModel expects FastVLM, not the Qwen3-VL video tower') | |
| adaptor = self.adaptors(driving_input)['inputs'] | |
| b, prefix_length = prefix.shape[:2] | |
| parts = [prefix] | |
| n_obs = 0 | |
| if self.pim is not None: | |
| observation_queries = self.pim.observation_queries(b).to(prefix.dtype) | |
| n_obs = observation_queries.shape[1] | |
| parts.append(observation_queries) | |
| parts.append(adaptor.to(prefix.dtype)) | |
| embeddings = torch.cat(parts, 1) | |
| mask = torch.cat((prefix_mask, torch.ones( | |
| b, n_obs + adaptor.shape[1], device=prefix.device, dtype=prefix_mask.dtype)), 1) | |
| embeddings = embeddings.to(next(self.language_model.parameters()).dtype) | |
| # One LM call; observation queries precede action queries. No ground-truth | |
| # answer text, future waypoint or event target is in this sequence. | |
| outputs = self.language_model(embeddings, attention_mask=mask) | |
| actions = outputs[:, prefix_length + n_obs:] | |
| diagnostics = {} | |
| if self.pim is not None: | |
| observations = outputs[:, prefix_length:prefix_length + n_obs] | |
| actions, state, diagnostics = self.pim( | |
| observations.to(self.pim.observation_projection.weight.dtype), | |
| actions.to(self.pim.action_projection.weight.dtype), timestamp, | |
| state=state, reset=reset, ego_pose=ego_pose, | |
| read_enabled=self.pim_read_enabled) | |
| predictions = self.adaptors.driving.get_predictions(actions) | |
| return PIMStepOutput(predictions['speed_wps'], predictions['route'], state, | |
| diagnostics, actions, outputs[:, :prefix_length], prefix_mask) | |
| def forward(self, driving_input, prompt_ids=None, return_context=False): | |
| if self.pim_enabled: | |
| raise RuntimeError('Use forward_step(input,timestamp,ego_pose,state) for PIM; ' | |
| 'implicit state would leak across streams') | |
| return super().forward(driving_input, prompt_ids, return_context) | |
| def forward_loss(self, example, per_sample=False): | |
| if not isinstance(example, PIMStreamBatch): | |
| if self.pim_enabled: | |
| raise TypeError('PIM training requires PIMStreamBatch from PIMDataModule') | |
| return super().forward_loss(example, per_sample) | |
| t_steps = len(example.frames) | |
| if t_steps == 0: | |
| raise ValueError('Empty temporal stream') | |
| burn_in = int(self.pim_cfg.get('burn_in', 0)) if self.pim_enabled else 0 | |
| tbptt = int(self.pim_cfg.get('tbptt_steps', 4)) | |
| if burn_in >= t_steps or tbptt < 1: | |
| raise ValueError('burn_in must be smaller than stream length; tbptt_steps >= 1') | |
| state = None # New sampled stream; never inherit a different minibatch. | |
| collected = defaultdict(list) | |
| predictions = {} | |
| for t, frame in enumerate(example.frames): | |
| if state is not None and t % tbptt == 0: | |
| state = state.detach() | |
| output = self.forward_step(frame.driving_input, example.timestamps[:, t], | |
| example.ego_poses[:, t], state) | |
| state = output.state | |
| adaptor_dict = self.adaptors(frame) | |
| losses = self.adaptors.compute_loss(output.action_features, adaptor_dict, frame) | |
| predictions = {k: v for k, v in losses.items() if not k.endswith('loss')} | |
| if t >= burn_in: | |
| for name, pair in losses.items(): | |
| if name.endswith('loss'): | |
| collected[name].append(pair) | |
| if self.use_consequence_loss: | |
| extra = self.compute_consequence_losses( | |
| output.scene_tokens, output.scene_mask, output.route, | |
| output.speed_wps, frame.driving_label) | |
| for name, pair in extra.items(): | |
| collected[name].append(pair) | |
| if self.pim_enabled: | |
| targets = example.labels[t] | |
| if targets is None and self.pim_cfg.get('require_labels', True): | |
| raise ValueError('PIM lifecycle labels missing; see docs/PIM.md') | |
| for name, pair in interaction_losses( | |
| output.diagnostics, targets, | |
| float(self.pim_cfg.get('event_loss_weight', .2))).items(): | |
| collected[name].append(pair) | |
| merged = {name: (torch.cat([p[0].reshape(-1) for p in pairs]), | |
| torch.cat([p[1].reshape(-1) for p in pairs])) | |
| for name, pairs in collected.items()} | |
| return (merged, predictions) if per_sample else summarise_losses(merged) | |
| def _stream_step(self, batch, mode): | |
| output = self.forward_loss(batch) | |
| batch_size = (batch.timestamps.shape[0] if isinstance(batch, PIMStreamBatch) | |
| else batch.driving_input.vehicle_speed.shape[0]) | |
| for name, value in output.loss_averages.items(): | |
| count = output.loss_counts[name].sum().detach().to(value.dtype) | |
| totals = torch.stack((value.detach() * count, count)) | |
| # All ranks must make the same logging decision for sparse labels. | |
| if torch.distributed.is_available() and torch.distributed.is_initialized(): | |
| torch.distributed.all_reduce(totals) | |
| global_count = int(totals[1].item()) | |
| if global_count: | |
| self.log(f'{mode}_losses/{name}', totals[0] / totals[1], | |
| batch_size=global_count, on_step=mode == 'train', | |
| on_epoch=True, sync_dist=False) | |
| self.log(f'{mode}/loss', output.loss, batch_size=batch_size, | |
| on_step=mode == 'train', on_epoch=True, prog_bar=True) | |
| return output.loss | |
| def training_step(self, batch, batch_idx=0): | |
| return self._stream_step(batch, 'train') | |
| def validation_step(self, batch, batch_idx=0): | |
| return self._stream_step(batch, 'val') | |
| def predict_step(self, batch, batch_idx=0): | |
| output = self.forward_loss(batch) | |
| return {k: v.detach().cpu() for k, v in output.loss_averages.items()} | |
| def configure_optimizers(self): | |
| # Explicit groups cover new query, GRU and projection parameters and avoid | |
| # assumptions in the legacy parameter-name whitelist. | |
| groups = defaultdict(list) | |
| for name, parameter in self.named_parameters(): | |
| if not parameter.requires_grad: | |
| continue | |
| lr = self.lr | |
| if name.startswith('vision_model.'): | |
| lr = self.vision_lr if self.vision_lr is not None else self.lr | |
| elif name.startswith('language_model.') and self.lm_lr is not None: | |
| lr = self.lm_lr | |
| decay = self.weight_decay if parameter.ndim > 1 and 'query_embeds' not in name else 0. | |
| groups[(lr, decay)].append(parameter) | |
| optimizer = torch.optim.AdamW([ | |
| {'params': params, 'lr': lr, 'weight_decay': decay} | |
| for (lr, decay), params in groups.items()], betas=self.betas) | |
| steps = self.trainer.estimated_stepping_batches | |
| scheduler = torch.optim.lr_scheduler.LambdaLR( | |
| optimizer, lambda s: min(1., (s + 1) / max(1., self.pct_start * steps))) | |
| return {'optimizer': optimizer, 'lr_scheduler': { | |
| 'scheduler': scheduler, 'interval': 'step', 'frequency': 1}} | |