AGT / code /agt /model /mask_attention.py
MRBSTUDIO's picture
Update code and model card
fb3460f verified
Raw History Blame Contribute Delete
4.12 kB
from contextlib import contextmanager
from types import MethodType
import weakref
import torch
from torch import Tensor
import torch.nn.functional as F
from .gating import mask_for_images
class OccluderKeyMask:
def __init__(self, aggregator):
self.patch_size = aggregator.patch_size
self.patch_start_idx = aggregator.patch_start_idx
assert self.patch_start_idx == 5, 'DGGT: camera token + 4 register tokens'
self.current = None
def build(self, masks, height, width):
batch_size, num_views = masks.shape[:2]
patch_h, patch_w = height // self.patch_size, width // self.patch_size
small = F.interpolate(masks.flatten(0, 1), size=(patch_h, patch_w), mode='nearest')
small = small.view(batch_size, num_views, 1, patch_h, patch_w)
occluded = (small > 0.5).flatten(3).squeeze(2)
keys = torch.zeros(batch_size, num_views, self.patch_start_idx + occluded.shape[-1],
device=masks.device, dtype=masks.dtype)
keys[..., self.patch_start_idx:] = keys[..., self.patch_start_idx:].masked_fill(occluded, float('-inf'))
return keys
def for_tokens(self, tokens):
assert tokens.shape[:3] == self.current.shape
return self.current.flatten(1)[:, None, None, :]
def masked_attention(self, x: Tensor, pos=None):
key_mask = getattr(self, '_key_mask', None)
if key_mask is None:
return self._original_forward(x, pos=pos)
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv.unbind(0)
q, k = self.q_norm(q), self.k_norm(k)
if self.rope is not None:
q = self.rope(q, pos)
k = self.rope(k, pos)
key_mask = key_mask.to(dtype=q.dtype, device=q.device)
assert self.fused_attn, 'DGGT attention uses F.scaled_dot_product_attention'
x = F.scaled_dot_product_attention(
q, k, v, attn_mask=key_mask,
dropout_p=self.attn_drop.p if self.training else 0.0,
)
x = x.transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
def process_global(self, tokens, B, S, P, C, global_idx, pos=None):
controller = self._mask_controller()
if controller.current is None:
return self._original_global(tokens, B, S, P, C, global_idx, pos=pos)
if tokens.shape != (B, S * P, C):
tokens = tokens.view(B, S, P, C).view(B, S * P, C)
if pos is not None and pos.shape != (B, S * P, 2):
pos = pos.view(B, S, P, 2).view(B, S * P, 2)
intermediates = []
for _ in range(self.aa_block_size):
attention = self.global_blocks[global_idx].attn
attention._key_mask = controller.for_tokens(tokens.view(B, S, P, C))
try:
tokens = self.global_blocks[global_idx](tokens, pos=pos)
finally:
attention._key_mask = None
global_idx += 1
intermediates.append(tokens.view(B, S, P, C))
return tokens, global_idx, intermediates
def install(model):
if hasattr(model, '_occluder_mask'):
return model
aggregator = model.aggregator
model._occluder_mask = OccluderKeyMask(aggregator)
aggregator._mask_controller = weakref.ref(model._occluder_mask)
aggregator._original_global = aggregator._process_global_attention
aggregator._process_global_attention = MethodType(process_global, aggregator)
for block in aggregator.global_blocks:
attention = block.attn
attention._original_forward = attention.forward
attention.forward = MethodType(masked_attention, attention)
return model
@contextmanager
def mask_context(model, mask=None, images=None):
controller = getattr(model, '_occluder_mask', None)
if controller is None:
yield
return
previous = controller.current
controller.current = None
try:
if mask is not None:
mask = mask_for_images(mask, images).unsqueeze(2).float()
controller.current = controller.build(mask, *images.shape[-2:])
yield
finally:
controller.current = previous