-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransformer.cpp
More file actions
245 lines (218 loc) · 9.01 KB
/
Copy pathtransformer.cpp
File metadata and controls
245 lines (218 loc) · 9.01 KB
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
#include "transformer.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <stdexcept>
namespace muscriptor {
std::vector<float> create_sin_embedding(const std::vector<int64_t>& positions,
int dim,
float max_period) {
assert(dim % 2 == 0);
int half = dim / 2;
int T = static_cast<int>(positions.size());
std::vector<float> out(static_cast<size_t>(T) * dim);
for (int t = 0; t < T; ++t) {
float pos = static_cast<float>(positions[t]);
for (int i = 0; i < half; ++i) {
float adim = static_cast<float>(i);
float phase = pos / std::pow(max_period, adim / static_cast<float>(half - 1));
out[static_cast<size_t>(t) * dim + i] = std::cos(phase);
out[static_cast<size_t>(t) * dim + half + i] = std::sin(phase);
}
}
return out;
}
void KVCache::init(int layers, int heads, int hd, int cap) {
n_layers = layers;
n_heads = heads;
head_dim = hd;
capacity = cap;
offset = 0;
k.resize(layers);
v.resize(layers);
size_t elems = static_cast<size_t>(cap) * heads * hd;
for (int i = 0; i < layers; ++i) {
k[i].assign(elems, 0.f);
v[i].assign(elems, 0.f);
}
}
namespace {
void layernorm(const float* x, int T, int D, const float* w, const float* b, float eps,
float* out) {
for (int t = 0; t < T; ++t) {
const float* row = x + static_cast<size_t>(t) * D;
float* orow = out + static_cast<size_t>(t) * D;
float mean = 0.f;
for (int d = 0; d < D; ++d) mean += row[d];
mean /= static_cast<float>(D);
float var = 0.f;
for (int d = 0; d < D; ++d) {
float diff = row[d] - mean;
var += diff * diff;
}
var /= static_cast<float>(D);
float inv = 1.f / std::sqrt(var + eps);
for (int d = 0; d < D; ++d) {
float n = (row[d] - mean) * inv;
orow[d] = n * w[d] + b[d];
}
}
}
void linear(const float* x, int T, int in_dim, int out_dim, const float* w, float* out) {
// w is [out_dim, in_dim]
for (int t = 0; t < T; ++t) {
for (int o = 0; o < out_dim; ++o) {
float sum = 0.f;
for (int i = 0; i < in_dim; ++i) {
sum += w[static_cast<size_t>(o) * in_dim + i] *
x[static_cast<size_t>(t) * in_dim + i];
}
out[static_cast<size_t>(t) * out_dim + o] = sum;
}
}
}
void gelu(float* x, size_t n) {
for (size_t i = 0; i < n; ++i) {
float v = x[i];
// tanh approximation matching PyTorch F.gelu default (none → erf, but
// torch uses erf; approximate with tanh which is close enough for tests
// with tiny models; for parity use erf)
x[i] = 0.5f * v * (1.f + std::erf(v * static_cast<float>(0.7071067811865476)));
}
}
void mha_forward(
const float* x, int T, int dim, int n_heads,
const AttnWeights& attn,
KVCache* cache, int layer_idx,
float* out) {
int head_dim = dim / n_heads;
// QKV projection
std::vector<float> qkv(static_cast<size_t>(T) * 3 * dim);
linear(x, T, dim, 3 * dim, attn.in_proj, qkv.data());
std::vector<float> q(static_cast<size_t>(T) * n_heads * head_dim);
std::vector<float> k_new(static_cast<size_t>(T) * n_heads * head_dim);
std::vector<float> v_new(static_cast<size_t>(T) * n_heads * head_dim);
// packed as b t (p h d) with p=3
for (int t = 0; t < T; ++t) {
for (int h = 0; h < n_heads; ++h) {
for (int d = 0; d < head_dim; ++d) {
size_t base = (static_cast<size_t>(t) * 3 * dim) + h * head_dim + d;
q[static_cast<size_t>(t) * n_heads * head_dim + h * head_dim + d] =
qkv[base];
k_new[static_cast<size_t>(t) * n_heads * head_dim + h * head_dim + d] =
qkv[base + dim];
v_new[static_cast<size_t>(t) * n_heads * head_dim + h * head_dim + d] =
qkv[base + 2 * dim];
}
}
}
const float* k_ptr = k_new.data();
const float* v_ptr = v_new.data();
int T_k = T;
std::vector<float> k_full, v_full;
if (cache) {
int offset = cache->offset;
// write into cache
size_t hd_stride = static_cast<size_t>(n_heads) * head_dim;
std::memcpy(cache->k[layer_idx].data() + static_cast<size_t>(offset) * hd_stride,
k_new.data(), static_cast<size_t>(T) * hd_stride * sizeof(float));
std::memcpy(cache->v[layer_idx].data() + static_cast<size_t>(offset) * hd_stride,
v_new.data(), static_cast<size_t>(T) * hd_stride * sizeof(float));
T_k = offset + T;
k_ptr = cache->k[layer_idx].data();
v_ptr = cache->v[layer_idx].data();
}
float scale = 1.f / std::sqrt(static_cast<float>(head_dim));
std::vector<float> attn_out(static_cast<size_t>(T) * n_heads * head_dim, 0.f);
// Causal attention: for each query t, attend to keys 0..t_abs
for (int h = 0; h < n_heads; ++h) {
for (int tq = 0; tq < T; ++tq) {
int abs_q = (cache ? cache->offset : 0) + tq;
// Softmax over keys 0..abs_q (bottom-right causal)
int n_keys = abs_q + 1;
if (n_keys > T_k) n_keys = T_k;
std::vector<float> scores(n_keys);
float max_s = -1e30f;
for (int tk = 0; tk < n_keys; ++tk) {
float dot = 0.f;
for (int d = 0; d < head_dim; ++d) {
float qv = q[static_cast<size_t>(tq) * n_heads * head_dim + h * head_dim + d];
float kv = k_ptr[static_cast<size_t>(tk) * n_heads * head_dim + h * head_dim + d];
dot += qv * kv;
}
scores[tk] = dot * scale;
max_s = std::max(max_s, scores[tk]);
}
float sum = 0.f;
for (int tk = 0; tk < n_keys; ++tk) {
scores[tk] = std::exp(scores[tk] - max_s);
sum += scores[tk];
}
for (int tk = 0; tk < n_keys; ++tk) scores[tk] /= sum;
for (int d = 0; d < head_dim; ++d) {
float acc = 0.f;
for (int tk = 0; tk < n_keys; ++tk) {
float vv = v_ptr[static_cast<size_t>(tk) * n_heads * head_dim + h * head_dim + d];
acc += scores[tk] * vv;
}
attn_out[static_cast<size_t>(tq) * n_heads * head_dim + h * head_dim + d] = acc;
}
}
}
// merge heads → [T, dim] then out_proj
std::vector<float> merged(static_cast<size_t>(T) * dim);
for (int t = 0; t < T; ++t) {
for (int h = 0; h < n_heads; ++h) {
for (int d = 0; d < head_dim; ++d) {
merged[static_cast<size_t>(t) * dim + h * head_dim + d] =
attn_out[static_cast<size_t>(t) * n_heads * head_dim + h * head_dim + d];
}
}
}
linear(merged.data(), T, dim, dim, attn.out_proj, out);
}
} // namespace
std::vector<float> transformer_forward(
const float* x, int T,
const TransformerConfig& cfg,
const std::vector<LayerWeights>& layers,
KVCache* cache,
int position_offset) {
if (static_cast<int>(layers.size()) != cfg.num_layers) {
throw std::runtime_error("layer count mismatch");
}
std::vector<int64_t> positions(T);
for (int t = 0; t < T; ++t) positions[t] = position_offset + t;
auto pos_emb = create_sin_embedding(positions, cfg.dim, cfg.max_period);
std::vector<float> h(static_cast<size_t>(T) * cfg.dim);
for (int t = 0; t < T; ++t) {
for (int d = 0; d < cfg.dim; ++d) {
h[static_cast<size_t>(t) * cfg.dim + d] =
x[static_cast<size_t>(t) * cfg.dim + d] +
pos_emb[static_cast<size_t>(t) * cfg.dim + d];
}
}
std::vector<float> normed(static_cast<size_t>(T) * cfg.dim);
std::vector<float> attn_out(static_cast<size_t>(T) * cfg.dim);
std::vector<float> ff_hidden(static_cast<size_t>(T) * cfg.dim_ff);
std::vector<float> ff_out(static_cast<size_t>(T) * cfg.dim);
for (int li = 0; li < cfg.num_layers; ++li) {
const auto& layer = layers[li];
// Pre-norm attention
layernorm(h.data(), T, cfg.dim, layer.norm1_w, layer.norm1_b, cfg.ln_eps, normed.data());
mha_forward(normed.data(), T, cfg.dim, cfg.num_heads, layer.attn, cache, li, attn_out.data());
for (size_t i = 0; i < h.size(); ++i) h[i] += attn_out[i];
// Pre-norm FFN
layernorm(h.data(), T, cfg.dim, layer.norm2_w, layer.norm2_b, cfg.ln_eps, normed.data());
linear(normed.data(), T, cfg.dim, cfg.dim_ff, layer.linear1, ff_hidden.data());
gelu(ff_hidden.data(), ff_hidden.size());
linear(ff_hidden.data(), T, cfg.dim_ff, cfg.dim, layer.linear2, ff_out.data());
for (size_t i = 0; i < h.size(); ++i) h[i] += ff_out[i];
}
if (cache) {
cache->offset += T;
}
return h;
}
} // namespace muscriptor