Skip to content

torch_world.masks ​

INFO

Esta página aún no está traducida. Leer en inglés

class MultiBlockMask ​

torch_world.masks.MultiBlockMask GitHub

python
MultiBlockMask(
    grid: tuple[int, int],
    enc_scale: tuple[float, float] = (0.85, 1.0),
    pred_scale: tuple[float, float] = (0.15, 0.2),
    aspect_ratio: tuple[float, float] = (0.75, 1.5),
    num_enc: int = 1,
    num_pred: int = 4,
    min_keep: int = 10,
    allow_overlap: bool = False,
)

I-JEPA multi-block masking on a 2D patch grid.

Samples num_pred target blocks and num_enc context blocks per image. Context blocks avoid the targets unless allow_overlap. Block sizes are shared across the batch, and every mask is cropped to the shortest one so masks stack into (B, K) index tensors.

Source code in torch_world/masks/multiblock.py
python
class MultiBlockMask:
    """I-JEPA multi-block masking on a 2D patch grid.

    Samples ``num_pred`` target blocks and ``num_enc`` context blocks per image. Context blocks avoid the
    targets unless ``allow_overlap``. Block sizes are shared across the batch, and every mask is cropped
    to the shortest one so masks stack into ``(B, K)`` index tensors.
    """

    def __init__(
        self,
        grid: tuple[int, int],
        enc_scale: tuple[float, float] = (0.85, 1.0),
        pred_scale: tuple[float, float] = (0.15, 0.2),
        aspect_ratio: tuple[float, float] = (0.75, 1.5),
        num_enc: int = 1,
        num_pred: int = 4,
        min_keep: int = 10,
        allow_overlap: bool = False,
    ):
        self.height, self.width = grid
        self.enc_scale, self.pred_scale, self.aspect_ratio = enc_scale, pred_scale, aspect_ratio
        self.num_enc, self.num_pred = num_enc, num_pred
        self.min_keep = min_keep
        self.allow_overlap = allow_overlap

    def _block_size(self, scale, aspect_ratio, g) -> tuple[int, int]:
        u = torch.rand(1, generator=g).item()
        keep = int(self.height * self.width * _uniform(scale, u))
        ar = _uniform(aspect_ratio, u)
        h = min(round(math.sqrt(keep * ar)), self.height - 1)
        w = min(round(math.sqrt(keep / ar)), self.width - 1)
        return h, w

    def _block(self, size, g, regions: list[Tensor] | None = None) -> tuple[Tensor, Tensor]:
        h, w = size
        if h * w <= self.min_keep:
            raise ValueError(f"a {h}x{w} block never keeps more than min_keep={self.min_keep} patches")
        tries, timeout = 0, 20
        while True:
            top = torch.randint(0, self.height - h, (1,), generator=g).item()
            left = torch.randint(0, self.width - w, (1,), generator=g).item()
            block = torch.zeros(self.height, self.width, dtype=torch.bool)
            block[top : top + h, left : left + w] = True
            mask = block.clone()
            for region in (regions or [])[: max(len(regions or []) - tries, 0)]:
                mask &= region
            idx = mask.flatten().nonzero().squeeze(-1)
            if len(idx) > self.min_keep:
                return idx, ~block
            timeout -= 1
            if timeout == 0:
                tries, timeout = tries + 1, 20

    def __call__(self, batch_size: int, generator: torch.Generator | None = None) -> tuple[list[Tensor], list[Tensor]]:
        """Return ``(masks_enc, masks_pred)``: lists of ``num_enc`` and ``num_pred`` index tensors of shape ``(B, K)``."""
        g = generator
        p_size = self._block_size(self.pred_scale, self.aspect_ratio, g)
        e_size = self._block_size(self.enc_scale, (1.0, 1.0), g)
        enc, pred = [], []
        for _ in range(batch_size):
            p, complements = zip(*(self._block(p_size, g) for _ in range(self.num_pred)))
            regions = None if self.allow_overlap else list(complements)
            e = [self._block(e_size, g, regions)[0] for _ in range(self.num_enc)]
            pred.append(p)
            enc.append(e)
        return _stack(enc, self.num_enc), _stack(pred, self.num_pred)

class MultiBlock3DMask ​

torch_world.masks.MultiBlock3DMask GitHub

python
MultiBlock3DMask(
    grid: tuple[int, int, int],
    spatial_scale: tuple[float, float] = (0.15, 0.15),
    temporal_scale: tuple[float, float] = (1.0, 1.0),
    aspect_ratio: tuple[float, float] = (0.75, 1.5),
    num_blocks: int = 8,
    max_temporal_keep: float = 1.0,
)

