File size: 10,537 Bytes
d4279d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
"""EEG codec: causal SEANet encoder -> causal transformer -> stride-2 conv -> 16-level RVQ -> mirror-image decoder.

    input_values [B, 41, T] microvolts @ 120 Hz
      -> / scale_uv, clip +-8 (the model's own front end)
      -> latent [B, 256, T / 4]  (30 frames/s, causal)
      -> eeg_codes [B, num_quantizers, T / 4]  (10 bits each)
      -> eeg_values [B, 41, T] microvolts

Every convolution and attention is causal, so the codec streams: a frame depends only on the signal up to its end.
Inference-only re-implementation of the training code; weight norm is folded into plain weights and each codebook is stored as its
centroid matrix. Outputs match the training code to float precision (see the model card's parity test).
"""
import math
from dataclasses import dataclass
from typing import Optional

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel
from transformers.utils import ModelOutput

from .configuration_eeg import EEGCodecConfig


class CausalConv1d(nn.Module):
    def __init__(self, cin, cout, k, stride=1, dilation=1):
        super().__init__()
        self.conv = nn.Conv1d(cin, cout, k, stride=stride, dilation=dilation)
        self.stride = stride
        self.pad = (k - 1) * dilation + 1 - stride

    def forward(self, x):
        T = x.shape[-1]
        n_frames = math.ceil(T / self.stride)
        extra = (n_frames - 1) * self.stride + (self.pad + self.stride) - (T + self.pad)
        return self.conv(F.pad(x, (self.pad, max(extra, 0))))


class CausalConvT1d(nn.Module):
    def __init__(self, cin, cout, k, stride):
        super().__init__()
        self.conv = nn.ConvTranspose1d(cin, cout, k, stride=stride)
        self.trim = k - stride

    def forward(self, x):
        y = self.conv(x)
        return y[..., : y.shape[-1] - self.trim] if self.trim else y


class ResBlock(nn.Module):
    def __init__(self, dim, dilation):
        super().__init__()
        h = dim // 2
        self.block = nn.Sequential(nn.ELU(), CausalConv1d(dim, h, 3, dilation=dilation), nn.ELU(), CausalConv1d(h, dim, 1))

    def forward(self, x):
        return x + self.block(x)


class SEANetEncoder(nn.Module):
    def __init__(self, channels, dim, n_filters, ratios):
        super().__init__()
        layers = [CausalConv1d(channels, n_filters, 7)]
        c = n_filters
        for r in ratios:
            layers += [ResBlock(c, 1), nn.ELU(), CausalConv1d(c, 2 * c, 2 * r, stride=r)]
            c *= 2
        layers += [nn.ELU(), CausalConv1d(c, dim, 3)]
        self.net = nn.Sequential(*layers)

    def forward(self, x):
        return self.net(x)


