| import torch | |
| def apply_masks(x, masks): | |
| """ | |
| :param x: [B, N, D] | |
| :param masks: [B, 2, Nq], containing indices (int64) to select from N patches | |
| :return: [B * 2, Nq, D] | |
| """ | |
| B, N, D = x.shape | |
| _, V, Nq = masks.shape # V = 2 views | |
| all_x = [] | |
| for v in range(V): | |
| # masks[:, v, :] -> [B, Nq] | |
| # We need to expand it for gather: | |
| # [B, Nq] -> [B, Nq, D] for gather | |
| idx = masks[:, v, :].unsqueeze(-1).expand(-1, -1, D) # [B, Nq, D] | |
| # Gather along dim=1 (patch dimension) | |
| gathered = torch.gather(x, dim=1, index=idx) # [B, Nq, D] | |
| all_x.append(gathered) | |
| # Concatenate along batch dimension: | |
| # [B, Nq, D] * 2 -> [B*2, Nq, D] | |
| return torch.cat(all_x, dim=0) | |