File size: 8,006 Bytes
4ec5e47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import math

import torch
import torch.nn as nn
import torch.nn.functional as F

from transformers.modeling_outputs import (
    BaseModelOutput,
    MaskedLMOutput,
)

from transformers.models.fnet.modeling_fnet import (
    FNetEmbeddings,
    FNetIntermediate,
    FNetOnlyMLMHead,
    FNetOutput,
    FNetPreTrainedModel,
)

from .configuration_splinet import SpliNetConfig


class SplineMixer(nn.Module):
    def __init__(self, config):
        super().__init__()

        self.radius = int(
            config.splinet_radius
        )

        z = -3.0 + 2.0 * math.sqrt(2.0)

        # Fixed analytic spline coefficients.
        #
        # IMPORTANT:
        # Do NOT register these as a non-persistent tensor buffer.
        # Hugging Face low-memory/meta-device loading can materialize
        # such a buffer without its analytically initialized values.
        #
        # Store the 33 coefficients as ordinary Python floats instead.
        # They are recreated on the actual input device and dtype in
        # forward(). They are not learned model state.
        self.kernel_values = tuple(
            float(
                math.sqrt(2.0)
                * (z ** abs(k))
            )
            for k in range(
                -self.radius,
                self.radius + 1,
            )
        )

    def forward(self, x):
        if x.shape[1] != 512:
            raise ValueError(
                "This released SpliNet checkpoint was pretrained "
                "and validated on fixed 512-token blocks. "
                f"Received sequence length {x.shape[1]}. "
                "Tokenize/pack the input to exactly 512 tokens."
            )

        d = x.shape[-1]

        y = (
            x.transpose(1, 2)
            .contiguous()
        )

        y = F.pad(
            y,
            (
                self.radius,
                self.radius,
            ),
            mode="reflect",
        )

        kernel = (
            torch.tensor(
                self.kernel_values,
                device=y.device,
                dtype=y.dtype,
            )
            .view(1, 1, -1)
            .expand(d, 1, -1)
            .contiguous()
        )

        y = F.conv1d(
            y,
            kernel,
            groups=d,
        )

        return (
            y.transpose(1, 2)
            .contiguous()
        )


class SpliNetMixingBlock(nn.Module):
    def __init__(self, config):
        super().__init__()

        self.mixer = SplineMixer(
            config
        )

        self.LayerNorm = nn.LayerNorm(
            config.hidden_size,
            eps=config.layer_norm_eps,
        )

    def forward(self, x):
        return self.LayerNorm(
            x + self.mixer(x)
        )


class SpliNetLayer(nn.Module):
    def __init__(self, config):
        super().__init__()

        self.mixing = (
            SpliNetMixingBlock(
                config
            )
        )

        self.intermediate = (
            FNetIntermediate(
                config
            )
        )

        self.output = (
            FNetOutput(
                config
            )
        )

    def forward(self, x):
        x = self.mixing(x)

        return self.output(
            self.intermediate(x),
            x,
        )


class SpliNetEncoder(nn.Module):
    def __init__(self, config):
        super().__init__()

        self.layer = nn.ModuleList(
            [
                SpliNetLayer(config)
                for _ in range(
                    config.num_hidden_layers
                )
            ]
        )

    def forward(
        self,
        x,
        output_hidden_states=False,
    ):
        hidden_states = (
            ()
            if output_hidden_states
            else None
        )

        for layer in self.layer:
            if output_hidden_states:
                hidden_states += (x,)

            x = layer(x)

        if output_hidden_states:
            hidden_states += (x,)

        return BaseModelOutput(
            last_hidden_state=x,
            hidden_states=hidden_states,
        )


class SpliNetModel(FNetPreTrainedModel):
    config_class = SpliNetConfig
    base_model_prefix = "splinet"

    def __init__(self, config):
        super().__init__(config)

        self.embeddings = (
            FNetEmbeddings(config)
        )

        self.encoder = (
            SpliNetEncoder(config)
        )

        self.post_init()

    def get_input_embeddings(self):
        return (
            self.embeddings
            .word_embeddings
        )

    def set_input_embeddings(
        self,
        value,
    ):
        self.embeddings.word_embeddings = value

    def forward(
        self,
        input_ids=None,
        token_type_ids=None,
        position_ids=None,
        inputs_embeds=None,
        output_hidden_states=False,
        **kwargs,
    ):
        if input_ids is not None:
            shape = input_ids.shape
            device = input_ids.device

        elif inputs_embeds is not None:
            shape = inputs_embeds.shape[:-1]
            device = inputs_embeds.device

        else:
            raise ValueError(
                "input_ids or inputs_embeds required."
            )

        if shape[1] != 512:
            raise ValueError(
                "This SpliNet checkpoint requires exactly "
                f"512 tokens; received {shape[1]}."
            )

        if token_type_ids is None:
            token_type_ids = torch.zeros(
                shape,
                dtype=torch.long,
                device=device,
            )

        x = self.embeddings(
            input_ids=input_ids,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            inputs_embeds=inputs_embeds,
        )

        return self.encoder(
            x,
            output_hidden_states=output_hidden_states,
        )


class SpliNetForMaskedLM(FNetPreTrainedModel):
    config_class = SpliNetConfig
    base_model_prefix = "splinet"

    _tied_weights_keys = {
        "cls.predictions.decoder.bias":
            "cls.predictions.bias",

        "cls.predictions.decoder.weight":
            "splinet.embeddings.word_embeddings.weight",
    }

    def __init__(self, config):
        super().__init__(config)

        self.splinet = (
            SpliNetModel(config)
        )

        self.cls = (
            FNetOnlyMLMHead(config)
        )

        self.post_init()

        if config.tie_word_embeddings:
            (
                self.cls
                .predictions
                .decoder.weight
            ) = (
                self.splinet
                .embeddings
                .word_embeddings
                .weight
            )

    def get_input_embeddings(self):
        return (
            self.splinet
            .embeddings
            .word_embeddings
        )

    def set_input_embeddings(
        self,
        value,
    ):
        (
            self.splinet
            .embeddings
            .word_embeddings
        ) = value

    def get_output_embeddings(self):
        return (
            self.cls
            .predictions
            .decoder
        )

    def set_output_embeddings(
        self,
        value,
    ):
        self.cls.predictions.decoder = value

    def forward(
        self,
        input_ids=None,
        labels=None,
        **kwargs,
    ):
        out = self.splinet(
            input_ids=input_ids,
            **kwargs,
        )

        logits = self.cls(
            out.last_hidden_state
        )

        loss = None

        if labels is not None:
            loss = F.cross_entropy(
                logits.reshape(
                    -1,
                    self.config.vocab_size,
                ),
                labels.reshape(-1),
                ignore_index=-100,
            )

        return MaskedLMOutput(
            loss=loss,
            logits=logits,
            hidden_states=out.hidden_states,
        )