V-JEPA spatio-temporal multi-block masking on a (T, H, W) token grid.

The union of num_blocks tubes is the prediction target; the remaining tokens are the context.

Source code in torch_world/masks/multiblock.py
python
class MultiBlock3DMask:
    """V-JEPA spatio-temporal multi-block masking on a ``(T, H, W)`` token grid.

    The union of ``num_blocks`` tubes is the prediction target; the remaining tokens are the context.
    """

    def __init__(
        self,
        grid: tuple[int, int, int],
        spatial_scale: tuple[float, float] = (0.15, 0.15),
        temporal_scale: tuple[float, float] = (1.0, 1.0),
        aspect_ratio: tuple[float, float] = (0.75, 1.5),
        num_blocks: int = 8,
        max_temporal_keep: float = 1.0,
    ):
        self.duration, self.height, self.width = grid
        self.spatial_scale, self.temporal_scale, self.aspect_ratio = spatial_scale, temporal_scale, aspect_ratio
        self.num_blocks = num_blocks
        self.max_context_duration = max(1, int(self.duration * max_temporal_keep))

    def _block_size(self, g) -> tuple[int, int, int]:
        u = torch.rand(3, generator=g).tolist()
        t = max(1, int(self.duration * _uniform(self.temporal_scale, u[0])))
        keep = int(self.height * self.width * _uniform(self.spatial_scale, u[1]))
        ar = _uniform(self.aspect_ratio, u[2])
        h = min(round(math.sqrt(keep * ar)), self.height)
        w = min(round(math.sqrt(keep / ar)), self.width)
        return t, h, w

    def _context(self, size, g) -> Tensor:
        t, h, w = size
        context = torch.ones(self.duration, self.height, self.width, dtype=torch.bool)
        for _ in range(self.num_blocks):
            top = torch.randint(0, self.height - h + 1, (1,), generator=g).item()
            left = torch.randint(0, self.width - w + 1, (1,), generator=g).item()
            start = torch.randint(0, self.duration - t + 1, (1,), generator=g).item()
            context[start : start + t, top : top + h, left : left + w] = False
        context[self.max_context_duration :] = False
        return context.flatten()

    def __call__(self, batch_size: int, generator: torch.Generator | None = None) -> tuple[list[Tensor], list[Tensor]]:
        """Return ``([mask_enc], [mask_pred])`` with index tensors of shape ``(B, K)``."""
        size = self._block_size(generator)
        enc, pred = [], []
        while len(enc) < batch_size:
            context = self._context(size, generator)
            if context.any():
                enc.append(context.nonzero().squeeze(-1))
                pred.append((~context).nonzero().squeeze(-1))
        return [_crop(enc)], [_crop(pred)]

class BlockwiseMask ​

torch_world.masks.BlockwiseMask GitHub

python
BlockwiseMask(
    grid: tuple[int, int],
    ratio: tuple[float, float] = (0.1, 0.5),
    probability: float = 0.5,
    min_patches: int = 4,
    max_fraction: float = 0.5,
    min_aspect: float = 0.3,
)

Block-wise masking for iBOT, as DINOv2 samples it: boolean (B, N) masks over a 2D patch grid.

int(probability * B) of the B images are masked and the rest are not. Their mask ratios are spread over ratio: the i-th masked image draws its ratio uniformly from the i-th of equal bins. A mask grows by rectangles of at least min_patches patches, at most max_fraction of the grid, and an aspect ratio log-uniform in [min_aspect, 1 / min_aspect], as in BEiT. Masked and unmasked images come in random order.

Reference: dinov2/data/masking.py and dinov2/data/collate.py in facebookresearch/dinov2.

