File size: 6,448 Bytes
818282c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Inference-only Wisp architecture for the packaged MTP reference runtime.

This file intentionally contains no checkpoint, training, loss, data, or
release-repository dependencies.  Ship it beside ``wisp_mtp_reference.py`` in
the Hugging Face package.  Its parameter tree is identical to the training
model's inference tree.
"""

from __future__ import annotations

from dataclasses import dataclass

import mlx.core as mx
import mlx.nn as nn


@dataclass(frozen=True)
class ModelArgs:
    vocab_size: int
    dim: int
    n_layers: int
    n_heads: int
    n_kv_heads: int
    ffn_hidden: int
    max_seq_len: int
    rope_theta: float
    norm_eps: float
    tie_embeddings: bool
    mtp_layers: int
    mtp_depth: int
    ce_chunk: int = 0

    @property
    def head_dim(self) -> int:
        return self.dim // self.n_heads


def causal_mask(length: int, dtype=mx.float32) -> mx.array:
    """Return Wisp's additive square causal mask."""

    upper = mx.triu(mx.ones((length, length), dtype=mx.bool_), k=1)
    return mx.where(
        upper,
        mx.array(-1e9, dtype=dtype),
        mx.array(0.0, dtype=dtype),
    )


class Attention(nn.Module):
    def __init__(self, args: ModelArgs):
        super().__init__()
        self.n_heads = args.n_heads
        self.n_kv_heads = args.n_kv_heads
        self.head_dim = args.head_dim
        self.scale = self.head_dim**-0.5
        self.wq = nn.Linear(
            args.dim,
            args.n_heads * args.head_dim,
            bias=False,
        )
        self.wk = nn.Linear(
            args.dim,
            args.n_kv_heads * args.head_dim,
            bias=False,
        )
        self.wv = nn.Linear(
            args.dim,
            args.n_kv_heads * args.head_dim,
            bias=False,
        )
        self.wo = nn.Linear(
            args.n_heads * args.head_dim,
            args.dim,
            bias=False,
        )
        self.rope = nn.RoPE(
            args.head_dim,
            traditional=False,
            base=args.rope_theta,
        )

    def __call__(self, x, mask=None, cache=None):
        batch, length, _ = x.shape
        query = self.wq(x).reshape(
            batch,
            length,
            self.n_heads,
            self.head_dim,
        )
        key = self.wk(x).reshape(
            batch,
            length,
            self.n_kv_heads,
            self.head_dim,
        )
        value = self.wv(x).reshape(
            batch,
            length,
            self.n_kv_heads,
            self.head_dim,
        )
        query = query.transpose(0, 2, 1, 3)
        key = key.transpose(0, 2, 1, 3)
        value = value.transpose(0, 2, 1, 3)

        offset = 0 if cache is None else cache[0].shape[2]
        query = self.rope(query, offset=offset)
        key = self.rope(key, offset=offset)
        if cache is not None:
            key = mx.concatenate([cache[0], key], axis=2)
            value = mx.concatenate([cache[1], value], axis=2)
        new_cache = (key, value)

        output = mx.fast.scaled_dot_product_attention(
            query,
            key,
            value,
            scale=self.scale,
            mask=mask,
        )
        output = output.transpose(0, 2, 1, 3).reshape(
            batch,
            length,
            -1,
        )
        return self.wo(output), new_cache


class FeedForward(nn.Module):
    def __init__(self, args: ModelArgs):
        super().__init__()
        self.w1 = nn.Linear(args.dim, args.ffn_hidden, bias=False)
        self.w3 = nn.Linear(args.dim, args.ffn_hidden, bias=False)
        self.w2 = nn.Linear(args.ffn_hidden, args.dim, bias=False)

    def __call__(self, value):
        return self.w2(nn.silu(self.w1(value)) * self.w3(value))


class Block(nn.Module):
    def __init__(self, args: ModelArgs):
        super().__init__()
        self.attn_norm = nn.RMSNorm(args.dim, eps=args.norm_eps)
        self.attn = Attention(args)
        self.ffn_norm = nn.RMSNorm(args.dim, eps=args.norm_eps)
        self.ffn = FeedForward(args)

    def __call__(self, value, mask=None, cache=None):
        attention, new_cache = self.attn(
            self.attn_norm(value),
            mask,
            cache,
        )
        value = value + attention
        value = value + self.ffn(self.ffn_norm(value))
        return value, new_cache


class MTPModule(nn.Module):
    def __init__(self, args: ModelArgs):
        super().__init__()
        self.h_norm = nn.RMSNorm(args.dim, eps=args.norm_eps)
        self.e_norm = nn.RMSNorm(args.dim, eps=args.norm_eps)
        self.proj = nn.Linear(2 * args.dim, args.dim, bias=False)
        self.blocks = [Block(args) for _ in range(args.mtp_layers)]

    def __call__(self, hidden, token_embeddings, mask=None, caches=None):
        value = mx.concatenate(
            [
                self.h_norm(hidden),
                self.e_norm(token_embeddings),
            ],
            axis=-1,
        )
        value = self.proj(value)
        new_caches = []
        for index, block in enumerate(self.blocks):
            cache = None if caches is None else caches[index]
            value, new_cache = block(value, mask, cache)
            new_caches.append(new_cache)
        return value, new_caches


class Wisp(nn.Module):
    def __init__(self, args: ModelArgs):
        super().__init__()
        self.args = args
        self.tok_emb = nn.Embedding(args.vocab_size, args.dim)
        self.blocks = [Block(args) for _ in range(args.n_layers)]
        self.norm = nn.RMSNorm(args.dim, eps=args.norm_eps)
        if not args.tie_embeddings:
            self.lm_head = nn.Linear(args.dim, args.vocab_size, bias=False)
        self.mtp = MTPModule(args)

    def head(self, hidden):
        normalized = self.norm(hidden)
        if self.args.tie_embeddings:
            return self.tok_emb.as_linear(normalized)
        return self.lm_head(normalized)

    def trunk(self, tokens, mask=None, caches=None):
        hidden = self.tok_emb(tokens)
        new_caches = []
        for index, block in enumerate(self.blocks):
            cache = None if caches is None else caches[index]
            hidden, new_cache = block(hidden, mask, cache)
            new_caches.append(new_cache)
        return hidden, new_caches

    def __call__(self, tokens, mask=None, caches=None):
        hidden, new_caches = self.trunk(tokens, mask, caches)
        return self.head(hidden), hidden, new_caches