vjxla / src /masks /utils.py
ckadirt's picture
Add files using upload-large-folder tool
7a8c992 verified
Raw
History Blame Contribute Delete
1.27 kB
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
def apply_masks(x, masks, concat=True):
"""
:param x: tensor of shape [B (batch-size), N (num-patches), D (feature-dim)]
:param masks: list of tensors of shape [B, K] containing indices of K patches in [N] to keep
"""
all_x = []
for m in masks:
mask_keep = m.unsqueeze(-1).repeat(1, 1, x.size(-1))
all_x += [torch.gather(x, dim=1, index=mask_keep)]
if not concat:
return all_x
return torch.cat(all_x, dim=0)
def _list_of_index_tensors_to_bool_mask(idxs: list[torch.Tensor],
B: int,
N: int,
device: torch.device) -> torch.BoolTensor:
"""
idxs : list of 1×Ni or Ni×1 tensors of indices (one per sample but any length)
B, N : wanted mask shape [B, N]
"""
mask = torch.zeros(B, N, dtype=torch.bool, device=device)
for i, t in enumerate(idxs):
if i >= B: # safety guard
break
mask[i, t.view(-1).clamp_(0, N - 1)] = True
return mask