Source code in torch_world/masks/blockwise.py
python
class BlockwiseMask:
    """Block-wise masking for iBOT, as DINOv2 samples it: boolean ``(B, N)`` masks over a 2D patch grid.

    ``int(probability * B)`` of the ``B`` images are masked and the rest are not. Their mask ratios are spread over
    ``ratio``: the ``i``-th masked image draws its ratio uniformly from the ``i``-th of equal bins. A mask grows by
    rectangles of at least ``min_patches`` patches, at most ``max_fraction`` of the grid, and an aspect ratio
    log-uniform in ``[min_aspect, 1 / min_aspect]``, as in BEiT. Masked and unmasked images come in random order.

    Reference: dinov2/data/masking.py and dinov2/data/collate.py in facebookresearch/dinov2.
    """

    def __init__(
        self,
        grid: tuple[int, int],
        ratio: tuple[float, float] = (0.1, 0.5),
        probability: float = 0.5,
        min_patches: int = 4,
        max_fraction: float = 0.5,
        min_aspect: float = 0.3,
    ):
        self.height, self.width = grid
        self.ratio, self.probability = ratio, probability
        self.min_patches = min_patches
        self.max_patches = int(max_fraction * self.height * self.width)
        self.log_aspect = (math.log(min_aspect), -math.log(min_aspect))

    def _add_block(self, mask: Tensor, limit: int, g: torch.Generator | None) -> int:
        """Mask one rectangle that adds between 1 and ``limit`` patches, in up to 10 tries; return how many it added."""
        for _ in range(10):
            area = _uniform(self.min_patches, limit, g)
            aspect = math.exp(_uniform(*self.log_aspect, g))
            h, w = round(math.sqrt(area * aspect)), round(math.sqrt(area / aspect))
            if h >= self.height or w >= self.width:
                continue
            top, left = _randint(self.height - h, g), _randint(self.width - w, g)
            block = mask[top : top + h, left : left + w]
            added = h * w - int(block.sum())
            if 0 < added <= limit:
                block.fill_(True)
                return added
        return 0

    def _mask(self, count: int, g: torch.Generator | None) -> Tensor:
        mask = torch.zeros(self.height, self.width, dtype=torch.bool)
        masked = 0
        while masked < count:
            added = self._add_block(mask, min(count - masked, self.max_patches), g)
            if added == 0:
                break
            masked += added
        return mask

    def __call__(self, batch_size: int, generator: torch.Generator | None = None) -> Tensor:
        num_masked = int(batch_size * self.probability)
        bounds = torch.linspace(*self.ratio, num_masked + 1).tolist()
        num_patches = self.height * self.width
        masks = [self._mask(int(num_patches * _uniform(lo, hi, generator)), generator) for lo, hi in pairwise(bounds)]
        masks += [torch.zeros(self.height, self.width, dtype=torch.bool)] * (batch_size - num_masked)
        order = torch.randperm(batch_size, generator=generator)
        return torch.stack(masks)[order].flatten(1)

function apply_masks ​

torch_world.masks.apply_masks GitHub

python
apply_masks(x: Tensor, masks: list[Tensor]) -> Tensor

Gather the tokens indexed by each (B, K) mask from x of shape (B, N, ...); stack masks on the batch dim.

Source code in torch_world/masks/utils.py
python
def apply_masks(x: Tensor, masks: list[Tensor]) -> Tensor:
    """Gather the tokens indexed by each ``(B, K)`` mask from ``x`` of shape ``(B, N, ...)``; stack masks on the batch dim."""
    out = []
    for m in masks:
        index = m.view(m.shape + (1,) * (x.dim() - 2)).expand(*m.shape, *x.shape[2:])
        out.append(torch.gather(x, 1, index))
    return torch.cat(out, dim=0)

function frame_causal_mask ​

torch_world.masks.frame_causal_mask GitHub

python
frame_causal_mask(
    num_frames: int,
    tokens_per_frame: int,
    window: int | None = None,
    device=None,
) -> Tensor

Boolean (N, N) mask where a token attends every token of its own frame and of the window frames before it.

Source code in torch_world/masks/utils.py
python
def frame_causal_mask(num_frames: int, tokens_per_frame: int, window: int | None = None, device=None) -> Tensor:
    """Boolean ``(N, N)`` mask where a token attends every token of its own frame and of the ``window`` frames before it."""
    t = torch.arange(num_frames, device=device).repeat_interleave(tokens_per_frame)
    lag = t[:, None] - t[None, :]
    return (lag >= 0) & (lag < (window or num_frames))

function repeat_interleave_batch ​

torch_world.masks.repeat_interleave_batch GitHub

python
repeat_interleave_batch(x: Tensor, batch_size: int, repeat: int) -> Tensor

Repeat each consecutive chunk of batch_size rows repeat times.

Source code in torch_world/masks/utils.py
python
def repeat_interleave_batch(x: Tensor, batch_size: int, repeat: int) -> Tensor:
    """Repeat each consecutive chunk of ``batch_size`` rows ``repeat`` times."""
    chunks = x.split(batch_size)
    return torch.cat([c for c in chunks for _ in range(repeat)], dim=0)