Repository navigation
Tier 1 PR #2: Alternating spatial<->temporal attention - #2
Conversation
Replaces the PR#1 placeholder ``mean(dim=2)`` in ``_stae_encode`` with a full alternating spatial/temporal transformer stack on the [B, T, N, d] tensor, matching STAEformer's encoder design. New module ``src/visu_predict/models/st_blocks.py``: - TemporalBlock: TransformerEncoderLayer reshaped to attend over T per sensor ([B,T,N,d] -> [B*N,T,d] -> back). - SpatialBlock: hand-rolled pre-norm attention block reshaped to attend over N per timestep ([B,T,N,d] -> [B*T,N,d] -> back). Accepts an optional attn_bias [num_heads, N, N] for the adaptive-adjacency hook in PR #3. - STAttnStack: alternates ``TemporalBlock`` and ``SpatialBlock`` in configurable interleave order ("TS" or "ST") for ``num_layers`` outer layers (2*num_layers sub-blocks total). TrafficTransformer changes: - Instantiates STAttnStack and a dedicated STAE output head ``Linear(seq_length * hidden_dim, pred_len)`` applied per sensor. - ``_stae_encode`` now returns the full [B, T, N, d_model] tensor. - ``forward`` routes STAE through the new head, bypassing the legacy decoder dispatch: ``[B, T, N, d] -> [B, pred_len, N]``. Config: - ``interleave_order: str = "TS"`` (validated when STAE is active) - ``num_st_layers: int | None = None`` (defaults to num_layers) - New ``seq_length`` kwarg threaded into TrafficTransformer so the head can be sized at construction time. Tests: 8 new tests for st_blocks (shape preservation, gradient flow, interleave-order validation, attn_bias plumbing). Existing STAE smoke tests updated to declare matching seq_length. 45 tests pass; ruff clean. Legacy path unchanged.
There was a problem hiding this comment.
Code Review
This pull request implements an alternating spatial-temporal transformer stack (STAttnStack) for the STAE pipeline, replacing the previous mean-pooling reduction. Key additions include TemporalBlock and SpatialBlock modules, configuration options for interleaving order, and a dedicated STAE output head in the TrafficTransformer. Feedback focuses on mitigating significant GPU memory overhead caused by detached attention weight storage in SpatialBlock, removing dead code in TemporalBlock, and adding input validation to the STAE head to prevent runtime errors from sequence length mismatches.
| if attn_bias is not None: | ||
| logits = logits + attn_bias | ||
| attn = F.softmax(logits, dim=-1) | ||
| self.attn_weights = attn.detach() |
There was a problem hiding this comment.
Storing attn.detach() in self.attn_weights during every forward pass can lead to significant GPU memory overhead, especially for datasets with a large number of sensors (e.g., PEMS-07 with 882 sensors). For a batch size of 16 and sequence length of 12, this tensor alone consumes approximately 9.5 GB per layer. Consider removing this assignment or making it optional via a need_weights flag to avoid out-of-memory errors during training.
| self.attn_weights = attn.detach() | |
| # self.attn_weights = attn.detach() # Removed to prevent excessive GPU memory consumption |
| batch_first=True, | ||
| activation="gelu", | ||
| ) | ||
| self.attn_weights: torch.Tensor | None = None |
There was a problem hiding this comment.
| bsz, seq_len, num_sensors, d_model = memory.shape | ||
| # rearrange to [B, N, T, d_model] -> [B, N, T*d_model] | ||
| flat = memory.permute(0, 2, 1, 3).reshape(bsz, num_sensors, seq_len * d_model) |
There was a problem hiding this comment.
The stae_head linear layer is initialized with a fixed seq_length. If the input src has a different temporal dimension than the seq_length provided at initialization, the reshape operation on line 404 will succeed, but the subsequent call to self.stae_head(flat) will trigger a RuntimeError due to a dimension mismatch. It is recommended to validate that the dynamic seq_len matches self.stae_seq_length before the projection.
| bsz, seq_len, num_sensors, d_model = memory.shape | |
| # rearrange to [B, N, T, d_model] -> [B, N, T*d_model] | |
| flat = memory.permute(0, 2, 1, 3).reshape(bsz, num_sensors, seq_len * d_model) | |
| bsz, seq_len, num_sensors, d_model = memory.shape | |
| if seq_len != self.stae_seq_length: | |
| raise ValueError( | |
| f"Input sequence length ({seq_len}) does not match " | |
| f"STAE head sequence length ({self.stae_seq_length})" | |
| ) | |
| # rearrange to [B, N, T, d_model] -> [B, N, T*d_model] |
Summary
Replaces the PR #1 placeholder `mean(dim=2)` in `_stae_encode` with a full alternating spatial/temporal transformer stack on the `[B, T, N, d]` tensor, matching STAEformer's encoder design. This is the PR that actually unlocks STAEformer's benefit.
What's new
Tests
Refs