-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathops.cpp
More file actions
71 lines (57 loc) · 1.82 KB
/
Copy pathops.cpp
File metadata and controls
71 lines (57 loc) · 1.82 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
#include "ops.hpp"
#include <cfloat>
#include <cmath>
void rmsnorm(float *out, const float *x, const float *weight, int n,
float eps) {
double sum = 0.0f;
for (int i = 0; i < n; i++)
sum += static_cast<double>(x[i]) * static_cast<double>(x[i]);
float scale = 1.0f / sqrtf(static_cast<float>((sum / n)) + eps);
for (int i = 0; i < n; i++)
out[i] = x[i] * scale * weight[i];
}
static void rope_rotation(float *row, int position, int n, int d, int theta) {
for (int i = 0; i < n; i++) {
float freq =
1.0f / powf(theta, static_cast<float>(2 * i) / static_cast<float>(d));
float angle = position * freq;
float cos_a = cosf(angle);
float sin_a = sinf(angle);
float q0 = row[i], q1 = row[i + n];
row[i] = q0 * cos_a - q1 * sin_a;
row[i + n] = q0 * sin_a + q1 * cos_a;
}
}
void rope(float *q, float *k, int head_dim, int n_heads, int n_kv_heads,
int pos, int theta) {
int mid = head_dim / 2;
for (int h = 0; h < n_heads; h++) {
float *q_values = q + h * head_dim;
rope_rotation(q_values, pos, mid, head_dim, theta);
}
for (int h = 0; h < n_kv_heads; h++) {
float *k_values = k + h * head_dim;
rope_rotation(k_values, pos, mid, head_dim, theta);
}
}
void softmax(float *x, int n) {
float max_x = -FLT_MAX, sum = 0.0f;
for (int i = 0; i < n; i++)
max_x = fmaxf(max_x, x[i]);
for (int i = 0; i < n; i++)
sum += expf(x[i] - max_x);
for (int i = 0; i < n; i++)
x[i] = expf(x[i] - max_x) / sum;
}
void silu(float *x, int n) {
for (int i = 0; i < n; i++)
x[i] = x[i] / (1.0f + expf(-x[i]));
}
void mul(float *out, const float *a, const float *b, int n) {
for (int i = 0; i < n; i++)
out[i] = a[i] * b[i];
}
void add(float *out, const float *a, const float *b, int n) {
for (int i = 0; i < n; i++)
out[i] = a[i] + b[i];
}