How Adaptive Slot Attention works
masterAdaptive Slot Attention allows for a dynamic number of slots by generating a differentiable one-hot mask to decide whether to use a slot. This is implemented using MultiHeadSlotAttention wrapped in an AdaptiveSlotWrapper.
Workflow:
- Define a
MultiHeadSlotAttentionmodule. - Wrap it with
AdaptiveSlotWrapper, specifying atemperature(Gumbel-softmax temperature). - The wrapper returns both the
slotsand akeep_slotstensor.
Loss Minimization:
To minimize the number of slots used for a scene (as suggested in the paper), you can add an auxiliary loss calculated as the sum of the keep_slots tensor to your main loss function.
import torch
from slot_attention import MultiHeadSlotAttention, AdaptiveSlotWrapper
# 1. Define slot attention
slot_attn = MultiHeadSlotAttention(
dim = 512,
num_slots = 5,
iters = 3,
)
# 2. Wrap the slot attention
adaptive_slots = AdaptiveSlotWrapper(
slot_attn,
temperature = 0.5 # gumbel softmax temperature
)
inputs = torch.randn(2, 1024, 512)
# 3. Forward pass returns slots and the mask
slots, keep_slots = adaptive_slots(inputs) # (2, 5, 512), (2, 5)
# 4. Auxiliary loss to minimize number of slots used
keep_aux_loss = keep_slots.sum() # add this to your main loss with some weight