class SEANetDecoder(nn.Module):
    def __init__(self, channels, dim, n_filters, ratios):
        super().__init__()
        c = n_filters * 2 ** len(ratios)
        layers = [CausalConv1d(dim, c, 7)]
        for r in ratios:
            layers += [nn.ELU(), CausalConvT1d(c, c // 2, 2 * r, stride=r)]
            c //= 2
            layers += [ResBlock(c, 1)]
        layers += [nn.ELU(), CausalConv1d(c, channels, 7)]
        self.net = nn.Sequential(*layers)

    def forward(self, z):
        return self.net(z)


def _rope(q, k):
    T, hd = q.shape[-2], q.shape[-1]
    inv = 1.0 / (10000 ** (torch.arange(0, hd, 2, device=q.device).float() / hd))
    f = torch.outer(torch.arange(T, device=q.device).float(), inv)
    cos, sin = f.cos().to(q.dtype), f.sin().to(q.dtype)

    def rot(x):
        x1, x2 = x[..., ::2], x[..., 1::2]
        return torch.stack((x1 * cos - x2 * sin, x1 * sin + x2 * cos), -1).flatten(-2)
    return rot(q), rot(k)


class TLayer(nn.Module):
    def __init__(self, d, heads, ff):
        super().__init__()
        self.h = heads
        self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.qkv, self.out = nn.Linear(d, 3 * d, bias=False), nn.Linear(d, d, bias=False)
        self.ff = nn.Sequential(nn.Linear(d, ff, bias=False), nn.GELU(), nn.Linear(ff, d, bias=False))
        self.s1 = nn.Parameter(torch.full((d,), 0.01))
        self.s2 = nn.Parameter(torch.full((d,), 0.01))

    def forward(self, x, mask):
        B, T, D = x.shape
        q, k, v = self.qkv(self.n1(x)).view(B, T, 3, self.h, D // self.h).permute(2, 0, 3, 1, 4)
        q, k = _rope(q, k)
        a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
        x = x + self.s1 * self.out(a.transpose(1, 2).reshape(B, T, D))
        return x + self.s2 * self.ff(self.n2(x))


class CausalTransformer(nn.Module):
    """Causal RoPE transformer over [B, D, T] with an attention context of `context` frames."""

    def __init__(self, d, layers, heads, ff, context):
        super().__init__()
        self.context = context
        self.layers = nn.ModuleList(TLayer(d, heads, ff) for _ in range(layers))

    def forward(self, x):
        x = x.transpose(1, 2)
        i = torch.arange(x.shape[1], device=x.device)
        mask = (i[None, :] <= i[:, None]) & (i[:, None] - i[None, :] < self.context)
        for layer in self.layers:
            x = layer(x, mask)
        return x.transpose(1, 2)


class Codebook(nn.Module):
    def __init__(self, dim, size):
        super().__init__()
        self.register_buffer("embed", torch.zeros(size, dim))

    def encode(self, x):
        return torch.cdist(x, self.embed).argmin(-1)

    def decode(self, codes):
        return F.embedding(codes, self.embed)


class RVQ(nn.Module):
    def __init__(self, in_dim, dim, n_q, size):
        super().__init__()
        self.n_q = n_q
        self.proj_in = nn.Conv1d(in_dim, dim, 1)
        self.proj_out = nn.Conv1d(dim, in_dim, 1)
        self.books = nn.ModuleList(Codebook(dim, size) for _ in range(n_q))

    def encode(self, z, n_q):
        x = self.proj_in(z.float())
        B, D, T = x.shape
        r = x.transpose(1, 2).reshape(-1, D)
        out = []
        for cb in self.books[:n_q]:
            c = cb.encode(r)
            r = r - cb.decode(c)
            out.append(c)
        return torch.stack(out, 1).view(B, T, -1).transpose(1, 2)

    def decode(self, codes, levels=None):
        """codes [B, L, T]; `levels` (indices into the L rows) sums only those levels, e.g. [0] = the first level alone."""
        B, L, T = codes.shape
        levels = range(L) if levels is None else levels
        q = sum(self.books[i].decode(codes[:, i].reshape(-1)) for i in levels)
        return self.proj_out(q.view(B, T, -1).transpose(1, 2))


@dataclass
class EEGCodecEncoderOutput(ModelOutput):
    """eeg_codes [B, num_quantizers, frames] (int64, 0-1023); latent [B, 256, frames], the continuous pre-quantizer latent."""
    eeg_codes: Optional[torch.LongTensor] = None
    latent: Optional[torch.FloatTensor] = None


@dataclass
class EEGCodecDecoderOutput(ModelOutput):
    """eeg_values [B, 41, T] microvolts."""
    eeg_values: Optional[torch.FloatTensor] = None


@dataclass
class EEGCodecOutput(ModelOutput):
    eeg_values: Optional[torch.FloatTensor] = None
    eeg_codes: Optional[torch.LongTensor] = None
    latent: Optional[torch.FloatTensor] = None


class EEGCodecPreTrainedModel(PreTrainedModel):
    config_class = EEGCodecConfig
    base_model_prefix = "codec"
    main_input_name = "input_values"

    def _init_weights(self, module):
        pass  # every weight comes from the checkpoint


class EEGCodecModel(EEGCodecPreTrainedModel):
    def __init__(self, config: EEGCodecConfig):
        super().__init__(config)
        c = config
        self.encoder = SEANetEncoder(c.channels, c.dim, c.n_filters, c.ratios)
        self.enc_tf = CausalTransformer(c.dim, c.t_layers, c.t_heads, c.t_ff, c.context)
        self.down = CausalConv1d(c.dim, c.dim, 4, stride=2)
        self.quantizer = RVQ(c.dim, c.codebook_dim, c.n_q, c.codebook_size)
        self.up = CausalConvT1d(c.dim, c.dim, 4, stride=2)
        self.dec_tf = CausalTransformer(c.dim, c.t_layers, c.t_heads, c.t_ff, c.context)
        self.decoder = SEANetDecoder(c.channels, c.dim, c.n_filters, c.ratios)
        self.post_init()

    @property
    def frame_rate(self):
        return self.config.frame_rate

    def front(self, x):
        """Microvolts -> model units (divide by scale_uv, clip at +-clip). Sites a recording lacks must be zero."""
        return (x / self.config.scale_uv).clamp(-self.config.clip, self.config.clip)

    def get_latent(self, input_values):
        """[B, 41, T] microvolts -> continuous latent [B, 256, ceil(T / 4)] (what the encoder reads)."""
        return self.down(self.enc_tf(self.encoder(self.front(input_values))))

    def _decode_latent(self, zq, length=None):
        x = self.decoder(self.dec_tf(self.up(zq))) * self.config.scale_uv
        return x if length is None else x[..., :length]

    @torch.no_grad()
    def encode(self, input_values, num_quantizers: Optional[int] = None, return_dict: bool = True):
        """[B, 41, T] microvolts -> eeg_codes [B, num_quantizers, frames] (+ the continuous latent). num_quantizers 1-16 sets the
        bitrate: 0.3 kbps per level."""
        n = num_quantizers or self.config.n_q
        z = self.get_latent(input_values)
        codes = self.quantizer.encode(z, n)
        return EEGCodecEncoderOutput(codes, z) if return_dict else (codes, z)

    @torch.no_grad()
    def decode(self, eeg_codes, length: Optional[int] = None, return_dict: bool = True):
        """eeg_codes [B, L, frames] (any number of leading levels L) -> eeg_values [B, 41, frames * 4] microvolts, cut to `length`."""
        x = self._decode_latent(self.quantizer.decode(eeg_codes), length)
        return EEGCodecDecoderOutput(x) if return_dict else (x,)

    @torch.no_grad()
    def dequantize(self, eeg_codes, levels=None):
        """eeg_codes -> the latent a decoder rebuilds from them [B, 256, frames]; `levels` picks a subset of the levels."""
        return self.quantizer.decode(eeg_codes, levels)

    def forward(self, input_values, num_quantizers: Optional[int] = None, return_dict: bool = True):
        """Encode then decode. num_quantizers=0 skips quantization (the decoder on the continuous latent: the codec's best fidelity)."""
        T = input_values.shape[-1]
        z = self.get_latent(input_values)
        if num_quantizers == 0:
            q = self.quantizer
            x, codes = self._decode_latent(q.proj_out(q.proj_in(z.float())), T), None
        else:
            codes = self.quantizer.encode(z, num_quantizers or self.config.n_q)
            x = self._decode_latent(self.quantizer.decode(codes), T)
        return EEGCodecOutput(x, codes, z) if return_dict else (x, codes, z)