"""Helpers for folding/unfolding a (B*F)-batched SparseTensor across frames into a dense (B, F*N_max, C) tensor for cross-frame attention. Layout convention: the sparse tensor's `layout` list has length B*F, ordered as [video0_frame0, video0_frame1, ..., video0_frameF-1, video1_frame0, ...]. """ from typing import List, Tuple import torch def pad_per_layout( feats: torch.Tensor, layout: List[slice], n_max: int, ) -> Tuple[torch.Tensor, torch.Tensor]: """Pad each per-layout group of features to n_max with zeros. Args: feats: (T_total, C) layout: list of `BF` slices into the first dim of `feats` n_max: max group size Returns: feats_pad: (BF, n_max, C), zero-padded lengths: (BF,) int64, real per-group length """ bf = len(layout) c = feats.shape[-1] feats_pad = feats.new_zeros((bf, n_max, c)) lengths = torch.zeros(bf, dtype=torch.long, device=feats.device) for i, sl in enumerate(layout): n_i = sl.stop - sl.start feats_pad[i, :n_i] = feats[sl] lengths[i] = n_i return feats_pad, lengths def build_pad_mask(lengths: torch.Tensor, num_frames: int, n_max: int, batch: int) -> torch.Tensor: """Build a (B, F*N_max) boolean mask. True means the token is real (valid). `lengths` is the (BF,) per-frame real length. """ device = lengths.device arange = torch.arange(n_max, device=device).unsqueeze(0) per_frame = arange < lengths.unsqueeze(1) per_frame = per_frame.view(batch, num_frames * n_max) return per_frame def unpad_to_layout( feats_pad: torch.Tensor, layout: List[slice], num_frames: int, n_max: int, ) -> torch.Tensor: """Inverse of pad_per_layout. Takes (B, F*N_max, C) -> (T_total, C). feats_pad is the *folded* tensor; we first unfold to (BF, N_max, C), then slice the real per-frame length back out. """ b = feats_pad.shape[0] c = feats_pad.shape[-1] bf = b * num_frames assert bf == len(layout), f"layout length {len(layout)} != B*F = {bf}" feats_bf = feats_pad.view(b, num_frames, n_max, c).reshape(bf, n_max, c) out_chunks = [] for i, sl in enumerate(layout): n_i = sl.stop - sl.start out_chunks.append(feats_bf[i, :n_i]) return torch.cat(out_chunks, dim=0)