File size: 2,474 Bytes
95c5a88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""PyTorch reference mixer for the original NextTransformer GSA checkpoint."""

import torch
from torch.nn import functional as F

from nexttransformer.models.backbone import Linear, norm
from nexttransformer.models.linear import LinearMixer, accumulation_dtype


class GatedSlotAttention(LinearMixer):
    def __init__(self, config, layer_index):
        super().__init__(config, layer_index, kind="gsa")
        self.slot_proj = Linear(config.width, config.heads * config.slots, bias=False)

    def forward(self, x, ve, cos_sin, window_size, kv_cache):
        if kv_cache is not None:
            raise NotImplementedError("Use full-prefix inference for Gated Slot Attention.")
        batch, length, width = x.shape
        heads, dim, slots = self.config.heads, self.config.head_dim, self.config.slots
        shape = (batch, length, heads, dim)
        query = F.silu(self.c_q(x).reshape(shape))
        key = F.silu(self.c_k(x).reshape(shape))
        value = self.c_v(x).reshape(shape)
        if ve is not None:
            gate = 3 * torch.sigmoid(self.ve_gate(x[..., :12]))
            value = value + gate.unsqueeze(-1) * ve.reshape(shape)
        value = F.silu(value)

        slot_logits = self.slot_proj(x).reshape(batch, length, heads, slots)
        forget = (F.logsigmoid(slot_logits.float()) / 8).exp()
        write = 1 - forget
        output_dtype = query.dtype
        state_dtype = accumulation_dtype(query)
        query, key, value = (tensor.to(state_dtype) for tensor in (query, key, value))
        forget, write = forget.to(state_dtype), write.to(state_dtype)
        key_slots = query.new_zeros(batch, heads, dim, slots)
        slot_values = query.new_zeros(batch, heads, slots, dim)
        outputs = []
        for t in range(length):
            retain, amount = forget[:, t], write[:, t]
            key_slots = key_slots * retain.unsqueeze(-2) + key[:, t].unsqueeze(-1) * amount.unsqueeze(-2)
            address = (query[:, t].unsqueeze(-1) * key_slots).sum(-2).softmax(-1)
            slot_values = slot_values * retain.unsqueeze(-1) + amount.unsqueeze(-1) * value[:, t].unsqueeze(-2)
            outputs.append((address.unsqueeze(-1) * slot_values).sum(-2))

        output = F.silu(torch.stack(outputs, dim=1).to(output_dtype))
        output = norm(output) * self.output_gain.to(output.dtype)
        return self.c_proj(output.reshape(batch, length, width))


def mixer(config, layer):
    return GatedSlotAttention(config, layer)