Skip to content

Tier 1 PR #2: Alternating spatial<->temporal attention - #2

Merged
lauromota-21 merged 1 commit into
sota-upgradefrom
tier1-pr02-alternating-attention
May 22, 2026
Merged

lauromota-21 merged 1 commit into
sota-upgradefrom
tier1-pr02-alternating-attention

Conversation

@lauromota-21

@lauromota-21 lauromota-21 commented May 22, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • `models/st_blocks.py`:
    • `TemporalBlock` — `TransformerEncoderLayer` reshaped to attend over time per sensor.
    • `SpatialBlock` — hand-rolled pre-norm attention block reshaped to attend over sensors per timestep. Accepts `attn_bias` for the adaptive adjacency in PR Tier 1 PR #3: Adaptive learnable adjacency #3.
    • `STAttnStack` — alternates the two blocks in configurable `interleave_order` (`TS` or `ST`).
  • `TrafficTransformer` STAE path now routes through `STAttnStack` and a dedicated head `Linear(seq_length * hidden_dim, pred_len)` per sensor, bypassing the legacy decoder dispatch.
  • New config knobs: `interleave_order`, `num_st_layers`. `seq_length` threaded into `TrafficTransformer` so the head can size itself.

Tests

  • 8 new tests in `tests/test_st_blocks.py` (shape preservation, gradient flow, `interleave_order` validation, `attn_bias` plumbing).
  • Existing STAE smoke tests updated to declare matching `seq_length`.
  • 45 tests total pass locally, `ruff check` clean.

Refs

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.
@lauromota-21
lauromota-21 merged commit a32811b into sota-upgrade May 22, 2026
3 checks passed
@lauromota-21
lauromota-21 deleted the tier1-pr02-alternating-attention branch May 22, 2026 23:39

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The attn_weights attribute is defined in __init__ but never assigned in the forward method. Since nn.TransformerEncoderLayer does not expose attention weights by default, this attribute is currently dead code and may be misleading to users expecting to visualize temporal attention.

Comment on lines +402 to +404
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant